1662 Commits
Author SHA1 Message Date
Eric Callahan d549af915f docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 19:56:30 -05:00
Eric Callahan 672c223cc6 docs: update README with a link to the changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 19:55:37 -05:00
Eric Callahan 68c5fb6f6b git_deploy: strip comments when parsing python reqs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:52 -05:00
Eric Callahan fce056e481 file_manager: fix notification sync on fast machines
Desktop class PCs may exit the request before the inotify observer
gains control of the loop.  When the observer does gain control
it will immediately notify as the sync mutex is no longer held,
this can result in sending  the websocket notification before
the response has returned.  Delay all notifications by 5ms to prevent
this.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:51 -05:00
Eric Callahan a02209443e server: remove duplicates when loading components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:51 -05:00
Eric Callahan 2cda75ff2c utils: simplify sentinel object
Use an enum to represent the sentinel rather than a singleton object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan 0e80e301f0 button: remove stale sentinel import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan e32fd688e4 moonraker: correct stale annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan 5a504243df app: use Jinja2 to render the welcome landing page
Read the template using the "source_info" utility, which
uses a zip-safe method to read a file.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:49 -05:00
Eric Callahan 7520d0e7b1 install: update script to set PYTHONPATH env var
This is preferable to setting the WorkingDirectory item in
the systemd unit, as its possible to switch between git repos
and installed wheels without requiring root.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:49 -05:00
Eric Callahan 5ffd18d132 machine: update install validation to use package
If the "moonraker" entry point is available use it as an executable.  Otherwise
launch the module through the "-m" switch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:48 -05:00
Eric Callahan 79467e6484 utils: add source_info utility module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:48 -05:00
Eric Callahan 277aecd305 moonraker: convert utils.py to a package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:47 -05:00
Eric Callahan f48c18bfda utils: add support for package version retreival
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:47 -05:00
Eric Callahan a3121775fc build: add initial support for pdm build
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:46 -05:00
Eric Callahan a5790d4b84 install: add moonraker system deps json file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:41:57 -05:00
Eric Callahan b50057c3ba install: remove dependency on pycurl
Moonraker no longer uses the curl http client backend.  The curl
commandline client is still used in some scripts and thus has been
retained.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:28 -05:00
Eric Callahan 15f37827a1 test: fix imports
The tests are stale and will not run successfully against the current
code.  This will be addressed in a future series of patches.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:27 -05:00
Eric Callahan 0f8638fec7 components: correct imports
All imports must now be relative to work correctly with the
moonraker parent package.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:27 -05:00
Eric Callahan b9a17e07e9 moonraker: convert code to a package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:26 -05:00
Eric Callahan a5d63db9a6 server: rename moonraker.py to server.py
Signed-off-by:  Eric Callahan <arksiine.code@gmail.com>
2023-02-21 18:05:01 -05:00
Eric Callahan 1e7be4598c docs: add a changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 16:54:29 -05:00
Eric Callahan 833519ecc3 docs: update file_manager documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 12:24:54 -05:00
Eric Callahan dce3b9eaf5 file_manager: add metadata scan endpoint
Support manual scan requests for systems where inotify
does not function correctlly (network shares).  This endpoint
may also be used to force a rescan of files that have already
had an initial scan.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 12:10:56 -05:00
Eric Callahan 9178b3833c file_manager: improve observer log message
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 07:33:45 -05:00
Eric Callahan 522fdab63d metadata: simplify the S3Dv5 temp regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 06:24:17 -05:00
Eric Callahan 7845390dd1 file_manager: support uploading to symlinks
Previously Moonraker disabled writing to symbolic links, as
doing so would overwrite the link.  Moonraker now resolves
the link, overwrites the file, and manually emits a websocket
notification.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-20 20:42:19 -05:00
Eric Callahan 0f7b781f57 file_manager: process metadata changes when no observer is configured
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:49:48 -05:00
Eric Callahan 347c9f4d2b file_manager: improve duplicate notifcation detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:58 -05:00
Eric Callahan 2fd668bf0d file_manager: implement configurable fs observer
Currently the choices are "none" and "inotify".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:58 -05:00
Eric Callahan 1e97571aa8 file_manager: refactor attribute names
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:57 -05:00
Eric Callahan 7330c2c123 file_manager: add request notifcation fallback
Schedule fallback websocket notifications in the event that
inotify is unable to watch a file system.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:57 -05:00
Eric Callahan 51e307dbd6 file_manager: don't queue "create from move" events
Treat these events as if they were actual file write events.  They
will reset the node completion time and suppress the notifcation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:56 -05:00
Christian Speich 45506647a7 metadata: Add support for Simplify3D v5
Signed-off-by: Christian Speich <christian@spei.ch>
2023-02-20 19:35:37 -05:00
Eric Callahan 3917c9cd56 docs: fix minor typos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 17:47:39 -05:00
Morton Jonuschat b2ba52ce3d sensor: add support to track generic single value sensors
This feature implements a sensor component that can be used to
track/log generic sensors from multiple sources. Each sensor
can have properties like unit of measurement, accuracy and a
display name that help frontends display the tracked measurements.


Signed-off-by: Morton Jonuschat <mjonuschat+moonraker@gmail.com>
2023-02-20 17:43:41 -05:00
Eric Callahan 0a811b9e44 file_manager: cleanup coroutines on close
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 16:40:31 -05:00
Eric Callahan 36de982692 docs: document file manager API fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 15:04:04 -05:00
Eric Callahan a8c82b4560 moonraker: bump API version for patch
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 14:28:18 -05:00
Eric Callahan 7dac9c3961 file_manager: queue move event notifications
It is possible for a move event to occur shortly after a directory
is created.  These events are not bundled as part of an operation
like "copy", so they should not be suppressed, however the
notification should be emitted after the "create_dir" from its
parent is emitted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 12:29:10 -05:00
Eric Callahan d39792b84e file_manager: allow concurrent inotify processing
All of the awaitable calls in the inotify loop only block to
postpone notifications.  Only gcode notifications require async
processing due to metadata analysis.  Queue these notifications
while allowing inotify events to be received concurrently.

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

fix
2023-02-17 08:24:55 -05:00
Eric Callahan 9f08aad6f6 file_manager: improve notification sync
Most requests do not require waiting for inotify to process the
file event before exiting.  Rework the NotifySyncLock to make this
optional.  Replace the write mutex with the sync lock itself,
a guarantee that the synchronization state is cleaned up when
a request is complete.

This implementation avoids potential deadlocks or long wait times
when inotify is not enabled on a file system.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-16 19:37:34 -05:00
Eric Callahan 87dba2f2e2 template: handle render exceptions
Re-raise as either a ServerError or ConfigError as appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-14 14:13:06 -05:00
Eric Callahan a40dae2bc8 file_manager: improve klipper config detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-13 15:33:04 -05:00
Eric Callahan bec9a66411 klippy_connection: fix regression in state reporting
Moonraker should only force the state to report as "startup"
when Klippy is connected and it hasn't detected a transition
to startup.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:18 -05:00
Eric Callahan dbd1b4ac1b github: increase the max line length to 88 characters
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:17 -05:00
Eric Callahan 9b9a6d0646 http_client: remove escape_url method
This method will not work correctly if any individual part contains
a special character.  For example, if an item in the path contains
a "#", the regex will return an incorrect result.  Likewise, if any item
in a query string contains an "&" the query string will be correctly
escaped.

All urls supplied to the http client must be escaped by the consumer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:17 -05:00
Eric Callahan 0b4e604c95 webcam: remove call to escape_url
The configured url should already be escaped.  It isn't possible to
reliably quote a full url if any of the parts contain special characters.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:16 -05:00
Eric Callahan 5661b0216c simplyprint: remove call to escape_url
The url received from SimplyPrint should already be escaped.  It
isn't possibly to reliably quote a full url if any of the parts contain
special characters.

This commit also corrects some minor type checking issues.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:16 -05:00
Eric Callahan 55ebe120c5 power: resolve url encoding issues
Dynamic parts of the url must be encoded individually to
guarantee correct url generation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:15 -05:00
cmerkle 0de712e822 power: add support for Hue device groups
Signed-off-by: Clayton Merkle <clay.merkle@gmail.com>
2023-02-09 11:15:27 -05:00
Eric Callahan 5325693ed6 machine: report provider in system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 17:44:57 -05:00
Eric Callahan 8c7b93c6dd machine: fix supervisord active state reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 17:00:39 -05:00
Eric Callahan 25d2ad4af6 docs: update SimplyPrint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 16:34:18 -05:00
Eric Callahan 3710d49f46 docs: various small updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 16:32:45 -05:00
Eric Callahan c5c6366a84 docs: document shutdown_action option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 11:11:35 -05:00
Eric Callahan ea4ec1f424 scripts: add halt polkit rules
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 11:11:34 -05:00
Eric Callahan 8010f1dda2 machine: add shutdown action option
Signed-off-by:  Eric Callahan <arkisne.code@gmail.com>
2023-02-08 11:11:34 -05:00
Eric Callahan f0b82afde4 machine: remove unnecessary supervisord handlers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 06:02:25 -05:00
Eric Callahan 645f0c9acf machine: add container detection logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 06:00:01 -05:00
Eric Callahan d70dfaeebd docs: update machine config documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 05:42:30 -05:00
Eric Callahan b02224485e machine: rename supervisord provider
This is a cli providers, so rename it to supervisord_cli.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 05:36:57 -05:00
Eric Callahan d9579c9374 shell_command: allow optional success codes
Some commands may return codes other than zero on a successful
return.  Allow callers to specify an optional list of return codes that
will return success without raising an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:18 -05:00
Eric Callahan c69441955a machine: support supervisord service info extraction
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 5aa645f974 machine: simplify extract_service_info() call
Don't require the caller to specifiy properties, use the default
property list if not specified.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 2fb136449a machine: fix supervisorctl command arguments
According to the supervisord documentation the `-c` option is used to
specify the configuraiton file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 8335906443 machine: automate supervisord process init
Don't hardcode klipper and moonraker, detect them along with all other
allowed services.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:16 -05:00
Eric Callahan 5807757efa Revert "announcements: enable dev_mode when the debug flag is set"
This reverts commit 83e0947d31.
2023-02-07 19:09:14 -05:00
Eric Callahan 0db655b9d6 github: update lint workflow
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:29:37 -05:00
Eric Callahan 385b9a1b7a update_manager: handle rev-list on tagless repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:20:08 -05:00
Eric Callahan d75831f10a update_manager: require at least two parts in a tag
Allowing only a single part in the regex resulted in repos
without tags being assigned erronous version info.  With
this change, the following tags can be parsed:

v1.0
v1.0.2
1.0
1.0.2

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:09:50 -05:00
Eric Callahan c331c5a7d7 update_manager: fix semver conversion
When converting a semantic version to a list for comparisons
guarantee that the base version has 3 parts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 10:28:36 -05:00
Eric Callahan 4ff7a50821 update_manager: relax semantic tag requirement
Allow tags versions with one, two, or three parts.  The following
examples are now valid:

v1
v1.3
v1.0,10

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 08:06:13 -05:00
Eric Callahan 90c7b80f37 docs: add bridge socket documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 19:55:36 -05:00
Eric Callahan 83e0947d31 announcements: enable dev_mode when the debug flag is set
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-06 18:12:29 -05:00
Eric Callahan 4af483c786 database: remove unnecessary BytesIO conversion
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 15:22:46 -05:00
Eric Callahan 559df5aea1 websockets: implement websocket-klippy bridge
Provide a new websocket implementation that creates a near one to one
bridge with a Unix Socket connection to Klippy.  This may be used to
access Klippy APIs not otherwise available over the primary websocket,
such as the various "dump" commands.

Unlike the primary websocket Moonraker does not decode or inspect
data that passes through the bridge.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 15:22:45 -05:00
Eric Callahan f9086181b8 moonraker: bump API version to 1.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 11:24:17 -05:00
Eric Callahan 198bff6aba docs: update_manger documenation change
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 11:17:26 -05:00
Eric Callahan 01977c8775 update_manager: refactoring
Code style and naming convention improvements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 07:50:08 -05:00
Eric Callahan c8ad69b902 update_manager: add individual refresh endpoint
This endpoint allows clients to refresh items on an individual basis
when the "name" parameter is specified.  This endpoint replaces

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 06:42:56 -05:00
Eric Callahan f50fa3c5e7 update_manager: add package resolution check to apt backend
Make sure packages within the package list exist prior to installation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:54 -05:00
Eric Callahan 21a7928ea2 update_manager: pip improvements
Re-implement pip updates using a pinned version.  A version
check is now always done prior to installing python requirements,
updating when necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:54 -05:00
Eric Callahan 76500fe9f9 update_manager: improve dependency detection
Parse system packages and python requirements prior to and after each
updating, using the difference to determine if an update is necessary.
Only the new detected packages are installed unless the "force" variable
is set.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:53 -05:00
Eric Callahan a413f4e4cd websockets: guarantee subscription removal
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-04 16:46:03 -05:00
Eric Callahan 1be19be747 klippy_connection: rework klippy initialization
Handle a race condition where a shutdown event could be received
from the webhooks subscription during initialization.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-04 16:43:35 -05:00
Quinn Damerell babf97be3b Adding OctoEverywhere to the default service list
module: Adding OctoEverywhere to the default service list.

Adding OctoEverywhere to the default service list in machine.py so future installs of moonraker will allow the octoeverywhere service to be managed from frontends.

Signed-off-by: Quinn Damerell <quinnd@outlook.com>
2023-02-03 19:09:34 -05:00
Eric Callahan 61d3182bea docs: add thumbnail request documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:55 -05:00
Eric Callahan c1e4142a40 update_manager: add arch filter
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:54 -05:00
Eric Callahan b02e766a4d update_manager: log detected packages
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:54 -05:00
Eric Callahan fb618a46fd file_manager: fix thumbnails endpoint registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:33 -05:00
Eric Callahan 55e852cd87 file_manager: add thumbnail request endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 06:13:44 -05:00
Eric Callahan 1bad68cb66 dbtool: improve encoded line regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-28 12:09:36 -05:00
Eric Callahan 6c4c7a00cf docs: add database backup/recovery
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-28 08:04:13 -05:00
Eric Callahan 50d22a2dff scripts: add database backup and restore scripts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 19:25:09 -05:00
Eric Callahan 46a92e1900 dbtool: update backup location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 07:57:51 -05:00
Eric Callahan 2392ccd719 scripts: update default database path for fetch-apikey.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 06:10:16 -05:00
Eric Callahan 12b1befcbc authorizaton: type checking fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 07:08:23 -05:00
Eric Callahan 3dbc99fd84 docs: update authorization documentation
Authorization APIs are a now available over the websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:20:02 -05:00
Eric Callahan d8941b3fb2 websockets: sanitize verbose logging
When verbose logging is enabled sanitize credentials from JSON-RPC
requests and responses.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:54 -05:00
Eric Callahan a5161816a7 websockets: decode jwts on authorized connections
Unix sockets never require authentication and it is possible for
Websocket connections to authenticate with the request itself.
In these cases the `identify` endpoint must still process an
access_token if provided, as it allows the front end to assign
the desired user to the connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:54 -05:00
Eric Callahan 80862799ed websockets: require re-auth on user logout
Propagate user state changes to open websockets and unix sockets.
If a websocket's user is logged out require re-authentication.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:53 -05:00
Eric Callahan 06ec5541e3 websockets: add support for API Key authentication
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:53 -05:00
Eric Callahan eca4c7e438 authorization: limit failed login attempts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 9d6719ed31 websockets: set a websocket connection limit
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 5a22b21a40 authorization: relax auth header requirements
Don't raise an exception if the authorization header contains an
invalid value, such as Basic auth.  Ignore it and move on to the
next step in authentication.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 4ca39bec0a authorization: authenticate over websocket
Register all of the "access" endpoints with the websocket.  Front
ends may now connect to the websocket without an oneshot token
and login.  If the front end already has a JWT for the user it
can be passed to the "identify" endpoint to authenticate directly.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:51 -05:00
Eric Callahan c83714bfe8 authorization: make api key authentication optional
Signed-off-by;  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:51 -05:00
pataar d4378eb051 notify: bump apprise to v1.2.1
Signed-off-by: Pieter Willekens<git@pataar.me>
2023-01-23 17:50:29 -05:00
Eric Callahan c964e68bc8 docs: fix erroneous note in secrets section
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-01-18 19:47:52 -05:00
Eric Callahan 2ad7a6a087 power: log the traceback on device init errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-18 19:31:47 -05:00
Eric Callahan db81607370 machine: use direct systemctl commands for reboot/shutdown
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-16 12:42:21 -05:00
Eric Callahan a154c5fa51 machine: add moonraker-obico to default services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-12 18:10:30 -05:00
Eric Callahan c9a1d0f3bb server: bump API version to 1.1.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-10 06:12:45 -05:00
Eric Callahan bf63798bb1 simplyprint: fix queue handler import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-09 07:12:08 -05:00
Eric Callahan 3400094881 klippy_connection: minor change to is_ready() method
Use attribute to check the condition rather than the property.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-09 07:11:33 -05:00
Eric Callahan 486f659d20 docs: add new endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:50:09 -05:00
Eric Callahan a4b496d135 file_manager: fix internal access check
Include the reserved file check in the `can_access_path()` method.  This
fixes a potential vulnerability in the notifier where it may be possible
to attach a reserved file to a notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:50:08 -05:00
Eric Callahan fe9a9899e3 file_manager: reserved path fix
Raise an exception if an attempt is made to access .git folders.

Signed-off-by:  Eric Callahan <arksine.cde@gmail.com>
2023-01-08 13:50:08 -05:00
Eric Callahan 6021b39234 file_manager: implement zip endpoint
Provides an API for front ends to archive a list of files and/or
folders into a single zipped file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:49:32 -05:00
Eric Callahan 53eda78b11 loghelper: moonraker log management
Move logger initialization out of the utils module into its own
module, loghelper.py.  This manager class simplifies access to the
underlying logger implementation and the queue listener.  Additionally
it allows for endpoint registration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:54 -05:00
Eric Callahan 24dc8914d0 klippy_connection: implement manual log rollover
On systems where Klipper is installed as a service allow a
manual log rollover.  The rollover cannot be called while printing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:53 -05:00
Eric Callahan ecf7fb9267 klippy_connection: add is_printing() and is_ready() methods
Several components throughout Moonraker determine whether or not
Klipper is printing or is ready before taking action.  This centralizes
queries in one area.  The checks do not query Klipper directly but
rather rely on subscriptions to push state to Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:52 -05:00
Eric Callahan 019c5fc416 app: move reserved endpoints to klippy_connection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 06:14:45 -05:00
Eric Callahan 225ec588eb docs: document allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 07:46:44 -05:00
Eric Callahan 690f841768 machine: introduce custom allow list for service control
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 07:46:43 -05:00
Eric Callahan b3a9447392 power: add support for multiple bound services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 06:30:18 -05:00
Matt White e3bcfb5ea0 mqtt: add option to publish states to individual mqtt topics
This change allows the user to choose the strategy for publishing
klipper states to MQTT.  The original strategy where all state
updates are published to a common topic is still the default, but
can be turned off using the "publish_combined_status" config option.

The newly added strategy is publishing individual state updates to
separate mqtt topics.  It is disabled by default, and can be enabled
with the "publish_split_status" config option.

Signed-off-by: Matt White <m.w.white@gmail.com>
2022-12-30 06:13:25 -05:00
Eric Callahan 358aee956b docs: clarify power on start usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-27 10:37:10 -05:00
Eric Callahan 1999b82a86 docs: update power documentation
Note how to override SDCARD_PRINT_FILE to power on
a device before a print starts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-26 08:29:24 -05:00
Eric Callahan d6b1a724a8 eventloop: improve callback handling
Wrap all callbacks in a coroutine that handles exceptions.  This
should eliminate "task not retreived" errors.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-24 08:07:45 -05:00
Eric Callahan 3d3911d4fd docs: document the "force" power option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-24 06:37:18 -05:00
Eric Callahan aeea9a2efd power: introduce "force" argument for remote method calls
The "force" argument may be used turn on a device during a print
that is otherwise locked for normal requests.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-12-23 19:13:11 -05:00
Pedro Lamas a6b8a8a3e9 docs: add "reset" parameter to post endpoint
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-12-23 08:07:04 -05:00
Pedro Lamas 51fee3e7a1 job_queue: add "reset" parameter to post endpoint
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-12-23 08:07:04 -05:00
Eric Callahan f7d8af6e12 docs: add the "jump queue" API
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-22 14:09:15 -05:00
Eric Callahan 129b0feb81 job_queue: add "jump" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-22 12:48:23 -05:00
Eric Callahan f296c6fadd update_manager: allow old application naming convention
While the [update_manager client ...] naming convention is
deprecated it should not be disallowed.  This fixes service restart
issues using the old naming convention.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-12 16:59:22 -05:00
Eric Callahan dde9bcc752 metadata: add object detection logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-30 16:40:36 -05:00
Eric Callahan 1cb46a8f8f metadata: fix check for existing objects
Don't process files with EXCLUDE_OBJECT_DEFINE gcode
commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-30 13:43:39 -05:00
Eric Callahan f3f39b7ab0 metadata: handle object processing identity
This allows object processing for slicers with aliases.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-28 10:50:40 -05:00
Eric Callahan f3e13faf19 file_manager: validate Klipper config path
Warn when Klipper's configuration file is not located in
the "config" subfolder of the datapath.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-26 19:30:59 -05:00
Eric Callahan 7b8c2c3409 metadata: add support for A3dp Slicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-26 06:22:27 -05:00
Pedro Lamas b67a08a65b machine: use virtualization.virt_identifier property
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-11-22 05:59:18 -05:00
Albert Møller Nielsen c61ff8b252 simplyprint: preprare for release
Signed-off-by: Albert Møller Nielsen <albert@simplyprint.io>
2022-11-20 19:16:08 -05:00
Eric Callahan 362bc1a3d3 machine: fix typos and clarify supervisord docs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-18 10:42:44 -05:00
mirokymac 48f3bb2189 machine.py: add support for supervisord service management
Signed-off-by: mirokymac <toufubomb@gmail.com>
2022-11-18 10:37:33 -05:00
Eric Callahan e628b243c2 docs: add canbus to /machine/system_info result
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 16:52:20 -05:00
Eric Callahan 88ebc21318 requirements: update distro 1.8.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 14:33:47 -05:00
Eric Callahan 68f5de6d2d machine: report canbus info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 14:20:07 -05:00
Eric Callahan bfe20433f9 mqtt: update compatibility with latest client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 10:11:59 -05:00
Eric Callahan bd1fd63b14 requirements: update python dependencies
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 10:11:59 -05:00
pataar 7afd556c21 notify: upgrade apprise to version 1.2.0
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-11-16 10:10:50 -05:00
Markus Küffner 8b2e8c2a4e scripts: update streaming-form-data dependency
Updates streaming-form-data to Version 1.11.0 to be compatible with Python 3.11.0

Signed-off-by: Markus Küffner <kueffner.markus@gmail.com>
2022-11-16 10:09:23 -05:00
Eric Callahan 490d27b7de extensions; type checking fix take two
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-13 14:30:24 -05:00
Eric Callahan 0c6e860534 extensions: fix type checking for Python 3.7
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-13 14:16:59 -05:00
Eric Callahan 7f58f2274e docs: add unix socket documentation 2022-11-13 12:32:07 -05:00
Eric Callahan b2d109a840 extensions: serve JSON-RPC API over a unix socket
Support unix connections with full access to all JSON-RPC APIs.
Internally these connections are treated as websocket connections,
however the underlying transport protocol is simplfied.  Packets
are JSON encoded objects terminated with an ETX character.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-10 11:57:21 -05:00
Eric Callahan 53129bef7e utils: add method for retrieving unix socket peercred
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-09 07:15:33 -05:00
Eric Callahan f089794adc websockets: create a client base class
Separate out code that applies to both standard websockets and the
future unix socket implementation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-09 07:15:33 -05:00
Eric Callahan 5a3b1b6e5c docs: fix list roots endpoint
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-11-07 07:54:43 -05:00
Eric Callahan ddf3325dae docs: document list roots
Update documentation to note that the uds now supports
templates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 11:48:00 -05:00
Eric Callahan bb7cd27be5 machine: fix typo in sudo access request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 11:43:52 -05:00
Eric Callahan a8018afd46 file_manager: always deny access to .git folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:32 -05:00
Eric Callahan d490796da9 file_manager: fix permission reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:32 -05:00
Eric Callahan 36536535bc klippy_connection: update configuration
Use the ConfigHelper's getpath() method to configure the
unix socket.  The option may now be a template where the
datapath is passed into the context.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:31 -05:00
Eric Callahan b291d94596 file_manager: implement additional reserved path filters
Do not add inotify watches for reserved paths that exclude
write acccess.  Do not return include reserved paths in
file list requests without read access.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:31 -05:00
Eric Callahan 484950cb40 confighelper: implement getpath
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:30 -05:00
Eric Callahan e8dad1c8c0 file_manager: add list roots endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:30 -05:00
Misterke 130c2a48f0 file_manager: disallow drilling down protected folders
Signed-off-by:  Kurt Haenen <kurt.haenen@gmail.com>
2022-11-05 10:45:46 -04:00
pataar 6f43940270 docs: improve notifier reference when using the action
This was unclear for users.

Signed-off-by: Pieter Willekens <me@pataar.nl
2022-11-04 16:20:37 -04:00
Eric Callahan 779997c2b8 git_deploy: refresh previously corrupt repos
It is possible that the user manually corrected a corrupt repo.
If a repo makes it past initialization reset the corrupt flag.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-22 19:03:48 -04:00
Eric Callahan 1a3689cb7d klippy_connect: resolve the uds path
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 16:45:16 -04:00
Eric Callahan 1ef34b8b60 machine: improve default database handling
Don't force a symlink to the default database if
the subfolder exits.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 16:44:51 -04:00
Eric Callahan 80a7d461ed data-path-fix: correct moonraker.conf typo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 11:21:17 -04:00
Eric Callahan 4c963de0fc data-path-fix: add gcode path option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 19:25:15 -04:00
Nick Douma 6afa664ac9 ldap: Add option to use a customer LDAP query for looking up the user logging in
This allows for more advanced integration of LDAP databases that are not
covered by the default behaviour of is_active_directory.

Signed-off-by: Nick Douma <n.douma@nekoconeko.nl>
2022-10-21 19:24:35 -04:00
Eric Callahan 379bcb10f9 data-path-fix: add missing alias
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 15:23:45 -04:00
Eric Callahan 8540f5a794 data-path-fix: add command line arguments
Give the script flexibility for use on installs with multiple instances.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 14:26:03 -04:00
Eric Callahan 1f86943cbb gpio: relax error handling
Increase the error threshold to 50 and reset within a 5 second threshold.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 14:13:17 -04:00
Eric Callahan 4df0b4d532 machine: abort validation if the backup config is loaded
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 10:26:25 -04:00
Eric Callahan 1190aba4b7 machine: add logging to validation init
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 10:26:25 -04:00
Jim C K Flaten 25adba0bf6 docs: Correct minimum_event_time example
The internal variable is called `min_`, but the config option is called `miniumum_`.
2022-10-21 10:23:29 -04:00
Eric Callahan 974b37dad8 machine: improve multi-instance validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 20:27:02 -04:00
Eric Callahan 8f444a908e shell_command: error message fix
Use the original command in the message rather than the
list generated by shlex.split().

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:35 -04:00
Eric Callahan 59cc8c6c7b update_manager: report errors in update response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:35 -04:00
Eric Callahan e4a670a380 update_manager: improve corrupt repo detection
It that "git status" will not detect some repo issues, these are only
found after a fetch.  When this condition is detected save the repo
state and report that the repo is corrupt and invalid.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:34 -04:00
Eric Callahan 74f43cad6e git_deploy: notify attempts to fix loose objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 19:32:54 -04:00
Eric Callahan c7e290a3cd update_manager: improve web client error handling
Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 17:58:58 -04:00
Eric Callahan 38b035389d power: improve logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 16:35:49 -04:00
Eric Callahan 1f1c590409 power: add initial state support for all devices
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-19 13:43:14 -04:00
Franklyn Tackitt 6131c7afc1 Git submodules use a .git file instead of a directory
I'm playing with using git submodules to track my entire printer config,
 and moonraker only works with separate clones as is. Using `.exists()`
 instead of `.is_dir()` allows moonraker to control the submodules.

Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-10-19 13:41:35 -04:00
Eric Callahan 4954cc74cd machine: change sudo folder access test
The previous "/lost+found" is not available on all systems.  Change to
"/root", which should be available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 06:21:18 -04:00
Eric Callahan f745c2ce17 database: remove legacy database warning
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 14:13:25 -04:00
Eric Callahan d6bdad3a9d machine: announce required update via gcode terminal
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 14:07:27 -04:00
Eric Callahan 9a466f3b22 server: improve warning formatting
Introduce a "raw" parameter for /server/info that defaults to False.
Front ends that do not wish to recieve warnings with html line breaks
may set this parameter to True, otherwise newlines will be replaced
with "<br/>".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 07:23:25 -04:00
Eric Callahan a8cbfe6345 file_manager: improve gcode path warning
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-18 07:23:25 -04:00
Eric Callahan 6b3c78da71 docs: fix notifier debug endpoint
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-18 05:20:39 -04:00
pataar b981dc109d notify: add server endpoints for notifier to list and test them
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-10-18 05:18:30 -04:00
Eric Callahan f1c4d6b143 machine: validation fix for new installs
Add a missing return statement to _link_data_subfolder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-17 06:30:54 -04:00
alfrix 7552631b65 update_manager: fix error message displaying the wrong option
Signed-off-by: Alfredo Monclus <alfredomonclus@gmail.com>
2022-10-16 10:31:15 -04:00
Eric Callahan 06279d0e10 data-path-fix: update for fresh installs
Don't require the database and gcode paths to exist.  Fall back on the
default location if they do not.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-16 07:53:51 -04:00
Eric Callahan 7e35e54a71 machine: increase timeout for sudo access check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 20:01:19 -04:00
Eric Callahan 05ca71f5a8 machine: relax config validation
Don't raise an exception if the option in a path does not exist.  Remove
the option and fall back to the default path location

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 19:58:34 -04:00
Eric Callahan 3ad7d0668a scripts: add data-path-fix script
This script can be used to fix broken installations on
MainsailOS and FluiddPi distributions running a
single instance of Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 11:42:43 -04:00
Eric Callahan b9cac62db8 update_manager: log when refresh is bypassed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 11:07:31 -04:00
Eric Callahan 65e24a14dc update_manager: do not refresh when install validation is pending
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 10:52:05 -04:00
Eric Callahan 53fcc7386f machine: increase timeouts for sudo commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 10:52:04 -04:00
Eric Callahan 00c4846d11 machine: validation fixes
Protect the sudo request with a lock.  Add retries to the sudo
commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 08:37:45 -04:00
th33xitus f0e4678fab docs: use term "sudo" instead of "root"
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-10-15 06:11:14 -04:00
th33xitus fb327a6ca9 machine: use term "sudo" instead of "root"
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-10-15 06:11:14 -04:00
Eric Callahan 500e8f3b68 machine: disable file write access when validation fails
Prevent users from uploading files before validation is complete, as
this can populate one of the subfolders resulting in a failure when
attempting to symlink the original path.

When validating the config symlink the database first.  This should
allow Moonraker to correctly move the database should an error
be encountered when validating the other config options.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 06:01:36 -04:00
Eric Callahan fb679aa056 database: minor fallback fix
Fallback if not using the default path and the database has not been created.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 19:25:47 -04:00
Eric Callahan 2603cc2e8f docs: update deprecations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 485b29490a update_manager: deprecate repo debug option
Use the "debug" command line option to enable debug
features for the update manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 1e8c7f0915 database: register debug endpoints
Allow full database access to registered debug endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 30e2ec04b7 app: add support for debug endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 86fc1057f7 server: deprecate debug logging option
Add a debug option to the command line to enable
debug features.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan d2cbd1d0a0 finish-upgrade: helper for finishing updates
This script provides a method for users to complete an upgrade
that requires elevated privileges via ssh.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 485c723a3c install: only write initial config for first time installs
This prevents an upgrade from unintentionally populating
the config directory when a legacy install exists.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 9021fbea48 machine: use default password for validation
For legacy Raspberry Pi installations attempt to automate
the update using the default password.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan be9aff8b5e power: loosen bound service requirement
Specifically check against the detected service unit, otherwise
allow a power device to bind to any available service.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan f22b859a0f docs: update install documentation
Moonraker no longer takes an `alias` command line option.  Use `printer_data`
as a placeholder for the default data folder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 26088cdfff install: change env location and rework default datapath
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 41ea45a486 moonraker: remove alias option
Differentiate instances based on the data path provided.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan c3cd24b3bf docs: add "instance_ids" field to system_info response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 266c5b53d1 machine: extend system info request with unit names
Report the unit names for both Moonarker and Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan d3484e8c13 klippy_connection: report systemd service info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 59471a7959 docs: update machine documentation
Add documentation for the new validation options, and document
changes to the sudo APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan dd7e480cdd docs: update documentation reflected new folder structure
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 577f55306e install: add data path and alias options to the script
Additionally, rework the systemd unit so it is not necessary to
overwrite and reload systemd when changes are made to Moonraker's
arguments.  Use a symbolic link for the executable and an environment
flle to supply the arguments.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 636aca6cbd app: add sudo request form to welcome page
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 5259a6fd0a moonraker: perform install validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 6e56815b42 machine: implement install validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 7004722499 app: report if https is enabled
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 7217b36f9b file_manager: handle overlapped inotify watches
Handle exceptions raised when adding a new watch.  Warn
the user and skip adding the node to the watched tree.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 069a655df8 file_manager: update reserved path handling
Allow components to register reserved paths, then perform reserved
path validation it upon request.  Reserved paths may be registered as
read-only or no access.  Any request to modify an file/folder that is
either reserved or a child of a reserved path is rejected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 4df6aba6c0 app: use datapath for ssl certificate storage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 1327602ec3 secrets: add support for the data folder
The secrets module will now look for "moonraker.secrets"
in the data folder.  If the file does not exist the deprecated
"secrets_path" option will be used as a fallback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 524552eb84 database: add support for the data folder
Deprecate the "database_path" option.  If the database
does not exist, however the "database_path" does, it
will be used as a fallback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 480ebfac8e file_manager: add support for new "data_path"
The config and logs paths are no longer configurable,
they all exist as folders or symbolic links within the primary
data folder.  The gcode path no longer relies on Klipper to
specify the location, instead Klipper's virtual_sdcard path
shold be configured to the location of the "gcodes" folder
in the data path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan b78cdf9660 moonraker: add data_path and alias command line arguments
Prepare to move away from configurable paths.  This will
resolve potential security vulnerabilities in the event that
a user's access is compromised.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan edaeb17f38 docs: update simplyprint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-12 11:14:12 -04:00
Eric Callahan 91e48200d6 simplyprint: implement direct layer detection
Klipper now has the ability to report the current layer on
properly configured slicers.  Prefer this value if available,
otherwise fall back to layer detection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan c48fe7307a job_state: add layer_changed event
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan 48674a46e1 simplyprint: add support for configured ambient sensors
Users may specify a dedicated ambient sensor in the
[simplyprint] configuration.  If the specified sensor is
invalid or no sensor is specified ambient detection
will fall back to an estimate using the extruder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan 785213b2b3 simplyprint: bring up AI stream to correct state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 18:01:57 -04:00
Eric Callahan 6e121c2221 simplyprint: implement "webcam_stream" demand
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:32 -04:00
Eric Callahan d5fa40df87 simplyprint: implement ping timer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:32 -04:00
Eric Callahan f8d15d3baa simplyprint: remove keepalive
This will be replaced by a custom ping timer to the backend.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:31 -04:00
Eric Callahan 2e3188a48b klippy_connection: socket credential fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:06:19 -04:00
Mathis Mensing cd19b51117 app: add jpg files to AUTHORIZED_EXTS
Signed-off-by: Mathis Mensing <github@matmen.dev>
2022-10-10 19:41:30 -04:00
Pedro Lamas 60b871adbe metadata: strip delimiting quotes in strings
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-09-27 06:08:34 -04:00
SoftFever df24e3ea77 metadata: Add support to extract metadata from g-code files generated by Bambu Studio
Signed-off-by: Li Jiang <softfeverever@gmail.com>
2022-09-22 06:00:45 -04:00
Andrew Basson 07f4643070 docs(api-changes): fix method typo
Signed-off-by: Andrew Basson <andrew.basson@gmail.com>
2022-09-21 05:48:07 -04:00
alfrix 621739bb2b docs: web_api: update allowed system services 2022-09-21 05:40:34 -04:00
Rogerio Goncalves 4806ffd2ae proc_stats: expose network packets, errors and drops
Signed-off-by: Rogerio Goncalves <rogerlz@gmail.com>
2022-09-21 05:38:06 -04:00
pataar 21bb17743f notify: add ability to notify using a remote action
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-09-21 05:36:55 -04:00
Eric Callahan 5d856b9c49 simplyprint: suppress write exceptions
Its possible for the websocket client to disconnect before
read_message() returns None.   Await all calls to write_message()
to handle websocket closed exceptions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-09-05 05:59:02 -04:00
pataar f047167b3b notify: upgrade apprise to version 1.0.0
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-08-30 10:19:41 -04:00
Eric Callahan d04e99a8ec simplyprint: automated file reset bugfix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 13:45:21 -04:00
Eric Callahan 7f2d43de3d simplyprint: automate file reset for sp uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 12:23:03 -04:00
Eric Callahan 3a03f48e0f simplyprint: report error messages
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:52 -04:00
Eric Callahan 25e79c78b2 klippy_connection: report Klippy's state message
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:52 -04:00
Eric Callahan b52b0bd98a webcam: improve default host handling
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:51 -04:00
Eric Callahan e8999363ed confighelper: raise duplicate exceptions
Moonraker requires that the configuration be parsed in 'strict' mode,
ie: duplicate sections are not allowed within the same file and duplicate
options are not allowed within the same section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:51 -04:00
Grant Harding 78605db001 webcam: fixed rotation param
Signed-off-by: Grant Harding gharding@gmail.com
2022-08-28 11:16:02 -04:00
Eric Callahan e3cafb58bc docs: update "machine" component documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 07:16:15 -04:00
Eric Callahan db7474aa88 machine: use sudo password for commands if available
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 06:30:28 -04:00
Eric Callahan 272f7b946d machine: add endpoint to check sudo access
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:59:38 -04:00
Eric Callahan 59403e226b git_deploy: line length fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:54:48 -04:00
Eric Callahan 25d99207f0 authorization: implement permitted path registration
Allow components to register paths that bypass authentication
requirements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:25:20 -04:00
Eric Callahan fd5053ecac app: improve debug logging
Dont log the full response when html is requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:22:23 -04:00
Eric Callahan 2314ea74c2 app: report asset path location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:22:18 -04:00
Eric Callahan 942d595bc2 websockets: static type fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:21:56 -04:00
Eric Callahan e82fe46c11 moonraker: provide startup warnings as a list
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:20:58 -04:00
Eric Callahan 0d936d5af0 moonraker: track warnings by id
This makes it possible to remove warnings and prevent duplicates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:20:33 -04:00
Eric Callahan 0dd8eee034 confighelper: add method to write the config to any folder
Signed-off-by:  Eric Callahan <arksine.cod@gmail.com>
2022-08-21 05:19:27 -04:00
Eric Callahan a4f9fbe298 confighelper: support config modification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:19:12 -04:00
Eric Callahan a776f1f6dc git_deploy: improved moved origin handling
Query the detected url and make sure it redirects to the
expected url.  This closes a security vulnerability
where a remote could be changed to an arbitrary repo's url.

The `moved_origin` option is no longer necessary, however it
is currently used as an additional check.  In the future it will be
deprecated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:44 -04:00
Eric Callahan 4b25b04c4f git_deploy: refuse recovery if repo is not verified
Close a security hole where an attacker could overwrite an existing repo
with any remote and run malicious code through an update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:38 -04:00
Eric Callahan b5e7a5ba5a update_manager: resolve pip location issues
If the supplied python executable is a symbolic link attempt
to read the location at which it points.   If this is a virtualenv
this should give us the correct pip location.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:16 -04:00
Eric Callahan c24fd7d11c template: add support for UI templates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:17:57 -04:00
Eric Callahan b7768671aa http_client: report final resolved url in response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:17:36 -04:00
Eric Callahan 12161d12f5 machine: improve private ip detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:16:06 -04:00
Eric Callahan 4efb6575b7 machine: report provider type and container info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:15:19 -04:00
Eric Callahan c154d92499 machine: add support for setting a sudo password
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:44 -04:00
Eric Callahan a7b50a8068 machine: extract moonraker systemd unit info
This allows moonraker to validate and log the current unit file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:31 -04:00
Eric Callahan cd24b116c6 utils: resolve the moonraker path to an absolute path
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:04 -04:00
Eric Callahan 66f9184c74 zeroconf: support binding to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 17:38:22 -04:00
Eric Callahan 49b3f78f20 docs: note how to bind to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 12:24:10 -04:00
Eric Callahan 97c8b05eee app: support binding to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 12:21:41 -04:00
Eric Callahan 853de9e8cb update_manager: resolve potential deadlocks on startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-18 07:17:54 -04:00
Eric Callahan 413e3b2f4f simplyprint: add power device fallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:48:13 -04:00
Eric Callahan 3424f1b3e2 machine: fix IP detection broadcast setting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:26:19 -04:00
Eric Callahan c4e370fcff machine: improve LAN IP detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:20:56 -04:00
Pedro Lamas 8bbd269084 metadata: adds chamber temp support
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-08-08 17:56:27 -04:00
Eric Callahan a9345d19fa simplyprint: fix incorrect directive
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:37:35 -04:00
Eric Callahan 71e9085778 install: add wireless-tools dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:03:09 -04:00
Eric Callahan 39f26dc31a simplyprint: silence stream errors
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:02:20 -04:00
Eric Callahan 6e253b0d42 webcam: fix default host fallback
Fallback to the loopback if unable to determine the
local ip address.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 16:55:59 -04:00
Eric Callahan 0188b81d4a dbus_manager: verify stat path exists
Signed-off-by:  Eric Callahan  <arksine.code@gmail.com>
2022-08-01 10:22:16 -04:00
Eric Callahan e0cf635d34 simplyprint: websocket write fix
Gracefully handle websocket closed conditions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-30 15:16:52 -04:00
Eric Callahan ea29788ab1 docs: add simplyprint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-28 10:57:25 -04:00
Eric Callahan c251a9d7ed simplyprint: initial implementation
This adds initial support for connecting Moonraker to the SimplyPrint
service.  Currently the connection defaults to SimplyPrint's dev/test
endpoint, this will be changed prior to official release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-28 08:06:49 -04:00
Eric Callahan cd8954e36c metadata: Add support for Kiri:Moto and SimplyPrint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-27 07:59:07 -04:00
Eric Callahan 5d4db16fd6 docs: update configuration documention
Note support for inline comments and the current behavior
for include directives.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-27 07:41:07 -04:00
Eric Callahan e264fa82b2 confighelper: don't overwrite option tracking
Its possible for any component to request a configuration
option from another component.  Don't overwrite the
inital value stored.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-26 19:34:40 -04:00
Eric Callahan a178a6cd01 confighelper: improve file parsing
Process included files in the order they are added.  This changes how
duplicate sections throughout included files are merged, options in
the last section to be parsed will take precedent.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-26 19:34:39 -04:00
Eric Callahan bdd0222a1c machine: handle exception if iwgetid fails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 17:16:34 -04:00
Eric Callahan d713076947 docs: add webcam documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 12:05:54 -04:00
Eric Callahan 6b4020a6e9 moonraker: load webcam as a core component
This makes sure that the webcam APIs are always available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 11:27:30 -04:00
Eric Callahan a3cae26e33 webcam: initial implememtation
The webcam module allows users to enter webcam configuration through
moonraker.conf while keeping compatibility with frontends that
store webcam data in the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 11:27:29 -04:00
Attila BODY cd6db1ee75 scripts: Following polkit versioning scheme change
Signed-off-by:  Attila Body <attila.body@gmail.com>
2022-07-19 17:35:30 -04:00
Frank Tackitt 16327ff551 install-moonraker: allow configurable virtualenv location
Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-07-19 14:51:06 -04:00
Frank Tackitt 7cd29c068d authorization: set private network CORS header
In the future, an `Access-Control-Request-Private-Network` header will be sent with
 these requests, and servers must respond with `Access-Control-Allow-Private-Network`.

This will start with the next Chrome version (104), and Mozilla has marked the
 standard as "worth prototyping", which often leads to final implementation.

Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-07-19 14:25:18 -04:00
olli-t 9fea1634b1 power: fix Hue implementation
Signed-off-by: Oliver Tetz olli.codes.some.lines@gmail.com
2022-07-18 08:17:16 -04:00
Eric Callahan bcb7a55996 power: fix type/checking formatting for Hue device
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-17 06:38:38 -04:00
lie_ink 4d803ec9e5 power: add support for hue devices
Signed-off-by: Oliver Tetz <olli.codes.some.lines@gmail.com>
2022-07-17 06:26:26 -04:00
Eric Callahan 3080885257 update_manager: change default refresh interval
Check for updates every 7 days rather than every 28 days.  This
is in preparation of an upcoming beta release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-17 06:13:50 -04:00
Eric Callahan 53a3c64186 moonraker: move loop creation to the eventloop module
Python 3.10 deprecates "get_event_loop()", so it is necessary to
create a new loop and set it as active at startup.  Previously
Moonraker only did this after a soft restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-16 19:41:09 -04:00
Eric Callahan d37f91c9c8 power: type checking fix
For legacy purposes its possible that "initialize()" may be an
awaitable.   Ignore the type as it consues mypy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 12:06:36 -04:00
Eric Callahan 31d4335e3e power: allow indefinite remote device init
Remote devices, such as the tplink smartplug and http
based devices, may not be immediately available when
Moonraker starts.  Previously this would result in an error.

Remote switches that requiring polling for state will now
reattempt initialization indefinitely.  This behavior brings
them in line with devices that are updated asynchronously.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 08:07:46 -04:00
Eric Callahan 835e49c10e klippy_connection: log raw peercred data on error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 06:01:48 -04:00
Eric Callahan 0a0993f9e0 server: sleep 1ms after calling component close methods
This allows any cancelled tasks to run through the eventloop
before loop.stop() is called.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-06-28 19:21:21 -04:00
Eric Callahan 09550af466 mqtt: resolve connection blocking issues
Override the paho-mqtt client "reconnect()" method with
a method capable of taking a connected socket.  This allows
Moonraker to connect the socket asynchronously, then finish
establishing the connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-28 19:21:21 -04:00
Eric Callahan 0b31d7d0b2 eventloop: add async create socket method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-28 18:25:16 -04:00
Eric Callahan 371840a988 klippy_connection: increase the read buffer limit
Allow a buffer of up to 20 MiB to cover the reception of
a very large request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-27 10:51:56 -04:00
Eric Callahan 1eaead1073 server: handle event exceptions
Don't allow exceptions to propagate beyond a call to
_process_event().  Make sure the future is not marked
as done prior to setting the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-27 10:51:49 -04:00
Eric Callahan 4bed314b0a authorizaton: fix static type checks
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-17 17:56:47 -04:00
Eric Callahan 8266376f46 authorization: fix minor typing issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-17 17:07:58 -04:00
Luca Schöneberg 58fa361c8c authorization: implement /access/info endpoint
Signed-off-by: Luca Schöneberg <luca-schoeneberg@outlook.com>
2022-06-17 11:19:12 -04:00
Eric Callahan a8b9fc0017 docs: document list feeds api
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-12 06:20:55 -04:00
Eric Callahan d19471fd4d announcements: implement list feeds endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-12 06:10:29 -04:00
Eric Callahan 14ec8472ef ldap: fix group validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-11 17:06:54 -04:00
Eric Callahan a492ae983c docs: add ldap documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:53 -04:00
Eric Callahan 65d532a6cf reqs: add ldap3 python requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:53 -04:00
Eric Callahan 7780a8a09e authorization: add ldap support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:52 -04:00
Eric Callahan f52df8c7ed ldap: initial implementation
Introduce an ldap component that can be used authenticate
Moonraker users over ldap connections.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:52 -04:00
Eric Callahan 5081321a32 Revert "authorization: add LDAP support"
This reverts commit a86cbc77f6.
2022-06-08 06:23:19 -04:00
Eric Callahan d0cdd76bed Revert "install: add ldap requirements"
This reverts commit 7af8a03129.
2022-06-08 06:23:14 -04:00
Eric Callahan 250b93e89c git_deploy: fix install script parsing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 06:13:17 -04:00
Eric Callahan 3b76d81155 machine: add sonar and crowsnest to allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-07 06:51:40 -04:00
Luca Schöneberg a86cbc77f6 authorization: add LDAP support
Signed-off-by: Luca Schöneberg luca-schoeneberg@outlook.com
2022-06-07 06:46:08 -04:00
Eric Callahan 7af8a03129 install: add ldap requirements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-07 06:38:04 -04:00
Eric Callahan 74d6e35166 Revert "job_queue: always initialize state to "ready""
This reverts commit d53cf27264.
2022-06-01 17:37:03 -04:00
Eric Callahan d53cf27264 job_queue: always initialize state to "ready"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-22 06:02:46 -04:00
Eric Callahan f15ec23c3a http_client: increase max body size
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-21 06:27:56 -04:00
Eric Callahan 0164bb239e klippy_connection: fix bug during initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-13 05:23:06 -04:00
Eric Callahan babfba1686 mqtt: allow unlimited connection attempts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-12 19:37:33 -04:00
Eric Callahan 09ac00ce2e klippy_connection: request endpoints before setting the state
All of Klipper's endpoints should be available before Moonraker
reports the "ready" state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-12 19:22:56 -04:00
Pierre Bedell 3d9f5dc6d9 metadata: expanded IceSL's support
Signed-off-by: Pierre Bedell pierre.bedell@gmail.com
2022-05-09 12:22:20 -04:00
Richard Mitchell 56097a35ad wled: Add extra control for wled effects
For the "Percent" preset the intensity controls the amount of the bar lit up 0-100
Work around issue when preset is re-enabled if sending intensity or speed while no preset is active

Removed control endpoint
Added missed toggle endpoint
Transition time to 0 for control changes

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-05-09 06:32:14 -04:00
Eric Callahan fcfa563d02 docs: fix minor typo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-04 05:28:20 -04:00
Eric Callahan 59f2736bb6 docs: clarify location of moonraker.conf
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-04 05:25:40 -04:00
David Smith 2f09b74dc1 docs: correct flip_v for webcam vertical flip
Signed-off-by: David Smith <davidosmith@gmail.com>
2022-05-03 06:32:53 -04:00
Eric Callahan cd520ba917 http_client: immediately raise cancelled errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-23 14:55:49 -04:00
Eric Callahan 94a11ff291 docs: add repo recovery documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 17:56:29 -04:00
Eric Callahan 11beaa7076 metadata: read metadata after object processing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 10:28:45 -04:00
Eric Callahan 6f2ce72b4c metadata: add a UUID to extracted metadata
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 06:47:31 -04:00
Eric Callahan c1eda1ef3d http_client: modify download progress reporting
Report progress for each percentage change.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 06:37:52 -04:00
Eric Callahan f8a38abc89 confighelper: Update the help url for moved options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-20 07:13:26 -04:00
Eric Callahan 985760c584 docs: add clarification to option deprecations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-20 07:08:29 -04:00
Eric Callahan d84f93d381 polkit: add flag to disable systemctl
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:46:15 -04:00
Eric Callahan 3ddbb9553d docs: note the "-z" option of the install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:18:16 -04:00
Eric Callahan b06f782665 install: add flag to disable systemctl
The "-z" flag will run the install script without running the
systemctl command.  This is useful for installations which
are done outside of the normal "boot" process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:11:04 -04:00
Eric Callahan 4be8e2e72f database: fix decode exception handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 10:59:38 -04:00
Eric Callahan 65946ef857 job_queue: increase ready job delay
Delay for a full second before processing a job after
Klippy reports ready.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:23:02 -04:00
Eric Callahan bbd5d8a1a1 history: add logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:22:58 -04:00
Eric Callahan 430c2550c5 job_state: add logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:18:42 -04:00
Eric Callahan fe84226908 klippy_connection: log klippy version as received
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:18:32 -04:00
Eric Callahan d3003a1584 machine: return default values for find public interface
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-15 17:27:36 -04:00
Eric Callahan 47c6245c3f docs: spelling fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan e0eded70e8 docs: document extension APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan 4666458793 websockets: simplify JSON-RPC execution
To accommodate access to multiple protocols Moonraker will always
require that the "params" field contain a dictionary, so reject any
other type as invalid.  There is no need to expand keyword arguments,
simply pass the params dict to the callback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan da864ab391 websockets: only allow connections to identify once
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan cbc02d625c websockets: add agent registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan a79e0eeef2 moonraker: add extensions to core components
Bump the API patch version with the addition of the extension
APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan 236a7a7736 extensions: initial implementation
Add basic support "agents", ie: unmanaged extensions.  Connected
agents are granted a limited ability to emit websocket notifications
and process rpc requests from Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan 1133c296b1 websockets: implement notification masking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan d5a55047ab websockets: fix status codes
HTTP 404 and JSON-RPC -32601 are equivalent, so translate
where necessary.  Any other JRPC code received outside of the
HTTP error range should be assigned a 500.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan f6876c15e4 websockets: add ability to call ws client methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:24 -04:00
Eric Callahan 3a21e9d6f0 websockets: add default values for client data
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:24 -04:00
Eric Callahan b296444091 github: create a pull request template
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 06:13:53 -04:00
Eric Callahan 7631999c8f klippy_connection: handle credential exceptions
Handle exceptions should the attempt to fetch peer
credentials on the unix socket fail.  This isn't a hard
requirement for connection and should not cause
the connection to abort.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-08 14:37:11 -04:00
Eric Callahan b21f909705 klippy_connection: get unix socket peer credentials
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-08 14:21:17 -04:00
Eric Callahan eb6aeddf78 update_manager: detect divergent remotes
If a repo's remote has diverged then a reset is necessary as the
attempt to pull will fail.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-07 08:25:26 -04:00
Eric Callahan 2096c380c4 tests: update confighelper tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 17:02:22 -04:00
Eric Callahan 0f70037ffc docs: update documentation for config changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:41:19 -04:00
Eric Callahan 536871ad18 moonraker: bump API Version to 1.0.4
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:33 -04:00
Eric Callahan 77027d252e moonraker: always log configuration exceptions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan bf19bcecae moonraker: report additional configuration info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan fc6714b30d confighelper: backup the entire configuraiton
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan ad00e08d11 confighelper: add support for include directives
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:31 -04:00
Eric Callahan 2e4814978f app: shallow copy arguments before passing to a request
This prevents a scenario where a request handler mutates
the arguments of a WebRequest, which could result in
changing the default "request_arguments" in
"InternalTransport.call_method()".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:36 -04:00
Eric Callahan fb2eacf702 confighelper: make parsed a required argument
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:36 -04:00
Eric Callahan ea25cce38f confighelper: require core component sections
This is a reimplementation of commit d61540cad5,
however this attempt provides a fallback for legacy configurations
that still have configuration in the server section.

This will change how `/server/config` reports configuration.  Options
will always be reported in their respective component's field, even if
they are currently configured in the `[server]` section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:34 -04:00
Eric Callahan f27daac4f4 confighelper: remove "orig section" tracking
This isn't necessary as we don't add new sections to the
original config object when parsing supplemental data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 20:45:17 -04:00
Eric Callahan 5f5f40293e Revert "docs: update user changes"
This reverts commit 82a22b287f.
2022-04-04 20:31:35 -04:00
Eric Callahan ac6cf0fac7 Revert "confighelper: match core components to their configuration"
This reverts commit d61540cad5.
2022-04-04 20:31:23 -04:00
Eric Callahan 7692197678 Revert "confighelper: remove "orig section" tracking"
This reverts commit 9c33eb225c.
2022-04-04 20:31:06 -04:00
Eric Callahan a706d23cfa docs: update mkdocs version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 20:13:01 -04:00
Eric Callahan 82a22b287f docs: update user changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 19:40:50 -04:00
Eric Callahan 366e68c8f4 klippy_connection: send an event when gcode commands are received
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:54 -04:00
Eric Callahan fe3b7456f6 klippy_apis: add pause, resume and cancel print method
These methods may be called internally, which invoke the associated
events.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:54 -04:00
Eric Callahan e05aeac884 proc_stats: report system memory usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:50 -04:00
Eric Callahan 071a430159 klippy_apis: send events on pause, resume, and cancel requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:04 -04:00
Eric Callahan 7c1d6a8f24 websockets: emit added, removed, and identified events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:03 -04:00
Eric Callahan 18169f279e file_manager: add get_directory method
This replaces the previous "get_sd_directory()" method, allowing
consumers to get any registered root path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:03 -04:00
Eric Callahan 393cfa2a0e machine: implement get_public_network method
This allows components to determine the current local
ip address that routes to the internet.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:02 -04:00
Eric Callahan 9c33eb225c confighelper: remove "orig section" tracking
This isn't necessary as we don't add new sections to the
original config object when parsing supplemental data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 15:26:16 -04:00
Eric Callahan d61540cad5 confighelper: match core components to their configuration
Most core components have default options that allow them to
load without a section specified in moonraker.conf.  This resulted
in those options showing up in the [server] section in the
"/server/config" response.  These changes will make sure that those
values show up in the correct section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 15:16:25 -04:00
Eric Callahan 58228ec161 docs: bring up the update_manager documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 5c9409c28d scripts: add a helper for tagging releases
The tag-release.sh script creates an annotated tag containing
Klipper's current state.  Moonraker's update manager parses
this annotation to bind the available Klipper version to this
release of Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 72a85e08d4 update_manager: refactor extension instantation
Don't allow extension errors to propagate, warn and continue
loading the module instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 238b08ea1f update_manager: bind Klipper beta updates to Moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 6afc70a9f5 update_manager: add support for beta git updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 03934d8d81 update_manager: deprecate web_beta type
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 58ea3cfdc7 update_manager: deprecate zip beta type
Use the "channel" option to specify a beta.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:22 -04:00
Eric Callahan f965ce8fd8 git_deploy: refactor tag retrieval
Use git for-each-ref to retreive tags and their associated commit
hashes.  This allows us to limit the amount of tags to 10 and
simplifies the code as the returned objects are already dereferenced.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:22 -04:00
Eric Callahan e9e86c3042 update_manager: refactor AppDeloy class
Don't require the `app_params` argument, instead dynamically
generate the configuration from a dict.  This simiplifies AppDeploy
initialization as the internally generated configurations can be
read in the same way as those supplied in moonraker.conf.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan 54081612ca confighelper: add a setoption method
This should only be used for internally generated configuration
that may change during runtime.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan 93b62236de update_manager: reorder update instances
Instantiate the moonraker instance first, then Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan c8042a5700 update_manager: add support for extensions
While use of "unofficial" klippy extras an moonraker components
is not officially supported, there is no harm in facilitating
updates for these extensions in the update manager.  This adds
configuration which will restart either moonraker or klipper
after an extension is updated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan 16737d086d update_manager: add full update tracking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan a4019bce8e confighelper: add support for optional separators
If "None" is specified as a separator for getdict and the getlist
variants then strings will split along any whitespace character.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan f3b0fbaa34 github: add an announcement issue template
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:39:49 -04:00
Eric Callahan 5643c0ffbe assets: show announcements on welcome page
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 12:17:08 -04:00
Eric Callahan 13bb624bd7 app: include announcements in welcome page context
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:58:31 -04:00
Eric Callahan 156e9652e1 announcements: add internal access methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:37:42 -04:00
Eric Callahan 2edbba3b53 assets: improve welcome page style
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:37:42 -04:00
Eric Callahan 8d49a5d5ee docs: update proc_stats documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-31 16:46:56 -04:00
Eric Callahan 9b5b3cc506 proc_stats: report system uptime in API request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-31 16:44:39 -04:00
Eric Callahan 1968beaa0d app: add a welcome handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 19:59:27 -04:00
Eric Callahan d11357e5f2 authorization: add status methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 14:35:39 -04:00
Eric Callahan 8bb020edc6 moonraker: add method to retreive warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 14:35:07 -04:00
Eric Callahan b85f3081ab power: add retries to custom http requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-29 15:39:04 -04:00
Eric Callahan 8c7247acbb announcements: add retries to http request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-29 15:37:24 -04:00
Brian 'Redbeard' Harrington be2e8623b9 docs: Remove ambiguity from documentation index
Presently the index page of the documentation makes no attempt to
clarify what Moonraker is or even that it has anything to do with 3D
printing or CNC machine control.  This attempts to add a basic
clarification by using the top level description from README.md.

Additionally this adds a second clarification that Klipper is a "3D
printer firmware" (as referenced in the Klipper `README.md`) in this
projects `README.md`.

Signed-off-by: Brian 'Redbeard' Harrington <redbeard@dead-city.org>
2022-03-29 15:20:41 -04:00
Eric Callahan 060ca56fae docs: fix malformed post requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-27 10:33:51 -04:00
Eric Callahan 384ab71d72 docs: update announcement APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 17:26:58 -04:00
Eric Callahan 242fabe7ad announcements: don't capitalize the feed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:48:15 -04:00
Eric Callahan d74d1e7612 moonraker: bump the API version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:41:49 -04:00
Eric Callahan 829b3b5c98 announcements: refactor RssFeed class
Don't require a config object to instantiate and don't attempt
to wrap database namespace.  These changes allow instantation
after the server has started.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:08:54 -04:00
Eric Callahan 5757347994 http_client: use the simple client
While the curl based client is better in most respects, it requires
that libcurl be against with an asynchronous DNS resolver, such
as c-ares, in order to prevent blocking.  As of now it Debian does
not ship with a version of curl with ares enabled.  Fall back to the
simple client until this can be resolved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan 81a482f83d announcements: add support for temporary dismissals
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan 64b6029559 announcements: remove warnings on failure
Its possible for users to have an unstable internet connection.  Log
connection errors rather than warn.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan cd03b91f87 announcements: add support for dynamic feed registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:42 -04:00
Eric Callahan 88b0282900 announcements: dont cache feeds
The parsed feeds are stored in the DB, so there is no
need to cache the result when 304 is returned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 19:15:13 -04:00
Eric Callahan 561f5f4230 http client: minor logging fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 18:21:48 -04:00
Eric Callahan 4b0685852e announcements: remove stale code
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 17:40:15 -04:00
Eric Callahan 1bdedd009f power: fix tasmota command encoding
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 14:46:46 -04:00
Eric Callahan ac8c44095a docs: add announcement documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 12:08:24 -04:00
Eric Callahan 209ace4728 gitignore: ignore .devel and .venv folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:13 -04:00
Eric Callahan 3b208c6889 moonraker: add announcements to core components
Bump Moonraker's the API version to 1.0.2 with the addition of new
endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:13 -04:00
Eric Callahan b1cc766576 announcements: initial implementation
This adds support for announcements retreived via RSS feed from
the "moonlight" GitHub repo.  Announcements may also be procedurally
generated internally.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:12 -04:00
Eric Callahan 4a6732f13a confighelper: implement method to read a dictionary
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:12 -04:00
Eric Callahan 790d77756e app: fix blocking I/O
Open and close static files to be read using the default
thread pool executor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan 27466984df update_manager: fix blocking I/O
When using tempfile.TemporaryDirectory it is possible that
exiting the context will block when attempting to delete
the temporary directory.  Don't use the context manager,
instead create and cleanup the temp dir using the default
threadpoolexecutor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan faf956c65d update_manager: use the http_client component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan 5bf112bcbc power: use the http_client component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:10 -04:00
Eric Callahan 0abb831ea0 moonraker: remove references to Tornado's http client
Add the http client wrapper to core components.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:07:11 -04:00
Eric Callahan 43b19d8a83 http_client: shared client implementation
This abstracts the tornado http client from the rest of Moonraker,
allowing all components to access the client's most used functionality
without importing tornado modules.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:07:10 -04:00
Eric Callahan 4b27e5e41d scripts: pin pyserial to version 3.4
The pyserial-asyncio dependency pins pyserial to any version
greater than 3.4.  Currently pip is distributing version 3.5,
which is not an official stable release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:06:15 -04:00
dependabot[bot] d20d2fd07e build(deps): bump pillow from 9.0.0 to 9.0.1 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 9.0.0 to 9.0.1.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/9.0.0...9.0.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-23 06:48:07 -04:00
Mathis Mensing ee312ee9c6 docs: fix incorrect identify method
Signed-off-by: Mathis Mensing <matmen@dreadful.tech>
2022-03-10 13:57:43 -05:00
pataar a700725681 docs: fix an incorrection in the notifier example
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-03-08 10:45:25 -05:00
Eric Callahan efeea0d8e1 docs: document connection identify endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:56:13 -05:00
Eric Callahan 052dd5e338 moonraker: bump API Version
Addition of a  the "server.connection.identify" API warrants a bump in th
micro version.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:42:27 -05:00
Eric Callahan 3667e0d41f websockets: implement server.connection.identify method
Provide a remote method by which clients may identify their
name, version, and type.

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

fix

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:42:27 -05:00
Eric Callahan b86e86aff2 websockets: report hostname and connected time
By retreiving and storing the hostname in the websocket
header, it is possible to determine a fully qualified domain
used to reach the instance.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 14:20:06 -05:00
Eric Callahan 221df0937d machine: fix typo in cpu description parser
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-02 19:25:53 -05:00
vertigo235 26d6ca009a notifier: Add paused and resumed events to notifier
So we can tell when our printers need our attention. 

Signed-off-by: Josh Jones (vertigo235) <jbjonesclt@gmail.com>
2022-03-02 16:48:06 -05:00
Eric Callahan 94c51c9412 scripts: bump preprocess-cancellation to 0.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-01 15:45:28 -05:00
pataar 9d49659884 notifier: add support for 'attach' property
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-03-01 11:13:32 -05:00
Gregor Majcen 553f8862b5 notifier: typo at job_state:completed
Signed-off-by: Gregor Majcen <majcn.m@gmail.com>
2022-03-01 08:56:47 -05:00
Eric Callahan b6fc692500 dbus_manager: clarify warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-28 06:57:38 -05:00
Eric Callahan 6065e9a0fe docs: add tip to resolve additional polkit warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-28 06:32:04 -05:00
Eric Callahan c87d8d2e51 docs: fix reference to the test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 20:55:03 -05:00
Eric Callahan f93fed62ae docs: update power documentation
If the "restart_klipper_when_powered" option is set Moonraker will
always abort if Klippy's current state is "ready".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 08:39:28 -05:00
Eric Callahan c165c40146 power: improve device initialization
Refactor the PowerDevice initialize() method so that it acquires the
request lock. Always register the "klippy_started" event if the
"restart_klipper" option is set, and always check if Klipper is is
 the ready state before performing the restart.  Remove stale
 PowerDevice methods no longer used.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 07:47:12 -05:00
Eric Callahan 970c8a4181 power: move process_request to the device class
Perform the entire request within a lock to prevent rentry until
the request completes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 20:10:27 -05:00
Eric Callahan 0d93cf2c39 docs: respect OctoPrint's case
Make sure that all references capitalize the "P" in OctoPrint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:53 -05:00
Eric Callahan 8f7f824a47 octoprint_compat: respect OctoPrint's case
Make sure that the "P" in Print is capitalized when referencing
OctoPrint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:52 -05:00
Eric Callahan 65e76aeec8 docs: document remote methods registered by machine
The "reboot_machine" and "shutdown_machine" remote methods may
be called from a Klipper gcode macro to accomplish their respective
tasks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:52 -05:00
Eric Callahan ab09364a98 docs: provide additional context for the secrets module
Advise users to use unique credentials, and warn them that unattended
clients can be configured to steal credentials.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan 2bc43ec3df docs: warn users about overlapping folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan fd8bde7185 file_manager: implement access check method
This method can be used by other components to check if Moonraker has
access to a particular file or folder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan a32bf4a47a file_manager: allow server to start with invalid paths
Don't raise an exeption if the config or log paths are invalid,
add warnings instead.  This allows the user to see what is wrong
and resolve this issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:50 -05:00
Eric Callahan 3a384e62dd file_manager: add registered directory validation
Make sure that paths registered with full access do not overlap one
another, nor that they overlap sensitive folders such as the database,
Moonraker's source, or Klipper's source.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:48 -05:00
Eric Callahan ed20223614 docs: update database config documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-25 14:05:26 -05:00
Eric Callahan 79f867ba83 database: remove debug option
This option was intended for Moonraker developers to live test
changes to write protected namespaces.   This can be accomplished
locally with other methods, thus this option has been removed to
prevent users from compromising sections of the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-25 12:38:36 -05:00
Eric Callahan 0a2c1904c0 docs: fix typo in [secrets] json example
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-24 17:05:09 -05:00
pataar 71de8def8e notifier: create the new notifier module
This component will be a bridge between moonraker and https://github.com/caronc/apprise. This way users can easily add all kind of notification services to their printer.

Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-02-23 17:05:55 -05:00
Eric Callahan 501af62018 docs: update /server/info and /machine/system_info docs
These endpoints now return additional values.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:25:52 -05:00
Eric Callahan 1fbfb90500 tests: update test_server for changes to moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:50 -05:00
Eric Callahan 54f2ee61d0 machine: report the python version in system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:50 -05:00
Eric Callahan 7679f8063f moonraker: remove the python version check
Moonraker depends on "future" annotations and uses fstrings, so
 versions of Python older than 3.7 will fail to load and never make
 it to the version check.

 Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:10 -05:00
Eric Callahan f83f476f81 moonraker: report the api version
Start tracking the Remote API version separately from the application
version.  This allows the API to stick to semantic versioning while
and track the application version separately.  This is necessary as
we prepare to release a beta.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:07 -05:00
th33xitus 8b8cb66481 readme: fix link for MainsailOS
readme: replace `Meteyou` with `Mainsail-Crew`

docs: replace `meteyou` with `mainsail-crew` in web_api.md

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-02-23 10:24:39 -05:00
Eric Callahan 8ff54e2372 docs: update documenation for "power on queued" changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 09:13:54 -05:00
Eric Callahan 7ab1dda772 power: change behavior of "on when queued"
Rename the "on_when_upload_queued" option to "on_when_job_queued",
deprecate the former.  This option now applies to any queued job while
the device is off.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 14:36:46 -05:00
Eric Callahan 2b1a3e5603 klippy_apis: fix blocking issue in start_print and do_restart
The "wait_connected" method would block indefinitely until a klippy
connection is established.  This isn't the behavior we want, we only
want to wait "if" a connection has been established until Klippy
reports that its startup sequence is complete.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 14:34:14 -05:00
Eric Callahan 86469903f3 tests: add database tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 3edb4b1bad tests: add support for loading a database
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f2f1d413d4 scripts: introduce dbtool
This tool may be used to backup and restore Moonraker's lmdb
database without depending on the "lmdb-utils" package.  The
backup is done to a plain text file in cdb format, so a backup
may be restored on any platform.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 55baad1ad0 tests: rework path_args and klippy fixtures
Initialize the temporary directory in a "session_args" fixture that is session
scoped.  Move the Klippy process to a session scope, restarting the process
only when necessary.  This combination speeds up tests as it reduces disk
I/O and the overhead of starting the Klippy process for each test.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 81f2418d78 tests: fix error in websocket_client fixture
A jsonrpc request is a notification when no ID is present.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 348d45e87c tests: increase the timeout to 60 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan e6b4e54bea tests: fix the server pending tasks tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 6946f67dbf tests: increase the klippy process timeout to 2.5 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f7f487ac18 database: sort protected namespaces before storing them
This makes the order in which they are reported consistent,
as the namespaces are stored in a set.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 888fb58c4f database: sync namespace bugfix
Use the transaction object to overwrite keys so that we don't
move the cursor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 2b7a5ff035 tests: assign the WebsocketError to an static variable
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan d630b79e8b tests: http client fixes
Correctly encode the query string.  Use the query string for DELETE
requests in addition to GET requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 5f96822c90 database: don't overwrite "get" server errors
Make sure the correct exception is raised when "get_item" fails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 2d28a3eeff database: fix typo in http exception
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 96b00549cf database: validate that namespace exists in ns_contains
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 0bd12c8dec database: don't allow sync against an empty dict
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f3cd177a02 database: move_batch() fix
Raise an exception if the key lengths for the source and destination
keys do not match.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 11e299558d database: fix insert_batch()
If a namespace does not exist insert batch must create a new one rather
than raise an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan bb39a3c1b2 database: handle invalid reduce results
It is possible to reduce to a value that is not a dict in "insert_item()"
and "update_item()".  Raise a ServerError with a clear description of
what went wrong in these situations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 89e78b9a00 database: fix type reported in overwrite warning
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan c1104617b6 database: fix typo in sync implementation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 3c92f42d49 database: allow synchronous calls before the server starts
It is possible that Moonraker can be instantiated while the eventloop
is running during tests.  To avoid errors allow synchronous calls until
the server starts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 9ab6d0e83d update_manager: support database changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:34 -05:00
Eric Callahan c081fa49a1 history: update for database changes
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 9e57db0611 file_manager: add method to retreive the metadata storage object
This allows other components to synchronously access and update
metadata if necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 0dd10ce116 file_manager: update for changes in the database
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan b43f4623fc authorization: update for changes in the database
Since the User DB is not going to be large cache the users
in local memory and sync with the DB when changes are
made to the local user store.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 46f74329d3 database: reduce duplicate code
Add a _get_db() method that perform the check for existance.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e2a62f80d4 database: introduce record based operations
Now that all transactions run in a thread it is possible for them to
interleave.  The record based operations allow for batch operations
within a single transaction.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e029b6c582 database: refactor to remove duplicate code
Wrap command implementations in with a _run_command() method.  All
database commands now return a Future object.  If the command was
run before the eventloop starts its possible to immediately query
the Future's result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 65d1f23352 database: add a sync method
Similar to the update method, however sync will remove any
keys in the database not in the new value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 781e3e6250 database: combine namespace wrappers
Rather than creating two wrappers, use a single wrapper whose methods
always return a future or awaitable.  If the operation occurs during
the __init__() method of a component it will be syncrhonous, and the
result from the future can be immediately queried.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 4d0a43cb25 database: refactor initial check for empty keys
Rather than reading out the entire database, attempt to pop off
empty keys in each database.  This should should speed up
init on platforms with slow disk I/O and prevents reading
large namespaces in memory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e754d123dd database: improve ns_contains method
It isn't necessary to read out the entire namespace, just attempt
to fetch the record and reduce the key list.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 43c1b998b0 database: add methods to clear and update a namespace
Since transactions are now threaded we need updating
and clearing a namespace needs to be performed within
one transaction.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e895b10ac3 database: run transactions in a thread after the eventloop starts
Database transactions can perform disk I/O tasks, which at times will
block the eventloop.  Run all transactions in threads to prevent this
from occuring.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 1be639b99a eventloop: use the default executor for run_in_thread()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan ac55b95c1d database: Add unsafe shutdowns to the log rollover
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 5f9706f6be test: initial testing framework
This adds the framework for unit testing Moonraker via pytest.
Initally only moonraker.py, klippy_connection.py, and confighelper.py
have acceptable coverage.  Coverage for other modules will be added on
an incremental basis, when most of Moonraker's source is covered tests
will be conducted via GitHub actions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:41 -05:00
Lars Pöpperl 34f607c061 docs: add alternative sample file for home assistant
Signed-off-by: Lars Pöpperl  <lars.poepperl@gmail.com>
2022-02-17 11:03:30 -05:00
Simon Germain 11f4ae75cc octoprint_compat: add webcam settings
Signed-off-by: Simon Germain <sgermain06@gmail.com>
2022-02-17 10:46:05 -05:00
Eric Callahan f79439aedd funding: add a ko-fi button
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-16 05:44:10 -05:00
Eric Callahan c2861a1391 app: correct location header encoding
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-15 14:39:33 -05:00
Eric Callahan e2d92b5575 confighelper: use read_file() rather than read()
The read() method will return an empty list if the file specified
does not exist or if the read failed in some fashion.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-15 11:42:50 -05:00
Eric Callahan 0e27a949af docs: update power documentation for "smartthings" devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-14 06:26:34 -05:00
Eric Callahan 10703321b0 power: fetch the Smart Things token option as a template
This allows users to store their token in a "secrets" file

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-14 06:19:37 -05:00
Mitch Gallman 0dc05eac76 docs: add smartthings power documentation
docs: add smartthings power documentation

Signed-off-by: Mitch Gallman <mitchell.gallman@gmail.com>
2022-02-14 06:12:52 -05:00
Mitch Gallman d01b8a9763 power: add support for smartthings switch
power: add support for smartthings switch

Signed-off-by: Mitch Gallman <mitchell.gallman@gmail.com>
2022-02-14 06:12:52 -05:00
Eric Callahan b60153c919 workflows: disable blank issues
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-13 20:50:22 -05:00
Eric Callahan ee11ed2a15 confighelper: fix the get_hash() method
Include the option's values in the hash.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 20:48:27 -05:00
Eric Callahan 9be93ff445 docs: add "info_tags" to update manager status
This also fixes some stale documentation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 11:32:32 -05:00
Eric Callahan ecfad5cff1 update_manager: add support for application tags
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 10:50:28 -05:00
Eric Callahan 92eda982ce docs: clarify contributing documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-10 16:53:11 -05:00
Pedro Lamas cb5ac86af7 metadata: add support for parsing layer count in Cura
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-02-10 12:11:20 -05:00
Eric Callahan 94a2949c00 moonraker: report missing klippy requirements
Moonraker requires that some Klipper objects be configured
and loaded.  This check has always been performed and logged,
now track and report missing requirements.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-10 08:28:51 -05:00
Eric Callahan b4ddffd5d1 moonraker: refactor KlippyConnection
Move the KlippyConnection class into its own module.  Refactor
init to use loops rather than callbacks, this reduces complexity
of tracking and cancelling callback handles.

All Klippy state previously tracked by the Server is now in the
KlippyConnection.  This improves testing and makes the code
less ambiguous, ie: the `server.make_request()` method is not
as clear as `klippy.request()`.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-09 19:15:11 -05:00
Eric Callahan 737cf8a2cb mooraker: refactor main entry point
Move the version check to the top of the module.   An older version
of python is unlikely to make it beyond the initial import statements,
so print a message to stdout and stderr.

Move argument parsing out of the main method.  This makes it possible
to invoke main without parsing command line arguments, which is useful
for tests.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-09 07:35:01 -05:00
Eric Callahan 6efcffa028 moonraker: perform error checking when registering remote methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-09 06:48:23 -05:00
Eric Callahan a04e91c046 proc_stats: track the loop blocked count
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 20:24:00 -05:00
Eric Callahan 9e9f9ee0fd moonraker: add the SIGTERM handler in server_init()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 1072958534 authorization: start the prune timer in component_init()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan a5eff12131 proc_stats: start timers in component init
Avoid adding  event loop callbacks in a component's "__init__()" method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 0f7af929f1 file_manager: suppress "root_update" notifications during init
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 47f0437973 eventloop: add a reset method
Rather than instantiate a new version of the event loop wrapper
we can simply reset the internal event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 18:14:46 -05:00
Eric Callahan a5c49e8742 moonraker: refactor init sequence
Don't load components and start the server from within the
__init__() method.  Break those out and call them in __main__().
This makes unit testing individual components possible.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 11:54:39 -05:00
Eric Callahan 35d8d88855 confighelper: remove direct component imports
Dont directly import components for instance checks.  Instead
check to see if the type is serializable, if not store the string
representation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 11:20:31 -05:00
Eric Callahan f6d8de2cee utils: move config backup methods to confighelper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 10:58:00 -05:00
pznamenskii 6749d3836e docs: add Home Assistant camera example
Signed-off-by: Pavel Znamenskiy <[pznamenskii@gmail.com](mailto:pznamenskii@gmail.com)>
2022-02-03 19:17:11 -05:00
Eric Callahan 509759ba0d secrets: fix ConfigParser to Dict conversion
The result should be a dictionary of dictionaries rather than a
dictionary of SectionProxy objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 17:57:50 -05:00
Eric Callahan 5a966836b5 moonraker: backup the most recent working config
Attempt to take a backup of the configuration file if Moonraker
loads successfully and has not seen a config change.

If Moonraker fails to load due to a config error, attempt to fallback
to the backup configuration.  If that fails, exit the server.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 17:19:17 -05:00
Eric Callahan 4ec781d66b confighelper: minor cleanup in get_configuration
Its safer to let the attempt to read fail before additional error
checking.  Also there is no need to remove DEFAULT from
config.sections(), as it can't be there per the Python docs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 12:19:29 -05:00
Eric Callahan ae8cab356b moonraker: gracefully handle invalid log paths
Don't exit the server if the log path is invalid.  Instead start
logging to stdout and add a warning for the user to
resolve.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 11:21:34 -05:00
Eric Callahan 305e002f8c docs: update docs for "klipper_device" power types
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 08:38:44 -05:00
Eric Callahan 0b13e2da44 power: add support for gcode_macro Klipper devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 08:14:48 -05:00
Matthew Humphrey aca7cb78b9 module: power
Add separate output_id configuration attribute for TPLink Smartplug device.

Signed-off-by:  Matthew Humphrey <mhumphrey@gmail.com>
2022-02-02 17:35:18 -05:00
Eric Callahan 10ac044485 scripts: add a --root argument to set-policykit-rules.sh
If a user specifies this then root is allowed to run the script.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 15:20:49 -05:00
Eric Callahan f616c83ebc docs: clarify PackageKit documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 14:12:03 -05:00
Eric Callahan 5ec98cf0ba scripts: workaround pip 22.0 issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 14:08:13 -05:00
Eric Callahan de796a9ec7 app_deploy: don't update pip
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 12:14:09 -05:00
Eric Callahan 13591d0a5b scripts: do not allow set-policykit-rules.sh to run as root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-29 14:07:15 -05:00
Eric Callahan b4ad6692e3 update_manager: fix klipper path regression
Commit 7401192 introduced a regression where the saved klipper
paths were not loaded into the Update object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-29 11:03:08 -05:00
Pedro Lamas 287982acdd power: initial support for Klipper Devices
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-01-29 07:53:30 -05:00
Eric Callahan 7c8c0e715f scripts: update set-policykit-rules.sh
Check for the moonraker-admin Supplementary group
in the moonraker service file and add it if necessary.

For PolKit versions > 0.106 make sure that the process
is launched with the moonraker-admin group before
granting any polkit permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 468ea36bba scripts: update install-moonraker.sh
Add the "moonraker-admin" supplementary group to the service unit
file.  Check if polkit rules are available after installation, if not
advise the user that they may wish to run set-polkit-rules.sh.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan d396dbd2cb utils: add support for versioning shallow clones
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 471885c3a2 git_deploy: add support for shallow clone tags
Shallow clones don't report the tag in git describe, so use
git rev-list to extract the tag and prepend it to the version
string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 7401192478 update_manager: store klipper paths in the database
If Klipper or its python executable is located at a custom path
this allows moonraker to instantiate its update on startup
rather than wait for Klipper to connect.  This also resolves an
issue where Klipper's update state is always refreshed on startup
when its located in a non-default path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan ede671f0df app_deploy: handle exceptions in same path check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 14f1b6f936 docs: update documentation for dbus additions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2022-01-28 18:00:21 -05:00
Eric Callahan 6aecd7b26d machine: add "none" provider
When the "none"  provider is set service action APIs will be disabled
and return an error when called.  Service state tracking is also
disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan b1a232efce update_manager: remove redundant locks
All requests to update, refresh, recover, or reinstall must acquire
the command lock. Given that the individual Deployment implementations
are not (and should not be) called from outside of a request the locks they
use to prevent unwanted re-entry are redundant, confusing, and could
potential result in a deadlock if used improperly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 4d473969db scripts: add packagekit dependency to install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan a92847771d scripts: add set-policykit-rules.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0e6fbb12b0 update_manager: add support for PackageKit updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 744f14d6f9 scripts: add pk-enum-converter.py
This is added to distrubute the changes made to "enum-converter.py"
taken from the original PackageKit repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0dbb6d51a8 moonraker: introduce thirdparty package
This allows for the inclusion of 3rd party Python Source
within the Moonraker package.  Initially this includes
a python source file containing PackageKit enumerations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 4ddd77430a update_manager: move low level package methods to a provider class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 3b27ab49f1 update_manager: use the machine component to restart services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan be338ad039 machine: add systemd dbus provider implmentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 73f0d5503d dbus_manager: add initial implementation
The DBus manager is a core component that connects to the
system bus, providing resources used to communicate with other
processes on the the system through the DBus interface.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0d6791a320 machine: refactor systemd cli implementation
Move all systemd cli calls to its own provider class, inherted from
a base provider class.  This is in preparation for multiple provider
implementations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 9b6161a6b0 proc_stats: add stat callback registration
This allows other components to be register callbacks that will
be executed in the stat update timer. This is useful for methods
that wish to poll subprocess commands, as its desireable to
prevent multiple subprocesses from running simultaneously.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan f4c5e808c3 shell_command: add exec_cmd method to factory
This allows for users to execute a method directly rather than
create a command.  This is useful for fire once commands that
do not need to inspect the return code unless there is an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 89d0bbdb63 shell_command: add support for sending data to a process
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 8546cd6ac5 shell_command: use a custom protocol for callbacks
Rather than override the Process class instead create a custom
protocol that forwards data over callbacks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 9911b5c7dd app: don't allow open redirects in '/server/redirect'
Validate that the URL argument against the `cors_domains` option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 14:05:48 -05:00
Eric Callahan 41c19e4b9a github: modify issue templates
Add some additional required fields that are helpful in diagnosing
issues, and remove the "what did you expect to happen", as that
tends to be implied in the issue.  Also allow blank issues so
announcements can be made.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 12:07:23 -05:00
Eric Callahan 0c5a0fd979 wled: add retries to http request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 06:16:54 -05:00
Eric Callahan 209bdc18da power: sleep for 1 second between failed retries
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-28 06:12:56 -05:00
Eric Callahan 04477705b0 app: content disposition fix for file names containing commas
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-27 19:21:25 -05:00
Eric Callahan 7fcd84bbe4 power: add retries to http requests
This is an attempt to mitigate 599 errors raised by tornado's
curl based http client.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-27 17:00:08 -05:00
Richard Mitchell 1cac7399f9 wled: deprecate color_order option
Support more synonym strings for colors
Case insensitive string type checks
Show errors in UI if e.g. wrong color was selected
Public color_config not color_order as it has confused users
Fix documentation for white stealthburner example

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-25 06:02:36 -05:00
Eric Callahan f5ceefbb8d websockets: log if the connection is proxied
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-21 06:57:52 -05:00
Eric Callahan e103accdfb websockets: refactor open/close logging
Log the User Agent when a websocket is opened.
When a websocket is closed log the close code, close Reason, and
time elapsed since the last pong was recieved from the client.
When Moonraker shuts down send a 1001 Code with Server Shutdown
as the reason.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-20 14:20:23 -05:00
Eric Callahan 09689143b5 shell_command: python 3.10 fix
Remove the deprecated "loop" parameter in asyncio.gather().

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-19 15:18:36 -05:00
Richard Mitchell 5f54a23f3e Richardjm/wled serial asyncio (#332)
wled: Use pyserial-asyncio for wled

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-15 14:22:49 -05:00
dependabot[bot] 60f2e3e1c7 build(deps): bump pillow from 8.3.2 to 9.0.0 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.3.2 to 9.0.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.3.2...9.0.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-13 05:53:30 -05:00
Eric Callahan dd6a06e9de docs: update proc_stats documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 19:58:49 -05:00
Eric Callahan 4c99f99cf0 proc_stats: report system cpu usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 19:58:49 -05:00
Lukas Fink 693a34d562 docs: add 'off_when_shutdown_delay' documentation
Signed-off-by: Lukas Fink <lukas.fink1@gmail.com>
2022-01-12 19:58:25 -05:00
Lukas Fink 3cbc2c2ca8 power: add 'off_when_shutdown_delay' option
This option allows to delay switching off a power source after klippy
shuts down.

Signed-off-by: Lukas Fink <lukas.fink1@gmail.com>
2022-01-12 19:58:25 -05:00
Richard Mitchell cfd3d63a0d wled: Add serial support for direct communication (#325)
wled: Add serial support for direct communication

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-12 19:56:14 -05:00
Eric Callahan 59fd35827e docs: add button documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 4c087612d8 mqtt: allow internal access to API endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 2025332e6f button: initial implementation
Adds support for GPIO buttons.  Each button is configured to render
a template when pressed and/or released.  The button event
templates recieve a context with  a "call_method" field, allowing
them to call nearly all Moonraker APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan a652845843 moonraker: add register_component() method
Allow base modules to register themselves as components during
initialization.  This makes them accessible via lookup_component()
across the entire application.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 27c65e0a64 application: support internal API consumption
Track registered endpoints and allow internal APIs calls through
their JSON-RPC method names.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 3bd5f7edbd template: add support for async rendering
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan fc5e34096a gpio: add support for line events
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 9346186337 gpio: refactor pin parsing
Return a dictionary of pin params rather than a tuple

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-06 11:56:41 -05:00
th33xitus 505c1bfdba metadata.py: fix parsing of IdeaMaker nozzle_diameter
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-06 11:55:52 -05:00
th33xitus 6c8e3690a7 chore: remove unused import
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus 2c732b7afa metadata.py: add parsing of filament name
This commit will add parsing of optional filament name metadata for:
- PrusaSlicer and it's derivatives
- Simplify3D
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Filament name = {material_name}
IdeaMaker:
;Filament name = {filament_name1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus d145442d4b metadata.py: add parsing of filament type
This commit will add parsing of optional filament type metadata for:
- PrusaSlicer and it's derivatives
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Filament type = {material_type}
IdeaMaker:
;Filament type = {filament_name_abbreviation1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus 20d3c9961d metadata.py: add parsing of nozzle diameter
This commit will add parsing of optional nozzle diameter metadata for:
- PrusaSlicer and it's derivatives
- Simplify3D
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Nozzle diameter = {machine_nozzle_size}
IdeaMaker:
;Nozzle diameter = {machine_nozzle_diameter1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
Pedro Lamas 9d7baa1eb6 utils: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas d997fd637a moonraker: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 05af4babb9 mqtt: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 7c5d840c1b zip_deploy: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 5f20dafadb docs: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Eric Callahan 1d1ce0671d docs: fix jinja2 example
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-28 11:05:15 -05:00
Eric Callahan adfe8a67b6 docs: fix error in mqtt power device documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-28 10:49:27 -05:00
Eric Callahan 0a541bbea1 docs: add documentation for the secrets module
Update the documentation for all relevant options that may
be resolved from secrets.

Signed-off-by:  Eric Calalahan <arksine.code@gmail.com>
2021-12-24 14:44:48 -05:00
Eric Callahan 1e440741da mqtt: add support for "secret" credentials
Deprecate the "password_file" option in favor of "password".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan c5fd863bb7 power: add support for secrets
The "user", "password", and "token" options are templates
that can resolve items stored in the secrets file.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan a269de5dc0 confighelper: add load_template method
This is an alternative to gettemplate that always returns a
template.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan a4f960d40c confighelper: implement deprecation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan 9dadf50ac6 templates: add support for secrets
Add the secrets module as a Jinja2 Environment global.
All templates will be able to access secrets as if it were
a dictionary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 12:41:28 -05:00
Eric Callahan d498eefd13 secrets: initial implmentation
Add support for an external "secrets" file that may contain
usernames, passwords, and tokens.  This file may be in
"ini" or "json" format.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 12:41:28 -05:00
Eric Callahan f4e3803647 metadata: refactor thumbnail parsing
Check for "Prusa" style embedded thumbnails by default for
all slicers.  This is becoming a standard, as it is now available
in Cura, Ideamaker, and Simplify3D via plugins.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-23 06:38:13 -05:00
Eric Callahan 51ca383591 docs: add missing headers to config examples
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:50:25 -05:00
Eric Callahan 01245ea8a1 docs: document the publish_mqtt_topic remote method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:31:00 -05:00
Eric Callahan 92954245fa mqtt: implement a "publish_mqtt_topic" remote method
Allow Klipper to publish MQTT topics from gcode macros.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:31:00 -05:00
Eric Callahan 57b00cb33a docs: add a warning for tplink devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 12:46:54 -05:00
Eric Callahan 5f7c6d623c docs: update "octoprint_compat" documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 07:49:41 -05:00
Eric Callahan cc1a55a871 metadata: always create a miniature thumbnail
Don't require that gcode files embed two thumbnails.  When
a single large thumbnail is parsed use pillow to create a
small one.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 07:29:16 -05:00
Eric Callahan 5766d16edc octoprint_compat: default printer profile fix
Cura's Octoprint plugin expects an "axes" field for each profile.
Report these values to match the default values used by the
plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan ec43f5e9b6 octoprint_compat: make UFP uploads optional
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan e2fb1cc931 octoprint_compat: add support for "print on start"
Cura's Octoprint plugin does not set the 'start' flag on uploads
when UFP is enabled.  Instead it waits for the upload to
finish then issues Octoprint's "file command" request.  Add
limited support for this API, mimicing how uploads are normally
handled.

Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan e46b4994d4 app: add support for empty responses
If a dynamic request handler returns None with "wrap_result"
disabled, set the return status to 204.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 18:12:27 -05:00
Eric Callahan b369173f94 app: refactor upload handler registration
Move upload handler registration out of the file manager.
Register the primary hander in the app module, and the
Octoprint Comptaiblity handler in octoprint_compat.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 16:53:33 -05:00
Eric Callahan ac9eaa7681 app: set the status to 201 for uploads
Set the location header when the upload returns a valid result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 15:32:28 -05:00
Eric Callahan 3e70e4b4ce machine: report additional release info
Report information contained within a linux distribution's
release file if it exists.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 16:58:21 -05:00
Eric Callahan 1333413db7 update_manager: fix pip location resolution
When creating a virtualenv, some operating systems provide
symbolic links back to /usr/bin/python3 rather than copy
the python exectuable over.  Previously Moonraker resolved
this symbolic link, resulting in a failure  to locate pip.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 12:30:26 -05:00
Eric Callahan 7d1cf435f7 authorization: report invalid "trusted_clients"
Add warnings that are reported to clients and logged if an
invalid trusted client is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 08:37:54 -05:00
Eric Callahan 828be30466 docs: refactor [power] documentation
Separate the configuration for each device type, making it
easier for users to identify options specific for each
device.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 08:00:53 -05:00
Eric Callahan d7bfb7744a docs: document mqtt power device configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-19 12:35:14 -05:00
Eric Callahan d0b1621bd5 power: add mqtt device support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-19 08:00:13 -05:00
Eric Callahan f57bddfe4a mqtt: send connect and disconnect events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 3ac8f8cd81 mqtt: add method to report instance name
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan e2b821e90c confighelper: add gettemplate method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 2142d344dd template: add support for Jinja2 template evaluation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 3f7cc53baa moonraker: don't allow a unix socket to open while closing
Hold the closed mutex in the "connect()" method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-12 10:24:19 -05:00
Eric Callahan 31dd758d52 moonraker: unix socket fix
Handle connection errors in the read loop.  Set a maximum number
of consecutive errors encountered during a read before aborting.
Resolves #309.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-12 06:40:53 -05:00
Eric Callahan a4abec43d5 mqtt: fix non-threadsafe on_socket_open callback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 14:31:10 -05:00
Eric Callahan c6cddf4b05 moonraker: logging improvements
Move logging setup to the Server class and enable asyncio debugging.
Sanitize debug logging for all "/access" endpoints so tokens and
passwords are not logged.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 14:16:15 -05:00
Eric Callahan c69ded21b0 job_state: initialize in "klippy_started" event
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 08:44:55 -05:00
Eric Callahan 08111415be update_manager: auto-refresh fix
Only refresh a provider when the update interval has expired.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 56a98aa8ed update_manager: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 511c91829a power: use native asyncio socket streams
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan ae4c4ad678 moonraker: use native asyncio unix streams
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan df674ae476 proc_stats: replace PeriodicCallback
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 5dadc2067d data_store: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:32:52 -05:00
Eric Callahan 4e625aef37 authorization: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:32:52 -05:00
Eric Callahan 69a06dd12a eventloop: add a timer class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-09 14:38:32 -05:00
Frank Tackitt 2216e85fef Bump preprocess-cancellation to 0.1.6
This fixes a bug that caused retraction moves to be included in bounding box calculations.
2021-12-09 14:26:45 -05:00
Eric Callahan 54abd27486 paneldue: multi-extruder fixes
Sort heater response so that the bed is displayed first, followed
by extruders in ascending order.  Set inactive extruders to
"standby" if they are on rather than "active".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 19:31:41 -05:00
Eric Callahan f5f87bf08c file_manager: metadata move fix
If the destination exits in the metadata database it is necessary
to either overwrite it with the source metadata or delete it
so that the new metadata can be rescanned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan 18b84b8d9f file_manager: don't request metadata from non-gcode files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan ec29787edd file_manager: inotify timing fix
Flush pending delete events when move and create events are detected.  This resolves timing issues with rapidfire create/delete events.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan 1ad83cec97 mqtt: fix connect/reconnect issues
Handle all potential exceptions.  Run the connect/disconnect
in another thread, as its possible for some calls to block
the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-06 08:38:27 -05:00
Eric Callahan ac73036857 machine: fix issues with network interface parsing
Don't parse non "ether" types.  Don't add interfaces that don't
have mac addresses and at least one IP address.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 17:12:21 -05:00
Eric Callahan c0c34ea045 file_manager: fix object processing option name
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 14:08:41 -05:00
Eric Callahan 7b9c6c5e77 Merge branch 'master' of https://github.com/Arksine/moonraker 2021-12-05 09:14:54 -05:00
Eric Callahan 6a90bfa480 update_manager: prevent apt from fetching updates on startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 09:14:49 -05:00
Pedro Lamas 8c12c137d0 moonraker: move GitHub issue templates to correct folder
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-05 07:01:28 -05:00
Stephan Wendel f22e16d8cc FIX: sudo_fix.sh not working on armbian
According to https://github.com/Arksine/moonraker/issues/241

Signed-off-by: Stephan Wendel <me@stephanwe.de>
2021-12-05 06:51:30 -05:00
Rafael 6852982406 Add API key info to example-home-assistant.yaml
Currently the file makes no mention of any type of auth, so I've added a short example with an explanation of when you should use it.

Signed-off-by:  Rafael Schridi <r.schridi@gmail.com>
2021-12-05 06:49:26 -05:00
Pedro Lamas d884e5288c moonraker: adds GitHub issue templates
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-05 06:48:21 -05:00
Eric Callahan b1c9a96040 metadata: add support for parsing layer count
Currently this is only supported in SuperSlicer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan cfa5f4a432 file_manager: don't emit events when a node is processing metadata
When a folder is copied processing can take several minutes, depending on the size and number of gcode files in the
path.  Suppress all file events on a node until processing
is complete.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan b3d2307d36 docs: document object processing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan 9dd0797f49 file_manager: ignore duplicate "create_file" notifications for gcode files
The the cancel object post processor results in an additional
"create_file" notification when the old file is replaced.
Track previous "create_file" notifications for valid gcode
files so the dups can be suppressed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan ea6c78773e scripts: add preprocess-cancellation dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan b7c64443db file_manager: refactor metadata processing
When destructively iterating over pending metdata requests
don't pop the pending item until metadata processing is
complete.  If a call to `parse_metadata()` has a request
pending, return the asyncio Event associated with that
request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan 88137d5898 file_manager: add option to enable object postprocessing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2021-12-05 06:45:06 -05:00
Eric Callahan 6bd46a4433 metadata: add support for object postprocessing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan f00263b782 docs: document the refresh_interval option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:41:18 -05:00
Eric Callahan 13bc4c5b9b update_manager: handle system package init
Force refresh requests after server initializaton.  Update
package state after installation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan e8c1798a13 update_manager: Prune stale data in the database
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 3203950ca9 update_manager: prevent refresh requests from spamming
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 4c68086798 zip_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan bb87917c97 git_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 74a03fca59 app_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan eb8f1e2526 update_manager: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:31 -05:00
Eric Callahan 3a547fb530 base_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:24 -05:00
Eric Callahan d23f72d232 database: increase max namespaces to 100
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:24 -05:00
Eric Callahan c4fa76f217 update_manager: remove refresh time tracking
This is preparation for moving refresh time tracking to the deployment
provider class.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:20 -05:00
Eric Callahan d8a31fc249 update_manager: remove init success check
Now that the update manager doesn't rely on the rate
limit it should always initialize successfully.  An individual
updater may still fail to initialize, however this does
not prevent the update manager from loading.

Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan 7f0712183d update_manager: remove GitHub rate limit initialization
The rate limit fields can be extracted from the response
to an API request, even if that request fails with 403.  This speeds up update manager initialization and reduces
failures if github is unreachable.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan f7bdfb4d6b confighelper: add get_hash method
This returns the checksum of a config section and can be used to check
if the section has changed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan eda5623b2e database: fix invalid key handling
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:10:42 -05:00
Eric Callahan 3df0f3ffe4 job_queue: add websocket notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-27 10:23:04 -05:00
Eric Callahan 269897bef7 job_queue: rename "resume" api to "start"
Given the changes to the job queue, "start" is a more
appropriate API call than "resume".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-27 06:04:47 -05:00
Eric Callahan 4837ea56cb job_queue: register remote method to control the queue
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 20:35:10 -05:00
Eric Callahan e9b3d8e7ae docs: update job_queue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 20:01:16 -05:00
Eric Callahan 28e88b1363 job_queue: dont attempt to start a print when empty
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-26 19:53:57 -05:00
Eric Callahan 784b8b9b18 file_manager: attempt to start gcode uploads prior to queueing
Only attempt to queue the upload if the job failed to start.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 19:46:59 -05:00
Eric Callahan f09c313c5b job_queue: fix resume request
Make sure that the queue is set to ready after resuming,
even if the next job is unable to be loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 18:11:11 -05:00
Eric Callahan d25c3c1d49 job_queue: queue state fix
When not in automatic mode make sure the queue
state is paused after adding a job to the queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:19:44 -05:00
Eric Callahan 0f428acd07 docs: update job_queue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:00:42 -05:00
Eric Callahan e8cdd8a928 job_queue: add "automatic_transition" option
When set to true, the queue will automatically transition
to the next job in the queue upon completion of the
current job.  When false the queue will pause between
jobs, requiring that the user manually resume.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:00:42 -05:00
Eric Callahan 0b9fa7d87e zeroconf: more refactoring
Resolve issues with ipv6 addresses.  Only register the
net_state_changed event handler if Moonraker is bound
to all interfaces.  Build a new instance of ServiceInfo
for each update rather than attempt to modify the
existing object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 15:51:49 -05:00
Eric Callahan c89a9152b5 moonraker: log exceptions when a component_init fails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 14:39:01 -05:00
Eric Callahan b70254feed zeroconf: minor formatting fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 14:30:47 -05:00
Clifford Roche 513a122290 zeroconf: Don't close on update
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-26 14:28:06 -05:00
Clifford Roche 6258082d70 zeroconf: Implement new approach for ip detection
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-26 14:28:06 -05:00
Eric Callahan 76e431330c machine: service unit detection fix
Add `--plain` and `--no-legend` to the command to list service units.
This fixes a bug where  a service could be prefixed with a unique
character, resulting undetected services.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 09:02:05 -05:00
Eric Callahan 685bd72274 app: add request debug logging
This mimics the logging available over JSON-RPC requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 06:11:13 -05:00
TravisTX d020dc81db docs: document the protocol config option
Signed-off-by:  Travis Collins <travistx@gmail.com>
2021-11-25 19:22:52 -05:00
Eric Callahan f0831cbe3c moonraker: prevent duplicate failed components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 17:16:09 -05:00
Eric Callahan 2a0be55a8d power: remove has_gpio check
This prevents loading the gpio module unless a gpio
device is configured.  Resolves #283.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 17:16:09 -05:00
Eric Callahan ccb86ea039 proc_stats: check for network updates every 10 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 08:18:24 -05:00
Eric Callahan b33183f60f machine: add support for parsing network info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 07:58:25 -05:00
Eric Callahan 7a99f83396 server: refactor get_host_info method
Return a dict with the host name, server address, server port, and ssl port.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 05:43:49 -05:00
Pedro Lamas 16c8063900 docs: fixes minor typos
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-24 11:33:23 -05:00
Eric Callahan 50fd8c9cc4 confighelper: track default values
This restores the behavior before commit 5b4de64.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-23 13:55:24 -05:00
Eric Callahan 0a1367744f confighelper: fix json parsing error for gpios
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-23 08:21:56 -05:00
Clifford Roche 4e8e4f7d14 zeroconf: add module for zeroconf discovery
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-22 15:03:33 -05:00
Clifford Roche 44abc64533 machine: add serial number attribute for cpu
Adds the property "serial_number" to the process info structure.

Signed-off-by:  Clifford Roche <clifford.roche@gmail.com>
2021-11-22 14:00:34 -05:00
Eric Callahan 97e27661d7 gpio: remove get_gpio_out_from_config method
The confighelper object now can setup  gpios directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-21 06:26:09 -05:00
Eric Callahan 0e4e3383e3 update_manager: node update fix
Use "getboolean" rather than "get" to fetch this option.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan fd6d318f0a power: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 69e2fb810f update_mananger: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 4572bd955e paneldue: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 9ebae5fd5a mqtt: use extended confighelper methods
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 22807ee393 authorization: use extended confighelper methods
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 845689fde1 confighelper: add getgpioout method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:55 -05:00
Eric Callahan 0b25350ebc confighelper: add support for getlist and getdict
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:07 -05:00
Eric Callahan c0ae10bef6 confighelper: add has_option method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:38:37 -05:00
Eric Callahan 5b4de64709 confighelper: add support for conditionals
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:38:34 -05:00
Pedro Lamas d51d65ef30 mqtt: retry connection if failed to resolve hostname
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-18 06:00:51 -05:00
Richard Mitchell 93299658fb wled: fix index for wled
Comparing to mqtt I think it should be H3 to appear in the index

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2021-11-18 05:17:36 -05:00
Eric Callahan df1892801f docs: refactor the "power" configuration docs
Add the "status_delay" option for Home Assistant and refactor to clarify what each option does for each device type.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 11:01:03 -05:00
Eric Callahan 1caaebe03f power: implement workaround for Homeassistant devices
Some devices on the Home Assistant server do not update their internal state immediately after a request returns.  Introduce a configurable delay to work around this issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 10:59:46 -05:00
Eric Callahan c3400bd237 power: add timer support to the RFDevice
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:11:08 -05:00
Eric Callahan 18c6ff5a99 power: refactor gpio device to use gpio component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:11:08 -05:00
Eric Callahan 83901b1896 gpio: helper component for managing system gpios
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:10:29 -05:00
Eric Callahan dfa11f0f3e utils: add method to load system level modules
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-15 06:41:38 -05:00
Eric Callahan adb88fd8cf authorization: validate user data on startup
This provides corrective action in the event that an
invalid user entry makes its way into the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 06:00:59 -05:00
Richard Mitchell 389e9c7e62 wled: support for remote neopixel control
Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2021-11-14 07:16:20 -05:00
FrYakaTKoP 79b1c071ad docs: change repository links from meteyou to mainsail-crew
Signed-off-by:  Christoph Frei <fryakatkop@gmail.com>
2021-11-14 06:47:17 -05:00
Pedro Lamas bed239c90a mqtt: implements last will and testament
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-13 11:00:26 -05:00
Eric Callahan ca27c2cf10 power: change gpiod line request based on version
For gpiod versions 1.3 or greater use the "default_val" keyword argument to set the default, otherwise use
"default_vals".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 9789b3d999 docs: update user changes
Note that core components should now be configured in their own config section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan a9e865eb54 docs: update documenation with API and configuration changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 6d458125a1 power: fix scheduled firmware restarts
Determine if a firmware restart should be postponed by checking Klippy's state.  This should correctly schedule the restart regardless of whether or not the device is bound to Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 7f11214609 power: abort a scheduled firmware restart if klipper reports ready
This handles a specific scenario where a power device is bound to the Klipper service and is configured to perform a firmware restart after power on.  In this case, we can detect if the firmware restart is required and abort it if necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 739af51904 power: add "on_when_upload_queued" option
When this option is set to "True", the device will power on after the file manager queues an upload for printing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 484c4aea59 eventloop: fix FlexCallback annotation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan ac23f00d1f update_manager: remove initialized lock
Now that init occurs before the server starts there is no need to block requests until post initialization.

Signed-off-buy:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 2d5914b358 moonraker: attempt to resolve "event loop closed" errors on restart
Occasionally a server restart will fail as the new loop instantiates as closed.  This seems to be an issue with asyncio, attempt to work around by retyring to create a new loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan c718e9d1c3 moonraker: don't use a set to load initial components
Previously a set was used to remove duplicate components, however this is unnecessary as the `load_component` method immediately returns dups.  Using a list should preserve the load order based on the configuration, making it more predictable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 76731b673b moonraker: refactor klipper initialization
The `send_event()` method now returns a future that can be awaited until all callbacks are complete.  All events emitted during Klipper init are now awaited, and a Lock is used to prevent re-entry.  This resolves potential timing issues with commands sent during the init sequence.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan c2bf9bf551 event_loop: add create_future method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 9854fd36cf power: use component_init for post initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan e6bedd1ffe paneldue: use component_init for post initialization
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 799e763050 mqtt: use component_init for post initalization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan fd59ace4f8 machine: use component_init for post initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 15d99be9f0 update_manager: use component_init method for post initialzation
Clean up retry functionality to use for loops rather than while loops.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan cbdbe83bbd moonraker: refactor component initialization
Components may call a "component_init" method for initialization that requires async calls.  This allows moonraker to track init progress and guarantee init order.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 7a8aeae673 file_manager: use the job queue to start gcode uploads
If a print cannot be started then it will be queued.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan b135f48867 moonraker: add job queue to core components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 0f1aea8df8 moonraker: refactor component loading
Remove the "load_component_multi" method as it is not
necessary.  Components are responsible for loading
"child" sections as required.  Core components can
now have their own config section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan ec12a187fc job_queue: initial implementation
Add support for holding multiple printer jobs in a queue.
When a job successfully completes Moonraker will load
the next job in the queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 358fe9733f history: implement reset totals endpoint
This allows clients to request that job totals are reset to 0.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 21ee446509 history: use the job_state module to manage job events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan d0c104aceb job_state: initial implementation
This module adds a helper to track Klippy's "print_stats" module.  It
stores the current stats and emits events for changes in job state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 53291f6887 power: use the default_vals keyword to init gpios
The "default_val" keyword argument is not available in libgpiod version 1.2.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-11 19:35:34 -05:00
Pedro Lamas a3ba4b4169 power: improves GPIO initial_state handling
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-11 19:09:06 -05:00
Pedro Lamas 7ff126a56e docs: updates to new Fluidd repo address
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-07 07:00:12 -05:00
Eric Callahan 4e567d72a9 readme: add links for Docker Images
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:35:54 -04:00
Eric Callahan 78af774413 readme: add links for Pi images
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:26:41 -04:00
Eric Callahan 800816055e readme: add a clients header
Also update the link to Fluidd.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:21:18 -04:00
Eric Callahan 61fab42281 moonraker: log unix socket permission errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-04 11:03:53 -04:00
FrY Sennberg 780279d261 docs: fix typo
Signed-off-by: Christoph Frei <fryakatkop@gmail.com>
2021-11-04 08:40:14 -04:00
Eric Callahan 105858b0c7 machine: fix perfomance regression
The `update_service_status()` method could result in the creation of multiple subprocesses for each update, resulting in a performance hit as subprocesses are inherently expensive.

Fetch the state for all detected services in a single subprocess.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-03 09:10:12 -04:00
Eric Callahan 6a39bbd0c3 mqtt: don't publish status updates when disconnected
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-03 08:49:40 -04:00
FrY Sennberg eec60a760b git_deploy: report git repository name
Signed-off-by: Christoph Frei <fryakatkop@gmail.com>
2021-11-01 19:10:35 -04:00
Eric Callahan 9f89b03aa3 docs: update /server/info documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 11:24:31 -04:00
Eric Callahan 86ac019572 moonraker: report software version in server.info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 11:24:31 -04:00
Eric Callahan 4f43cf3a9f shell_command: handle ProcessLookupError when cancelling
This suggests that the process has previously exited.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 08:25:28 -04:00
Eric Callahan e71e723f89 confighelper: attempt to clarify unparsed config warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:17:25 -04:00
Eric Callahan 8e33698e23 power: improve logging when the gpiod module fails to load
Log all import errors other than ModuleNotFound errors.  Add a server warning if a gpio type is configured and the gpiod module is not loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:12:20 -04:00
Eric Callahan 2addf845d3 machine: add PNY to the list of known SD manufacturers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:12:00 -04:00
Eric Callahan f9372f3638 scripts: remove Klipper check in install script
Moonraker no longer requires that Klipper be installed and started prior to launch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 06:11:06 -04:00
Eric Callahan 21305853ce scripts: add liblmdb-dev and libjpeg-dev to dependencies
These packages can be required on systems that need to build python wheels.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 06:03:56 -04:00
Eric Callahan 504d87831d docs: document "root_info" filed reported by get_directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 17:06:14 -04:00
Eric Callahan b55b21921a file_manager: report additional info in response to get_directory
Include the root's name and its permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 16:49:41 -04:00
Eric Callahan e9b06472c1 file_manager: minor refactoring in _list_directory method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 16:46:40 -04:00
Eric Callahan aa608b4c29 metadata: support extracting thumbnails from footer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 11:01:27 -04:00
Eric Callahan 4e262dfa14 file_manager: remove redundant code in delete_file method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 07:34:40 -04:00
Eric Callahan 538c68fc8b file_manager: normalize path requests
This resolves an issue where a path is containter two slashes as a separator reports as outside of the root.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 07:28:55 -04:00
Eric Callahan 28c8bf61da machine: add a more robust container check
Most containers do not have access to systemd, so using
systemd-detect-virt will fail.  We can check the cgroup
and sched files of the first process to reliably determine
if Moonraker is running within a container.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 19:38:15 -04:00
Eric Callahan 179e9428c5 docs: add 'virtualization' to the return value of system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 11:45:13 -04:00
Eric Callahan f35bceb309 machine: detect virtualized envronment
It isn't valid to run some commands from within containers.  Use systmd-detect-virt to detect a virtualized environment and report the type and id via the system_info endpoint.

If Moonraker is running from within a container do not allow access to the reboot and shutdown endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 11:45:13 -04:00
Eric Callahan 7890753d9f docs: update documentation to reflect api changes
The file list and directory list endpoints now report file
permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 12:02:06 -04:00
Eric Callahan de8c0fc871 file_manager: fix inotify symlink handling
When a symbolic link is created there is no completion event, so immediately fire the notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 11:24:57 -04:00
Eric Callahan e33962fdd4 file_manager: check write permissions for uploads
If the specified path is a symbolic link do not proceed with the upload, raise an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 08:55:44 -04:00
Eric Callahan 734f295822 file_manager: allow registration of full access directories
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 08:55:44 -04:00
Eric Callahan 4c42b8d072 file_manager: report file and directory permissions
Signed-off-by: Eric Callahan <arksine.code@gmail.com>

fix
2021-10-27 08:55:19 -04:00
Eric Callahan 1dd89bac4b docs: bump mkdocs requirement to 1.2.3
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:46:56 -04:00
Eric Callahan f086f75c07 docs: Add documentation for new service and power features
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:46:56 -04:00
Eric Callahan 47999e24c4 power: add support for bound services
A bound service is stopped when a device powers off and started when a device is powered on.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:39:52 -04:00
Eric Callahan 12e035b6eb machine: list all active units
This resolves an issue where an allowed service is not
tagged as available if it is not loaded when moonraker
starts.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-10-24 08:45:28 -04:00
Eric Callahan 9d7dac3425 moonraker: rework Klippy init sequence
Stop polling Klippy after it it has exited the "startup" state.
When this has been detected, emit a "klippy_startup"
event.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 08:45:28 -04:00
Eric Callahan a0b5275cc9 machine: add method to wait for service init
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
Eric Callahan 97522947ec proc_stats: update service state in the proc_stat timer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
Eric Callahan 8126a73663 machine: report active status of available services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
th33xitus 6a6422c16e metadata: add IdeaMaker thumbnail parsing
This commit allows Moonraker to parse thumbnails from g-code files generated by IdeaMaker.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-10-14 14:23:00 -04:00
Eric Callahan 8b510d9b03 docs: document the "timer" option for the power component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-14 08:03:13 -04:00
Eric Callahan 838b25d288 power: implement timer functionality for gpio devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-14 08:03:13 -04:00
crashmaxx 2836600857 power: add timer option to tplink-smartplug devices
Signed-off-by: Andrew Stowell crashmaxx@gmail.com
2021-10-12 06:35:32 -04:00
Eric Callahan 562f971c3d docs: update the mqtt documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 18:08:25 -04:00
Eric Callahan 25f9800f77 moonraker: don't send status updates for empty objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 17:58:43 -04:00
Eric Callahan 0ed367d734 mqtt: support specifying fields in "status_objects" option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 12:21:27 -04:00
Eric Callahan 070e03d741 file_manager: Don't filter inotify events on the gcodes root
Broadcast events for all files and let clients determine
what should be shown.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 11:33:33 -04:00
Eric Callahan 7f1c327f02 file_manager: hidden folder bugfix
Since inotify supports hidden folders we shouldn't skip them when scanning for nodes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 11:04:59 -04:00
Eric Callahan c631bff0c9 docs: Document MQTT support for printer objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 15:33:11 -04:00
Eric Callahan 0c311aeef4 mqtt: add support for publishing klipper status updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 14:17:13 -04:00
Eric Callahan b1f122beec scripts: update service to start after the network is brought online
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 08:07:03 -04:00
danijoo c3f1b290f8 power: add RF transmitter support
Signed-off: Daniel Bauer <github@dbauer.me>
2021-10-03 09:05:12 -04:00
Eric Callahan 86764657cf machine: add moonraker-telegram-bot to list of allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-29 18:08:08 -04:00
Eric Callahan 4df93481ec docs: add note about nginx to installation.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-29 17:22:58 -04:00
Eric Callahan 4e2bbde829 scripts: remove nginx dependency
Moonraker itself does not depend on nginx and it
is no longer required to install clients on the host.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-09-29 17:22:26 -04:00
Eric Callahan fdfab66951 metadata: add PrusaSlicer aliases
The varous forks of PrusaSlicer are processed identically
outside of their identifier, so there is no need to
implement new classes for each fork.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-28 06:14:24 -04:00
Eric Callahan 81b0c0a581 docs: minor API change reflecting new owner of Klipper repo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 00c6072274 workflows: update Klipper's repo location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 9c09ca2ed5 update_manager: add support for moved git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 2447ccab62 docs: update proc_stats documentation
The "websocket_connections" is now reported by proc_stats.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:22:19 -04:00
Eric Callahan d6fafef902 proc_stats: report websocket connection count
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:19:01 -04:00
Eric Callahan 46a8723566 scripts: add libcurl4-openssl-dev dependency
This dependency is also require to build the pycurl wheel.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:02:09 -04:00
Eric Callahan 233be2e889 scripts: add libssl-dev dependency
This is required for operating systems that need to build
the pycurl wheel

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 13:08:27 -04:00
Eric Callahan 83eddf5e7d docs: update /server/info documentation
Note the addition of the "websocket_count" field.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 11:35:58 -04:00
Eric Callahan b1d739e032 moonraker: report websocket connection via /server/info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 11:30:25 -04:00
Eric Callahan e76e83d8c1 moonraker: configure the tornado http client to use the curl backend
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 08:32:24 -04:00
Eric Callahan 73d3eae8ae scripts: add pycurl dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 08:23:32 -04:00
Eric Callahan e92da4c82c power: add gpiod support for Arch Linux
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-15 18:09:20 -04:00
Eric Callahan 776e0d6c90 file_manager: strip leading slashes supplied in the upload path argument
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-14 14:43:00 -04:00
dependabot[bot] 8ca953f55c build(deps): bump pillow from 8.2.0 to 8.3.2 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.2.0 to 8.3.2.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.2.0...8.3.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-13 05:34:32 -04:00
Pedro Lamas db3f69e0dd Improves Home Assistant failure handling
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-09-04 05:39:55 -04:00
Pedro Lamas 183f4a75e5 Adds Home Assistant power switch example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-09-04 05:39:55 -04:00
Eric Callahan 628c7e2e4d docs: fix typos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-04 05:38:03 -04:00
Stefan Dej 81176a6d31 confighelper: update 'Invalid config option' warning for better understanding
Signed-off-by: Stefan Dej <meteyou@gmail.com>
2021-08-29 14:15:12 -04:00
Eric Callahan 245053434f authorization: specifically identify basic auth
Raise an exception when a request with Basic Auth is received, however do not log the username/password.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-28 08:54:40 -04:00
Eric Callahan dfb8da6e3e authorization: improve error message for invalid auth headers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-27 06:11:55 -04:00
Eric Callahan b040640813 update_manager: broadcast update_refreshed notification in the status refresh handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-26 15:44:26 -04:00
Eric Callahan a1cf02231a scripts: add --allow-releaseinfo-change option to apt-get in install-moonraker.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-24 06:41:45 -04:00
Eric Callahan 8a7b348899 update_manager: fix apt-get issue with changed release info
Add --allow-releaseinfo-change to the call to apt-get.  This resolves an issue where the repos are chaning their "Suite" value from stable to oldstable with the release of Debian Bullseye.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-24 06:39:54 -04:00
Pedro Lamas f1523ef5f8 Fixes rounding issue in home assistant sensor
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-08-21 18:05:06 -04:00
Eric Callahan 5204fe3e08 metadata: fix est time parsing for Simplify3D
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-07 11:45:44 -04:00
Pedro Lamas 5522e150b7 docs: Refactors the Home Assistant example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-07-28 15:47:26 -04:00
Eric Callahan 86e0ef0d5e git_deploy: use "git pull --rebase" when repo debug is enabled
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-27 05:52:56 -04:00
Eric Callahan 42f61ceafa power: attempt to retry failed device init for 120 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 14:26:10 -04:00
Eric Callahan 2f95b0f426 docs: add network reporting to proc_stats documetation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 09:06:03 -04:00
Eric Callahan c684b063b2 proc_stats: report network stats for all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 08:49:38 -04:00
Eric Callahan 8f8d780c72 proc_stats: fix stat logging when the event loop is blocked
Convert the deque to a list before slicing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-15 11:03:07 -04:00
Eric Callahan 91f264bdaf update_manager: fix unbound variable error
Signed-off-by:  Eric Callahan <arksine.code
2021-07-15 08:14:18 -04:00
Eric Callahan 1fdfb5299e moonraker: create a new asyncio event loop on restart
This should guarantee that no dangliing callbacks are leftover on a soft restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-15 06:57:54 -04:00
Eric Callahan 0d1431395e update_manager: fix potential race condition with auto_refresh
Wait until update manager init is complete before attempting starting the auto refresh periodic callback.  This prevents an auto refresh from blocking init if Moonraker is started during the auto refresh window.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-15 06:52:04 -04:00
Eric Callahan 7f740ccb5a authorization: add warning if a domian in "cors_domains" contains a trailing slash
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 15:47:38 -04:00
Eric Callahan f94a27c8e4 docs: add documentation for "is_system_service" option 2021-07-12 15:37:31 -04:00
Eric Callahan cb8d5ecb35 app_deploy: add "is_system_service" configuration option
This allows users to add update manager "clients" that don't have systemd services registered.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan a921b4269e test: remove test client files
The test client has been moved to its own repository, Arksine/moontest.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan 87444f5bcb zip_deploy: allow updates to stable releases when on the "beta" channel
Users on the "beta" channel should be updated to the latest release, including stable releases.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan 2ceafb0ff5 git_deploy: replace references to ioloop with eventloop
Wrap some additional system calls that could potentially block in "run_in_thread".

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:34:15 -04:00
Eric Callahan 912840bbcd zip_deploy: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan d52554231a app_deploy: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan c4796ee321 update_manager: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 13a85fe9e0 file_manager: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan e4ecc1febe authorization: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 646e97ad55 machine: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 05e2389dc1 mqtt: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 8382b90682 paneldue: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan c61cfa325f power: replace references of ioloop with EventLoop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 78e10cf7f8 proc_stats: Use the EventLoop to run blocking calls in in a background thread
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 85d12da18d shell_command: replace tornado lock with asyncio lock
Also use asyncio's sleep method in place of tornado's wrapper around it.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 4430d564fe websockets: replace references to ioloop with event loop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 8a3ff7a54a app: replace refrences to ioloop with eventloop
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan d224536552 moonraker: replace calls to ioloop with eventloop wrapper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 07cb64a191 eventloop: initial implementation
This adds a thin wrapper around asyncio's eventloop.  Generally it is similar to Tornado's IOLoop, however without the need to support all awaitables.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 1ce8af18ec docs: add "web_beta" documentation for the update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 18:06:07 -04:00
Eric Callahan fddc67db93 update_manager: add support for web betas
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 18:06:07 -04:00
Eric Callahan df43aca222 proc_stats: fix erroneous timer handle assignment
The delayed callback to "log_last_stats()" in the Watchdog shold not have its return value assigned to the watchdog handle.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 08:01:27 -04:00
Eric Callahan fb9206aa8f proc_stats: read system files in another thread
This should prevent the event loop from getting blocked by a system call.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 05:53:11 -04:00
Eric Callahan e20c12619b git_deploy: compare upstream url to lowercase url during validation
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 12:09:17 -04:00
Eric Callahan 211c7e70e1 app_deploy: fix typo preventing repo clients from loading
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 11:58:11 -04:00
Eric Callahan d60b852b27 docs: add documentation for latest changes to the update manager
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-08 10:52:56 -04:00
Eric Callahan dacd9f7565 update_manager: report detected_type and configured_type for applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 09:02:08 -04:00
Eric Callahan d76abe019f update_manager: return True when on update success
All calls to update now return a boolean value.  When performing a full upate this return value is used to
check if Moonraker should wait for Klippy to reconnect.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

When debug logging is disabled do not  log HTTP requests.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fix whitespace errros in uninstall-moonraker.sh

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine d235139e6b paneldue: use the new "print_stats" module to check printing state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 4f97ebb28d test_client: Update to use new "print_stats" module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine f082d4dd44 paneldue: Update to fetch status from Klipper's print_stats object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 89fa9ba47e gcode_apis: update "print start" API to use SDCARD_PRINT_FILE gcode
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
144 changed files with 47527 additions and 5788 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
+3
View File
@@ -0,0 +1,3 @@
# These are supported funding model platforms
ko_fi: arksine
+10
View File
@@ -0,0 +1,10 @@
---
name: Announcement
about: Create a Moonraker Announcement. For dev use only.
title: ''
labels: announcement
assignees: ''
---
+66
View File
@@ -0,0 +1,66 @@
name: Bug report
description: Create a report to help us improve
labels: ["bug", "triage"]
body:
- type: markdown
attributes:
value: |
This issue form is for reporting bugs only!
If you have a feature request, please use [Feature Request](/new?template=feature_request.yml)
- type: textarea
id: what-happened
attributes:
label: What happened
description: >-
A clear and concise description of what the bug is.
validations:
required: true
- type: dropdown
id: client
attributes:
label: Client
multiple: true
description: On what clients are you seeing the problem?
options:
- Mainsail
- Fluidd
- MoonCord
- KlipperScreen
- MobileRaker
- Other
validations:
required: true
- type: dropdown
id: browser
attributes:
label: Browser
multiple: true
description: On what browsers are you seeing the problem?
options:
- Chrome
- Firefox
- Safari
- Microsoft Edge
- Brave
- Other or N/A
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: How to reproduce
description: >-
Minimal and precise steps to reproduce this bug.
validations:
required: true
- type: textarea
id: additional-info
attributes:
label: Additional information
description: |
Please attach moonraker.log using the field below. If you are using
a Browser or Client not provided in the options above please specify
them here.
You may also include any additional information, screenshots, or files
that helpful in describing the issue.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Klipper Discord
url: https://discord.klipper3d.org/
about: Quickest way to get in contact
@@ -0,0 +1,40 @@
name: Feature request
description: Suggest an idea for this project
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
This issue form is for feature requests only!
If you've found a bug, please use [bug_report](/new?template=bug_report.yml)
- type: textarea
id: problem-description
attributes:
label: Is your feature request related to a problem? Please describe
description: >-
A clear and concise description of what the problem is.
validations:
required: true
- type: textarea
id: solution-description
attributes:
label: Describe the solution you'd like
description: >-
A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: possible-alternatives
attributes:
label: Describe alternatives you've considered
description: >-
A clear and concise description of any alternative solutions or features you've considered.
- type: textarea
id: additional-info
attributes:
label: Additional information
description: |
If you have any additional information for us, use the field below.
Please note, you can attach screenshots or screen recordings here, by
dragging and dropping files in the field below.
@@ -0,0 +1,7 @@
<!---
Thank you for contributing to Moonraker. Before creating your pull request please
review the [contributing documentation](https://moonraker.readthedocs.io/en/latest/contributing/).
Be sure that each commit message is formatted as described, with a signature containing
your real name and a reachable email address. Your signature acknowledges that you accept the
[developer certificate of origin](https://github.com/Arksine/moonraker/blob/master/docs/developer-certificate-of-origin).
--->
+51
View File
@@ -0,0 +1,51 @@
# CI Code for generating and publishing beta assets
name: publish_assets
on:
release:
types: [published]
jobs:
generate_assets:
runs-on: ubuntu-latest
steps:
- name: Checkout Moonraker
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
path: moonraker
- name: Checkout Klipper
uses: actions/checkout@v2
with:
fetch-depth: 0
repository: Klipper3d/klipper
path: klipper
- name: Build Beta Assets
if: ${{ github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh -b
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Build Stable Assets
if: ${{ !github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Upload assets
run: |
cd moonraker
gh release upload ${{ env.TAG }} ${{ env.FILES }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
FILES: >
${{ github.workspace }}/moonraker.zip
${{ github.workspace }}/klipper.zip
${{ github.workspace }}/RELEASE_INFO
${{ github.workspace }}/COMMIT_LOG
TAG: ${{ github.event.release.tag_name }}
+20
View File
@@ -0,0 +1,20 @@
# CI for code style and application tests
name: test-code
on: [push, pull_request]
jobs:
lint-python-code:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: ricardochaves/python-lint@v1.4.0
with:
python-root-list: "moonraker scripts"
use-pylint: false
use-pycodestyle: true
use-flake8: false
use-black: false
use-mypy: true
use-isort: false
extra-pycodestyle-options: "--ignore=E226,E301,E302,E303,W503,W504 --max-line-length=88 --max-doc-length=88"
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
+13
View File
@@ -0,0 +1,13 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
.devel
.venv
venv
start_moonraker
*.env
.pdm.toml
build
dist
+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
+40 -5
View File
@@ -1,9 +1,44 @@
[![pdm-managed](https://img.shields.io/badge/pdm-managed-blueviolet)](https://pdm.fming.dev)
# 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 the 3D printing firmware
[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/).
### Clients
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/mainsail-crew/mainsail) by [Mainsail-Crew](https://github.com/mainsail-crew)
- [Fluidd](https://github.com/fluidd-core/fluidd) by Cadriel
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
### Raspberry Pi Images
Moonraker is available pre-installed with the following Raspberry Pi images:
- [MainsailOS](https://github.com/mainsail-crew/MainsailOS) by [Mainsail-Crew](https://github.com/mainsail-crew)
- Includes Klipper, Moonraker, and Mainsail
- [FluiddPi](https://github.com/fluidd-core/FluiddPi) by Cadriel
- Includes Klipper, Moonraker, and Fluidd
### Docker Containers
The following projects deploy Moonraker via Docker:
- [prind](https://github.com/mkuf/prind) by mkuf
- A suite of containers which allow you to run Klipper in
Docker. Includes support for OctoPrint and Moonraker.
### Changes
Please refer to the [changelog](https://moonraker.readthedocs.io/en/latest/changelog)
for a list of notable changes to Moonraker.
+402
View File
@@ -0,0 +1,402 @@
##
This document keeps a record of all changes to Moonraker's web APIs.
### February 20th 2023
- The following new endpoints are available when at least one `[sensor]`
section has been configured:
- `GET /server/sensors/list`
- `GET /server/sensors/sensor`
- `GET /server/sensors/measurements`
See [web_api.md](web_api.md) for details on these new endpoints.
- A `sensors:sensor_update` notification has been added. When at least one
monitored sensor is reporting a changed value Moonraker will broadcast this
notification.
See [web_api.md](web_api.md) for details on this new notification.
### February 17 2023
- Moonraker API Version 1.2.1
- An error in the return value for some file manager endpoints has
been corrected. Specifically, the returned result contains an `item` object
with a `path` field that was prefixed with the root (ie: "gcodes").
This is inconsistent with the websocket notification and has been corrected
to remove the prefix. This affects the following endpoints:
- `POST /server/files/directory` | `server.files.post_directory`
- `DELETE /server/files/directory` | `server.files.delete_directory`
- `POST /server/files/move` | `server.files.move`
- `POST /server/files/copy` | `server.files.copy`
### March 4th 2022
- Moonraker API Version 1.0.1
- The `server.websocket.id` endpoint has been deprecated. It is
recommended to use `server.connection.identify` method to identify
your client. This method returns a `connection_id` which is
the websocket's unique id. See
[the documentation](web_api.md#identify-connection) for details.
### May 8th 2021
- The `file_manager` has been refactored to support system file
file events through `inotify`. Only mutable `roots` are monitored,
(currently `gcodes` and `config`). Subfolders within these
these roots are also monitored, however hidden folders are not.
The following changes API changes have been made to acccommodate
this functionality:
- The `notify_filelist_changed` actions have changed. The new
actions are as follows:
- `create_file`: sent when a new file has been created. This
includes file uploads and copied files.
- `create_dir`: sent when a new directory has been created.
- `delete_file`: sent when a file has been deleted.
- `delete_dir`: sent when a directory has been deleted.
- `move_file`: sent when a file has moved.
- `move_dir`: sent when a directory has moved.
- `modify_file`: sent when an existing file has been modified
- `root_update`: sent when a root directory location has been set.
For example, if a user changes the gcode path in Klipper, this
action is sent with a `notify_filelist_changed` notification.
- File list notifications for gcode files are now only sent after
all metadata has been processed. Likewise, requests to copy,
move, or upload a file will only return after metadata has been
processed. Notifications are synced with requests so that the
request should always return before the notification is sent.
- Thumbnails are now stored in the `.thumbs` directory to prevent
changes to thumbnails from emitting filelist notications. This
change will be reflected in the metadata's `relative_path` field,
so clients that use this field should not need to take additional
action. Note that existing thumbnails will remain in the `thumbs`
directory and filelist notifications will be sent for changes to
these thumbnails.
- The `notify_metadata_update` notification has been removed Clients
- can reliably expect metadata to be available for new or moved gcode
files when a request returns.
- The return values for several endpoints have been updated. They
now contain information similar to that which is pushed by the
`notify_filelist_changed` notification.
- The deprecated `data` field in gcode metadata has been removed.
The `size` field now returns the size of the `.png` file.
### March 15th 2021
- The `data` field for gcode thumbnails is now deprecated and will
be removed in the near future. Thumbnails are now saved to png
files in a `thumbs` directory relative to a gcode file's location.
This path is available in the `relative_path` field for each
thumbnail entry in the metadata.
### January 31st 2021
- The `GET /server/temperature_store` endpoint now only returns fields
that each sensor reports. For example, if a particuarly temperature
sensor does not report "target" or "power", then the corresponding
fields will not be reported for that sensor in response to the
`temperature_store` request.
### January 22nd 2021
- The `POST /machine/update/client` endpoint now requires a `name`
argument. This change added multiple client support
- The response to `GET /machine/update/status` no longer returns a
`client` field. Instead it will add fields matching the `name` of
each configured client. Keep in mind that the client object could
have a different set of fields depending on the type of a client. The
easy way to check for this is to see if a `branch` field is present.
If so, this client is a `git repo`. Otherwise it is a `web` client.
### January 4th 2021
- A `notify_update_refreshed` notification has been added. Moonraker now
auto-refreshes the update status at roughly a 2 hour interval. When
an auto-refresh is complete this notification is broadcast. Included
is an object that matches the response from `/machine/update/status`.
- The behavior of some of the `update_manager` APIs has changed:
- The `refresh` argument for `/machine/update/status` is now more
of a suggestion than a rule. If an update or a print is in
progress then the request will ignore the refresh argument
and immediately return the current status. Generally speaking requesting
a refresh should not be necessary with addition of auto refresh.
- The update requests (ie `/machine/update/klipper`) will now return
an error if a print is in progress. If the requested update is in
progress then the request will return valid with a message stating
that the update is in progress. If another object is being updated
then the request will be queued and block until it its complete.
### January 1st 2021
- A `notify_klippy_shutdown` websocket notification has been added
### December 30th 2020
- Some additional fields are now reported in the response to
`GET /machine/update/status`.
### November 28th 2020
- The following new endpoints are available when the `[update_manager]`
section has been configured:
- `GET /machine/update/status`
- `POST /machine/update/moonraker`
- `POST /machine/update/klipper`
- `POST /machine/update/client`
- `POST /machine/update/system`
- The following endpoint has been added and is available as part of the
core API:
- `POST /machine/services/restart`
See [web_api.md](web_api.md) for details on these new endpoints.
### November 23rd 2020
- Moonraker now serves Klipper's "docs" directory. This can be access
at `GET /server/files/docs/<filename>`.
### November 19th 2020
- The path for the power APIs has changed from `gpio_power` to `device_power`:
- `GET /machine/device_power/devices`\
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
Returns an array of objects listing all detected devices.
Each object in the array is guaranteed to have the following
fields:
- `device`: The device name
- `status`: May be "init", "on", "off", or "error"
- `type`: May be "gpio" or "tplink_smartplug"
- `GET /machine/device_power/status?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
"params":{"dev_name":null}}`\
It is no longer possible to call this method with no arguments.
Status will only be returned for the requested device, to get
status of all devices use `/machine/device_power/devices`. As
before, this returns an object in the format of
`{device_name: status}`, where device_name is the name of the device
and `status` is the devices current status.
- `POST /machine/device_power/on?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
"params":{"dev_name":null}}`\
Toggles device on. Returns the current status of the device.
- `POST /machine/device_power/off?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
"params":{"dev_name":null}}`\
Toggles device off. Returns the current status of the device.
- The `notify_power_changed` notification now includes an object
containing device info, matching that which would be recieved
from a single item in `/machine/power/devices`.
### November 12th 2020
- Two new fields have been added to the gcode metadata:
- `gcode_start_byte`: Indicates the byte position in the
file where the first "Gxx" or "Mxx" command is detected.
- `gcode_end_byte`: Indicates the byte position in the
file where the last "Gxx" or "Mxx" command is detected.
These fields may be used to more accurately predict print
progress based on the file size.
### November 11th 2020
- The `server.websocket.id` API has been added. This returns a
unique ID that Moonraker uses to track each client connection.
As such, this API is only available over the websocket, there
is no complementary HTTP request.
- All HTTP API request may now include arguments in either the
query string or in the request's body.
- Subscriptions are now managed on a per connection basis. Each
connection will only recieve updates for objects in which they
are currently subscribed. If an "empty" request is sent, the
subscription will be cancelled.
- The `POST /printer/object/subscribe` now requires a
`connection_id` argument. This is used to identify which
connection's associated subscription should be updated.
Currenlty subscriptions are only supported over the a
websocket connection, one may use the id received from
`server.websocket.id`.
- The `notify_klippy_ready` websocket notification has been
added.
### November 2nd 2020
- The `GET /server/files/directory` endpoint now accepts a new
optional argument, `extended`. If `extended=true`, then
the data returned for gcode files will also include extracted
metadata if it exists.
### October 25th 2020
- The `modified` field reported for files and directories is no
longer represented as a string. It is now a floating point
value representing unix time (in seconds). This can be used
to display the "last modified date" based on the client's
timezone.
### October 21st 2020
- The `/server/gcode_store` endpoint no longer returns a string
in the result's `gcode_store` field. It now returns an
Array of objects, each object containing `message` and `time`
fields. The time refers to a timestamp in unix time (seconds),
and may be used to determine when the gcode store received the
accompanying `message`.
### September 30th 2020
- Two new endpoints have been added:
- `GET /server/info` (`server.info`)
- `GET /server/gcode_store` (`server.gcode_store`)
See web_api.md for details on their usage.
### September 7th 2020
- A new websocket API has been added, `server.files.delete_file`:
```
{jsonrpc: "2.0", method: "server.files.delete_file", params:
{path: "<root>/<file_name>"}, id: <request id>}
```
Where <root> is either "gcodes" or "config", and <file_name> is
the relative path to the file for deletion. For example:
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
### September 3rd 2020
- The Websocket APIs have changed for clarity. The APIs methods now
use namespaces similar to those found in common programming languages.
This change affects all websocket APIs, however websocket events have
not changed. Below is a chart mapping the Previous API to the New API:
| Previous Websocket Method | New Websocket Method |
|---------------------------|----------------------|
| get_printer_info | printer.info |
| post_printer_emergency_stop | printer.emergency_stop |
| post_printer_restart | printer.restart |
| post_printer_firmware_restart | printer.firmware_restart |
| get_printer_objects_list | printer.objects.list |
| get_printer_objects_query | printer.objects.query |
| post_printer_objects_subscribe | printer.objects.subscribe |
| get_printer_query_endstops_status | printer.query_endstops.status |
| post_printer_gcode_script | printer.gcode.script |
| get_printer_gcode_help | printer.gcode.help |
| post_printer_print_start | printer.print.start |
| post_printer_print_pause | printer.print.pause |
| post_printer_print_resume | printer.print.resume |
| post_printer_print_cancel | printer.print.cancel |
| post_machine_reboot | machine.reboot |
| post_machine_shutdown | machine.shutdown |
| get_server_temperature_store | server.temperature_store |
| get_file_list | server.files.list |
| get_file_metadata | server.files.metadata |
| get_directory | server.files.get_directory |
| post_directory | server.files.post_directory |
| delete_directory | server.files.delete_directory |
| post_file_move | server.files.move |
| post_file_copy | server.files.copy |
- The "power" plugin APIs have changed. This affects both HTTP and
Websocket APIs. They were originally added to the "/printer" path,
however this adds the possibility of a naming conflict. The new
APIs are as follows:
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
### September 1st 2020
- A new notification has been added: `notify_metdata_update`. This
notification is sent when Moonraker parses metdata from a new upload.
Note that the upload must be made via the API, files manually (using
SAMBA, SCP, etc) do not trigger a notification. The notification is
sent in the following format:
```
{jsonrpc: "2.0", method: "notify_metadata_update", params: [metadata]}
```
Where `metadata` is an object in the following format:
```json
{
filename: "file name",
size: <file size>,
modified: "last modified date",
slicer: "Slicer Name",
first_layer_height: <in mm>,
layer_height: <in mm>,
object_height: <in mm>,
estimated_time: <time in seconds>,
filament_total: <in mm>,
thumbnails: [
{
width: <in pixels>,
height: <in pixels>,
size: <length of string>,
data: <base64 string>
}, ...
]
}
```
### August 16th 2020
- The structure of data returned from `/printer/info` (`get_printer_info`)
has changed to the following format:
```json
{
state: "<klippy state>",
state_message: "<current state message>",
hostname: "<hostname>",
software_version: "<version>",
cpu_info: "<cpu_info>",
klipper_path: "<moonraker use only>",
python_path: "<moonraker use only>",
log_file: "<moonraker use only>",
config_file: "<moonraker use only>",
}
```
The "state" item can be one of the following:
- "startup" - Klippy is in the process of starting up
- "ready" - Klippy is ready
- "shutdown" - Klippy has shutdown
- "error" - Klippy has experienced an error during startup
The message from each state can be found in the `state_message`.
- A `webhooks` printer object has been added, available for subscription or
query. It includes the following items:
- `state` - Printer state identical to that returned from `/printer/info`
- `state_message` - identical to that returned from `/printer/info`
- `/printer/objects/status` (`get_printer_objects_status`) has been renamed to
`/printer/objects/query` (`get_printer_objects_query`). The format of the
websocket request has changed, it should now look like the following:
```json
{
jsonrpc: "2.0",
method: "get_printer_objects_query",
params: {
objects: {
gcode: null,
toolhead: ["position", "status"]
}
},
id: <request id>
}
```
As shown above, printer objects are now wrapped in an "objects" parameter.
When a client wishes to subscribe to all items of a printer object, they
should now be set to `null` rather than an empty array.
The return value has also changed:
```json
{
eventtime: <klippy time of update>,
status: {
gcode: {
busy: true,
gcode_position: [0, 0, 0 ,0],
...},
toolhead: {
position: [0, 0, 0, 0],
status: "Ready",
...},
...}
}
```
The `status` item now contains the requested status.
- `/printer/objects/subscription` (`post_printer_objects_subscription`) is now
`printer/objects/subscribe` (`post_printer_objects_subscribe`). This
request takes parameters in the same format as the `query`. It now returns
state for all currently subscribed objects (in the same format as a `query`).
This data can be used to initialize all local state after the request
completes.
- Subscriptions are now pushed as "diffs". Clients will only recieve updates
for subscribed items when that data changes. This requires that clients
initialize their local state with the data returned from the subscription
request.
- The structure of data returned from `/printer/objects/list` has changed. It
now returns an array of available printer objects:
```json
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
```
- The `notify_klippy_state_changed` notification has been removed. Clients
can subscribe to `webhooks` and use `webhooks.state` to be notified of
transitions to the "ready" and "shutdown" states
- A `notify_klippy_disconnected` event has been added to notify clients
when the connection between Klippy and Moonraker has been terminated.
This event is sent with no parameters:
```json
{jsonrpc: "2.0", method: "notify_klippy_disconnected"}
```
+85
View File
@@ -0,0 +1,85 @@
# Changelog
All notable changes to this project will be documented in this file.
Notable changes prior to 2023-02-01 may be found in [user_changes.md] and
[api_changes.md].
The format is based on [Keep a Changelog].
## [Unreleased]
### Added
- Added this changelog!
- Added pyproject.toml with support for builds through [pdm](https://pdm.fming.dev/latest/).
- **sensor**: New component for generic sensor configuration.
- [Configuration Docs](configuration.md#sensor)
- [API Docs](web_api.md#sensor-apis)
- [Websocket Notification Docs](web_api.md#sensor-events)
- **file_manager**: Added new [scan metadata](web_api.md#scan-gcode-metadata) endpoint.
- **file_manager**: Added new [thumbnails](web_api.md#get-gcode-thumbnails) endpoint.
- **file_manager**: Added [file_system_observer](configuration.md#file_manager)
configuration option.
- **file_manager**: Added [enable_observer_warnings](configuration.md#file_manager)
configuration option.
- **file_manager**: Added ability to upload to symbolic links.
- **metadata**: Added support for Simplify3D V5 metadata parsing
- **machine**: Added [shutdown_action](configuration.md#machine) configuration
option.
- **machine**: Added service detection to the `supervisord_cli` provider.
- **machine**: Added `octoeverywhere` to the list of default allowed service.
- **power**: Added support for "Hue" device groups.
- **websockets**: Added support for [direct bridge](web_api.md#bridge-websocket)
connections.
- **update_manager**: Added new [refresh](web_api.md#refresh-update-status) endpoint.
- **update_manager**: Added support for pinned pip upgrades.
- **websockets**: Added support for post connection authentication over the websocket.
- **scripts**: Added database backup and restore scripts.
### Changed
- Converted Moonraker source into a Python package.
- The source from `moonraker.py` has been moved to `server.py`. The remaining code in
`moonraker.py` serves as a legacy entry point for launching Moonraker.
- **file_manager**: Improved inotify synchronization with API requests.
- **file_manager**: Endpoint return values are now consistent with their
respective websocket notifications.
- **machine**: The [provider](configuration.md#machine) configuration option
now expects `supervisord_cli` instead of `supervisord`.
- **update_manager**: Relaxed requirement for git repo tag detection. Now only two
parts are required (ie: v1.5 and v1.5.0 are acceptable).
### Deprecated
- **file_manager**: The `enable_inotify_warnings` configuration option has been
deprecated in favor of `enable_observer_warnings`.
### Fixed
- **file_manager**: Fix edge condition where `create_file` notifications
may be sent before a `create_dir` notification.
- **power** - Fixed URL encoding issues for http devices.
- **template**: A ConfigError is now raised when a template fails to
render during configuration.
- **machine**: Fixed support for Supervisord Version 4 and above.
- **update_manager**: Added package resolution step to the APT backend.
- **update_manger**: Fixed PackageKit resolution step for 64-bit systems.
- **update_manager**: Fixed Python requirements file parsing. Comments are now ignored.
### Removed
- Pycurl dependency. Moonraker no longer uses Tornado's curl based http client.
## [0.7.1] - 2021-07-08
- Experimental pre-release
<!-- Links -->
[keep a changelog]: https://keepachangelog.com/en/1.0.0/
[semantic versioning]: https://semver.org/spec/v2.0.0.html
[user_changes.md]: user_changes.md
[api_changes.md]: api_changes.md
<!-- Versions -->
[unreleased]: https://github.com/Arksine/moonraker/compare/v0.7.1...HEAD
[0.7.1]: https://github.com/Arksine/moonraker/releases/tag/v0.7.1
+365
View File
@@ -0,0 +1,365 @@
## Components
Components in Moonraker are used to extend Moonraker's functionality,
similar to "extras" in Klipper. Moonraker divides components into
two categories, "core" components and "optional" components. A core
component gets its configuration from the `[server]` section and is
loaded when Moonraker starts. For example, the `file_manager` is a
core component. If a core component fails to load Moonraker will
exit with an error.
Optional components must be configured in `moonraker.conf`. If they
have no specific configuration, a bare section, such as `[octoprint_compat]`
must be present in `moonraker.conf`. Unlike with core components,
Moonraker will still start if an optional component fails to load.
Its failed status will be available for clients to query and present
to the user.
### Basic Example
Components exist in the `components` directory. The below example
shows how an `example.py` component might look:
```python
# Example Component
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
class Example:
def __init__(self, config):
self.server = config.get_server()
self.name = config.get_name()
# Raises an error if "example_int_option" is not configured in
# the [example] section
self.example_int_opt = config.getint("example_int_option")
# Returns a NoneType if "example_float_option is not configured
# in the config
self.example_float_opt = config.getfloat("example_float_option", None)
self.server.register_endpoint("/server/example", ['GET'],
self._handle_example_request)
async def request_some_klippy_state(self):
klippy_apis = self.server.lookup_component('klippy_apis')
return await klippy_apis.query_objects({'print_stats': None})
async def _handle_example_request(self, web_request):
web_request.get_int("required_reqest_param")
web_request.get_float("optional_request_param", None)
state = await self.request_some_klippy_state()
return {"example_return_value": state}
def load_component(config):
return Example(config)
```
If you have created a "Klippy extras" module then the above should look
look familiar. Moonraker attempts to use similar method for adding
extensions, making easier Klipper contributors to add new functionality
to Moonraker. Be aware that there is no "Reactor" object in Moonraker,
it uses `asyncio` for coroutines. Like Klippy, you should not write
code that blocks the main thread.
### The ConfigHelper Object
As shown above, each component is passed a config object. This object
will be a `ConfigHelper` type, which is an object that wraps a
configuration section to simply access to the native `ConfigParser`.
A `ConfigHelper` should never be directly instantiated.
#### *ConfigHelper.get_server()*
Returns the primary [server](#the-server-object) instance.
#### *ConfigHelper.get_name()*
Returns the configuration section name associated with this `ConfigHelper`.
#### *ConfigHelper.get(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a string. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getint(option_name, default=Sentinel)*
Returns the value of the option`option_name` as an integer. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getfloat(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a float. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.getboolean(option_name, default=Sentinel)*
Returns the value of the option`option_name` as a boolean. If
the option does not exist, returns `default`. If `default` is
not provided raises a `ConfigError`.
#### *ConfigHelper.has_section(section_name)*
Returns True if a section matching `section_name` is in the configuration,
otherwise False.
Note that a ConfigHelper object also implements `__contains__`,
which is an alias for `has_section`, ie: `section_name in config_instance`
#### *ConfigHelper.getsection(section_name)*
Returns a Config object for the section matching `section_name`. If the
section does not exist in the configuration raises a `ConfigError`.
Note that a ConfigHelper object also implements `__getitem__`,
which is an alias for `get_section`, ie: `config_instance[section_name]`
#### *ConfigHelper.get_options()*
Returns a dict mapping options to values for all options in the Config
object.
#### *ConfigHelper.get_prefix_sections(prefix)*
Returns a list section names in the configuration that start with `prefix`.
These strings can be used to retreve ConfigHelpers via
[get_section()](#confighelpergetsectionsection_name).
### The Server Object
The server instance represents the central management object in Moonraker.
It can be used to register endpoints, register notifications, look up other
components, send events, and more.
#### *Server.lookup_component(component_name, default=Sentinel)*
Attempts to look up a loaded component, returning the result. If
the component has not been loaded, `default` will be returned.
If `default` is not provided a `ServerError` will be raised.
#### *Server.load_component(config, component_name, default=Sentinel)*
Attempts to load an uninitialized component and returns the result. It is
only valid to call this within a a component's `__init__()` method, and
should only be necessary if one optional component relies on another. Core components will always be loaded before optional components, thus an optional
component may always call
[lookup_component()](#serverlookup_componentcomponent_name-defaultsentinel)
when it needs a reference to core component.
If the component fails to load `default` will be returned. If `default`
is not provided a `ServerError` will be raised.
#### *Server.register_endpoint(uri, request_methods, callback, transports=["http", "websocket", "mqtt"], wrap_result=True)*
Registers the supplied `uri` with the server.
The `request_methods` argument should be a list of strings containing any
combination of `GET`, `POST`, and `DELETE`.
The `callback` is executed when a request matching the `uri` and a
`request_method` is received. The callback function will be passed a
`WebRequest` object with details about the request. This function
should be able of handling each registered `request_method`. The
provided callback must be a coroutine.
The `transports` argument is a list containing any combination of
`http`, `websocket` and `mqtt`. JSON-RPC methods for `websocket` and `mqtt`
will be generated based on what is supplied by the `uri` and
request_methods` argument. A unique JSON_RPC method is generated for each
request method. For example:
```python
self.server.register_endpoint("/server/example", ["POST"], self._handle_request)
```
would register a JSON-RPC method like:
```
server.example
```
However, if multiple requests methods are supplied, the generated JSON-RPC
methods will differ:
```python
self.server.register_endpoint("/server/example", ["GET", "POST", "DELETE"],
self._handle_request)
```
would register:
```
server.get_example
server.post_example
server.delete_example
```
The `wrap_result` argument applies only to the `http` protocol. In Moonraker
all http requests return a result with a JSON body. By default, the value returned
by a `callback` is wrapped in a dict:
```python
{"result": return_value}
```
It is only necessary to set this to false if you need to return a body that
does not match this result. For example, the `[octoprint_compat]` component
uses this functionality to return results in a format that match what
OctoPrint itself would return.
#### *Server.register_event_handler(event, callback)*
Registers the provided `callback` method to be executed when the
provided `event` is sent. The callback may be a coroutine, however it
is not required.
#### *Server.send_event(event, \*args)*
Emits the event named `event`, calling all callbacks registered to the
event. All positional arguments in `*args` will be passed to each
callback. Event names should be in the form of
`"module_name:event_description"`.
#### *Server.register_notification(event_name, notify_name=None)*
Registers a websocket notification to be pushed when `event_name`
is emitted. By default JSON-RPC notifcation sent will be in the form of
`notify_{event_description}`. For example, when the server sends the
`server:klippy_connected` event, the JSON_RPC notification will be
`notify_klippy_connected`.
If a `notify_name` is provided it will override the `{event_description}`
extracted from the `event_name`. For example, if the `notify_name="kconnect`
were specfied when registering the `server:klippy_connected` event, the
websocket would emit a `notify_kconnect` notification.
#### *Server.get_host_info()*
Returns a tuple of the current host name of the PC and the port Moonraker
is serving on.
#### *Server.get_klippy_info()*
Returns a dict containing the values from the most recent `info` request to
Klippy. If Klippy has never connected this will be an empty dict.
### The WebRequest Object
All callbacks registered with the
[register_endpoint()](#serverregister_endpointuri-request_methods-callback-protocolhttp-websocket-wrap_resulttrue)
method are passed a WebRequest object when they are executed. This object
contains information about the request including its endpoint name and arguments
parsed from the request.
#### *WebRequest.get_endpoint()*
Returns the URI registered with this request, ie: `/server/example`.
#### *WebRequest.get_action()*
Returns the request action, which is synonomous with its HTTP request
method. Will be either `GET`, `POST`, or `DELETE`. This is useful
if your endpoint was registered with multiple request methods and
needs to handle each differently.
#### *WebRequest.get_connection()*
Returns the associated Websocket connection ID. This will be `None`
for HTTP requests when no associated websocket is connected to
the client.
#### *WebRequest.get_args()*
Returns a reference to the entire argument dictionary. Useful if
one request handler needs to preprocess the arguments before
passing the WebRequest on to another request handler.
#### *WebRequest.get(key, default=Sentinel)*
Returns the request argument at the provided `key`. If the key is not
present `default` will be returned. If `default` is not provided a
`ServerError` will be raised.
#### *WebRequest.get_str(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a string, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_int(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to an integer, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_float(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a float, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_boolean(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a boolean, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `ServerError` will be raised.
### MQTT
If configured by the user the MQTT component is available for lookup.
Developers may use this to subscribe and publish topics.
#### *MQTTClient.is_connected()*
Returns true if Moonraker is currently connected to the Broker, false
otherwise.
#### *MQTTClient.wait_connection(timeout=None)*
Blocks until a connection with the broker has been successfully established
or until the specified timeout has exceeded. Returns true if the connection
was successful established, or False on timeout. If no timeout is specified
then this method will block indefinitely until a connection has been
established.
#### *MQTTClient.publish_topic(topic, payload=None, qos=None, retain=False)*
Attempts to publish a topic to the Broker. The `payload` may be a bool, int,
float, string, or json encodable (Dict or List). If omitted then an empty
payload is sent. The `qos` may be an integer from 0 to 2. If not specifed
then the QOS level will use the configured default. If `retain` is set to
`True` then the retain flag for the payload will be set.
Returns a Future that will block until topic is confirmed as published.
For QOS level 0 an exception will be raised if the broker is not connected.
#### *MQTTClient.publish_topic_with_response(topic, response_topic, payload=None, qos=None, retain=False, timeout=None)*
Publishes the supplied `topic` with the arguments specified by `payload`,
`qos`, and `retain`, then subscribes to the `response_topic`. The payload
delivered by the response topic is returned. Note that this method is
a coroutine, it must always be awaited. The call will block until the
entire process has completed unless a `timeout` (in seconds) is specifed.
The `timeout` is applied to both the attempt to publish and the pending
response, so the maximum waiting time would be approximately 2*timeout.
!!! warning
This should only be used when it is guaranteed that the `response_topic`
does not have a retained value. Otherwise the returned response will
be the retained value.
#### *MQTTClient.subscribe_topic(topic, callback, qos=None)*
Subscibes to the supplied `topic` with the specified `qos`. If `qos` is not
supplied the configured default will be used. The `callback` should be a
callable that accepts a `payload` argument of a `bytes` type. The callable
may be a coroutine. The callback will be run each time the subscribed topic
is published by another client.
Returns a `SubscriptionHandle` that may be used to unsubscribe the topic.
#### *MQTTClinet.unsubscribe(hdl)*
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
exist for the topic then the topic is unsubscribed from the broker.
File diff suppressed because it is too large. Load diff
+118 -21
View File
@@ -6,26 +6,123 @@ the Moonraker application into the Klipper repo after Moonraker matures,
at which point this repo will be archived. As such, contibuting guidelines
are near those of Klipper:
- All source files should begin with a copyright notice in the following
format:
```
# Module name and brief description of module
#
# Copyright (C) 2020 YOUR NAME <YOUR EMAIL ADDRESS>
#
# This file may be distributed under the terms of the GNU GPLv3 license
```
- No line in the source code or documentation should exceed 80 characters.
Be sure there is no trailing whitespace.
- Each Commit message should be in the following format:
```
module name: brief description of commit
#### New Module Contributions
More detailed explanation if necessary.
All source files should begin with a copyright notice in the following format:
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
email address.
```python
# 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
```
#### Git Commit Format
Commits should be contain one functional change. Changes that are unrelated
or independent should be broken up into multiple commits. It is acceptable
for a commit to contain multiple files if a change to one module depends on a
change to another (ie: changing the name of a method).
Avoid merge commits. If it is necessary to update a Pull Request from the
master branch use git's interactive rebase and force push.
Each Commit message should be in the following format:
```text
module: brief description of commit
More detailed explanation of the change if required
Signed-off-by: Your Name <your email address>
```
Where:
- `module`: is the name of the Python module you are changing or parent
folder if not applicable
- `Your Name`: Your real first and last name
- `<your email address>`: A real, reachable email address
For example, the git log of a new `power.py` device implementation might look
like the following:
```git
power: add support for mqtt devices
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
```
```git
docs: add mqtt power device documentation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
```
By signing off on commits, you acknowledge that you agree to the
[developer certificate of origin](../developer-certificate-of-origin)
shown below. As mentioned above, 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.
```
#### Code Style
Python methods should be fully annotated. Variables should be annotated where
the type cannot be inferred. Moonraker uses the `mypy` static type checker for
code validation with the following options:
- `--ignore-missing-imports`
- `--follow-imports=silent`
No line in the source code should exceed 80 characters. Be sure there is no
trailing whitespace. To validate code before submission one may use
`pycodestyle` with the following options:
- `--ignore=E226,E301,E302,E303,W503,W504`
- `--max-line-length=80`
- `--max-doc-length=80`
Generally speaking, each line in submitted documentation should also be no
longer than 80 characters, however there are situations where this isn't
possible, such as long hyperlinks or example return values. Documentation
isn't linted, so it
Don't peek into the member variables of another class. Use getters or
properties to access object state.
+58 -2
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.
@@ -125,7 +181,7 @@
metadata from gcode files.
- Clean up API registration. All endpoints are now registered by Klippy
host modules outside of static files and `/api/version`, which is used for
compatibility with Octoprint's legacy file upload API.
compatibility with OctoPrint's file upload API.
- The server now runs in its own process. Communication between the Host and
the server is done over a duplex pipe. Currently this results in a second
log file being generated specifically for the server at
@@ -221,7 +277,7 @@
/printer/extras/endstops` to `GET /printer/endstops`
- Serveral API changes have been made to accomodate the addition of webhooks:
- `GET /printer/klippy_info` is now `GET /printer/info`. This endpoint no
longer returns host information, as that can be retreived direct via the
longer returns host information, as that can be retrieved direct via the
`location` object in javascript. Instead it returns CPU information.
- `GET /printer/objects` is no longer used to accomodate multiple request
types by modifying the "Accept" headers. Each request has been broken
+2
View File
@@ -0,0 +1,2 @@
mkdocs==1.3.0
pymdown-extensions==9.1
+106
View File
@@ -0,0 +1,106 @@
# Example Home Assistant configuration file for a Artillery Sidewinder X1
# Credit to GitHub users @Kruppes and @pedrolamas
# extended by @tispokes
camera:
- platform: generic
still_image_url: http://192.168.178.66/webcam/?action=snapshot
stream_source: http://192.168.178.66/webcam/?action=stream
framerate: 10
sensor:
- platform: rest
name: SWX1_sensor
resource: "http://192.168.178.66: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" if ("result" in value_json) else "offline" }}
# Adding an API key is only necessary while using the [authorization] component
# and if Home Assistant is not a trusted client
headers:
x-api-key: 123456789abcdefghijklmno
- platform: template
sensors:
swx1_state:
unique_id: sensor.swx1_state
friendly_name: "Status"
icon_template: mdi:printer-3d
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['state'] if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_current_print:
unique_id: sensor.swx1_current_print
friendly_name: >-
{{ "Printed" if states.sensor.swx1_sensor.attributes['display_status']['progress'] == 1 else "Printing..." }}
icon_template: mdi:video-3d
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['filename'].split(".")[0] if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_current_progress:
unique_id: sensor.swx1_current_progress
friendly_name: "Progress"
unit_of_measurement: '%'
icon_template: mdi:file-percent
value_template: >-
{{ (states.sensor.swx1_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_print_time:
unique_id: sensor.swx1_print_time
friendly_name: "T-elapsed"
icon_template: mdi:clock-start
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_time_remaining:
unique_id: sensor.swx1_time_remaining
friendly_name: "T-remaining"
icon_template: mdi:clock-end
value_template: >-
{{ (((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0) | timestamp_custom('%H:%M:%S', 0)) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_eta:
unique_id: sensor.swx1_eta
friendly_name: "T-ETA"
icon_template: mdi:clock-outline
value_template: >-
{{ (as_timestamp(now()) + 2 * 60 * 60 + ((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0)) | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_nozzletemp:
unique_id: sensor.swx1_nozzletemp
friendly_name: >-
Nozzle
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['extruder']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
icon_template: >-
{{ "mdi:printer-3d-nozzle-heat" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:printer-3d-nozzle-heat-outline" }}
value_template: >-
{{ states.sensor.swx1_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_bedtemp:
unique_id: sensor.swx1_bedtemp
friendly_name: >-
Bed
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['heater_bed']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
icon_template: >-
{{ "mdi:radiator" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:radiator-off" }}
value_template: >-
{{ states.sensor.swx1_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
# Make sure to change the `Printer` name below to the device name on your configuration
#
switch:
- platform: rest
name: SWX1_power
resource: "http://192.168.178.66:7125/machine/device_power/device?device=SWX1"
body_on: '{"action": "on"}'
body_off: '{"action": "off"}'
headers:
Content-Type: 'application/json'
is_on_template: >-
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
+111
View File
@@ -0,0 +1,111 @@
# Example Home Assistant configuration file for a Voron V0.
# Credit to GitHub users @Kruppes and @pedrolamas
#
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' if ('result' in value_json) else None }}
# Adding an API key is only necessary while using the [authorization] component
# and if Home Assistant is not a trusted client
headers:
x-api-key: 123456789abcdefghijklmno
- platform: template
sensors:
vzero_hotend_target:
friendly_name: 'V0.126 Hotend Target'
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['extruder']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_hotend_actual:
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bed_target:
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bed_actual:
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_state:
icon_template: mdi:printer-3d
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['state'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_current_print:
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['filename'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_current_progress:
unit_of_measurement: '%'
icon_template: mdi:file-percent
value_template: >-
{{ (states.sensor.voron_v0_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_print_time:
icon_template: mdi:clock-start
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_time_remaining:
icon_template: mdi:clock-end
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)) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_eta:
icon_template: mdi:clock-outline
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) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_nozzletemp:
icon_template: mdi:thermometer
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 if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bedtemp:
icon_template: mdi:thermometer
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 if is_state('sensor.voron_v0_sensor', 'OK') else None }}
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
# Make sure to change the `Printer` name below to the device name on your configuration
#
switch:
- platform: rest
name: Voron_V0_power
resource: "http://192.168.178.56:7125/machine/device_power/device?device=Printer"
body_on: '{"action": "on"}'
body_off: '{"action": "off"}'
headers:
Content-Type: 'application/json'
is_on_template: >-
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
# MJPEG camera can be exposed to HA
#
camera:
- platform: mjpeg
name: Voron_V0_camera
still_image_url: http://192.168.178.56/webcam/?action=snapshot
mjpeg_url: http://192.168.178.56/webcam/?action=stream
+21
View File
@@ -0,0 +1,21 @@
# Welcome to Moonraker Documentation
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with the 3D printing firmware
[Klipper](https://github.com/Klipper3d/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
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.
+576 -185
View File
@@ -6,241 +6,632 @@ 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: ~/printer_data/gcodes
```
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 configure `printer.cfg` and
`klippy.log` so they are located in Moonraker's `data_path`, for example:
```
# 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_data/config/printer.cfg -l /home/pi/printer_data/logs/klippy.log -a /tmp/klippy_uds"
```
Moonraker's install script will create the data folder, however you
may wish to create it now and move `printer.cfg` to the correct
location, ie:
```
mkdir ~/printer_data
mkdir ~/printer_data/logs
mkdir ~/printer_data/config
mv printer.cfg ~/printer_data/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
```
The install script will attempt to create a basic configuration if
`moonraker.conf` does not exist at the expected location, however if you
prefer to have Moonraker start with a robust configuration you may create
it now. By default the configuration file should be located at
`$HOME/printer_data/config/moonraker.conf`, however the location of the
data path may be configured using the script's command line options.
The [sample moonraker.conf](./moonraker.conf) may be used as a starting
point, full details can be found in the
[confguration documentation](./configuration.md).
Finally, run moonraker's install script:
For a default installation run the following commands:
```
cd ~/moonraker/scripts
./install-moonraker.sh
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- `-f`:
Force an overwrite of Moonraker's systemd script. By default the
the systemd script will not be modified if it exists.
- `-a <alias>`:
The installer uses this option to determine the name of the service
to install. If `-d` is not provided then this options will also be
used to determine the name of the data path folder. If omitted this
defaults to `moonraker`.
- `-d <path to data folder>`:
Specifies the path to Moonraker's data folder. This folder organizes
files and directories used by moonraker. See the `Data Folder Structure`
section for details. If omitted this defaults to `$HOME/printer_data`.
- `-c <path to configuration file>`
Specifies the path to Moonraker's configuation file. By default the
configuration is expected at `<data_folder>/config/moonraker.conf`. ie:
`/home/pi/printer_data/config/moonraker.conf`.
- `-l <path to log file>`
Specifies the path to Moonraker's log file. By default Moonraker logs
to `<data_folder>/logs/moonraker.log`. ie:
`/home/pi/printer_data/logs/moonraker.log`.
- `-z`:
Disables `systemctl` commands during install (ie: daemon-reload, restart).
This is useful for installations that occur outside of a standard environment
where systemd is not running.
- `-x`:
Skips installation of [polkit rules](#policykit-permissions). This may be
necessary to install Moonraker on systems that do not have policykit
installed.
Additionally, installation may be customized with the following environment
variables:
- `MOONRAKER_VENV`
- `MOONRAKER_REBUILD_ENV`
- `MOONRAKER_FORCE_DEFAULTS`
- `MOONRAKER_DISABLE_SYSTEMCTL`
- `MOONRAKER_SKIP_POLKIT`
- `MOONRAKER_CONFIG_PATH`
- `MOONAKER_LOG_PATH`
- `MOONRAKER_DATA_PATH`
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`Moonraker: server connection detected`
`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>'}`
Now you may install a client, such as
[Mainsail](https://github.com/mainsail-crew/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd).
!!! Note
Moonraker's install script no longer includes the nginx dependency.
If you want to install one of the above clients on the local machine,
you may want to first install nginx (`sudo apt install nginx` on
debian/ubuntu distros).
### Data Folder Structure
As mentioned previously, files and folders used by Moonraker are organized
in a primary data folder. The example below illustrates the folder
structure using the default data path of `$HOME/printer_data`.
# Configuration
The host, port, log file location, socket file location and api key file
are all specified via command arguments:
```
usage: moonraker.py [-h] [-a <address>] [-p <port>] [-s <socketfile>]
[-l <logfile>] [-k <apikeyfile>]
/home/pi/printer_data
├── backup
│   └── 20220822T202419Z
│   ├── config
│   │   └── moonraker.conf
│   └── service
│   └── moonraker.service
├── certs
│   ├── moonraker.cert (optional)
│   └── moonraker.key (optional)
├── config
│   ├── moonraker.conf
│   └── printer.cfg
├── database
│   ├── data.mdb
│   └── lock.mdb
├── gcodes
│   ├── test_gcode_one.gcode
│   └── test_gcode_two.gcode
├── logs
│   ├── klippy.log
│   └── moonraker.log
├── systemd
│ └── moonraker.env
├── moonraker.secrets (optional)
└── moonraker.asvc
```
If it is not desirible for the files and folders to exist in these specific
locations it is acceptable to use symbolic links. For example, it is common
for the gcode folder to be located at `$HOME/gcode_files`. Rather than
reconfigure Klipper's `virtual_sdcard` it may be desirable to create a
`gcodes` symbolic link in the data path pointing to this location.
!!! Note
It is still possible to directly configure the paths to the configuration
and log files if you do not wish to use the default file names of
`moonraker.conf` and `moonraker.log`
When Moonraker attempts to update legacy installations symbolic links
are used to avoid an unrecoverable error. Additionally a `backup`
folder is created which contains the prior configuration and/or
systemd service unit, ie:
```
/home/pi/printer_data
├── backup
│   └── 20220822T202419Z
│   ├── config
│   │   ├── include
│   │   │   ├── extras.conf
│   │   │   ├── power.conf
│   │   │   └── updates.conf
│   │   └── moonraker.conf
│   └── service
│   └── moonraker.service
├── certs
│   ├── moonraker.cert -> /home/pi/certs/certificate.pem
│   └── moonraker.key -> /home/pi/certs/key.pem
├── config -> /home/pi/klipper_config
├── database -> /home/pi/.moonraker_database
├── gcodes -> /home/pi/gcode_files
├── logs -> /home/pi/logs
├── systemd
│ └── moonraker.env
└── moonraker.secrets -> /home/pi/moonraker_secrets.ini
```
!!! Warning
The gcode and config paths should not contain symbolic links
that result in an "overlap" of on another. Moonraker uses
inotify to watch files in each of these folders and takes action
when a file change is detected. The action taken depends on the
"root" folder, thus it is important that they be distinct.
### The systemd service file
The default installation will create `/etc/systemd/system/moonraker.service`.
Below is a common example of service file, installed on a Raspberry Pi:
```ini
# systemd service file for moonraker
[Unit]
Description=API Server for Klipper SV1
Requires=network-online.target
After=network-online.target
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=pi
SupplementaryGroups=moonraker-admin
RemainAfterExit=yes
WorkingDirectory=/home/pi/moonraker
EnvironmentFile=/home/pi/printer_data/systemd/moonraker.env
ExecStart=/home/pi/moonraker-env/bin/python $MOONRAKER_ARGS
Restart=always
RestartSec=10
```
Following are some items to take note of:
- The `Description` contains a string that Moonraker uses to validate
the version of the service file, (notice `SV1` at the end, ie: Service
Version 1).
- The `moonraker-admin` supplementary group is used to grant policykit
permissions.
- The `EnvironmentFile` field contains Moonraker's arguments. More on this
below.
- The `ExecStart` field begins with the python executable, followed by
by the enviroment variable `MOONRAKER_ARGS`. This variable is set in
the environment file.
#### The Environment File
The environment file, `moonraker.env`. is created in the data path during
installation. A default installation's environment file will contain the path
to `moonraker.py` and the data path option, ie:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data"
```
A legacy installation converted to the updated flexible service unit
might contain the following:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log"
```
Post installation it is simple to customize the [arguments](#command-line-usage)
supplied to Moonraker by editing this file and restarting the service.
### 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]p [-d <data path>] [-c <configfile>] [-l <logfile>] [-n]
Moonraker - Klipper API Server
optional arguments:
options:
-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
-d <data path>, --datapath <data path>
Location of Moonraker Data File Path
-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
-v, --verbose Enable verbose logging
-g, --debug Enable Moonraker debug features
-o, --asyncio-debug Enable asyncio debug flag
```
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
- `data path`: `$HOME/printer_data`
- `config file`: `$HOME/printer_data/config/moonraker.conf`
- `log file`: `$HOME/printer_data/logs/moonraker.log`
- logging to a file is enabled
- Verbose logging is disabled
- Moonraker's debug features are disabled
- The asyncio debug flag is set to false
It is recommended to use the defaults, however one may change these
arguments by editing `/etc/default/moonraker`.
!!! Tip
While the `data path` option may be omitted it is recommended that it
always be included for new installations. This allows Moonraker
to differentiate between new and legacy installations.
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 is necessary to run Moonraker without logging to a 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 -d ~/printer_data -n
```
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.
In general it is not recommended to install Moonraker with file logging
disabled. While moonraker will still log to stdout, all requests for support
must be accompanied by moonraker.log.
These options may be changed by editing `moonraker.env`.
### PolicyKit Permissions
Some of Moonraker's components require elevated privileges to perform actions.
Previously these actions could only be run via commandline programs launched
with the `sudo` prefix. This has significant downsides:
- The user must be granted `NOPASSWD` sudo access. Raspberry Pi OS
grants the Pi user this access by default, however most other distros
require that this be enabled through editing `visudo` or adding files
in `/etc/sudoers.d/`.
- Some linux distributions require additional steps such as those taken
in `sudo_fix.sh`.
- Running CLI programs is relatively expensive. This isn't an issue for
programs that are run once at startup, but is undesirable if Moonraker
wants to poll information about the system.
Moonraker now supports communicating with system services via D-Bus.
Operations that require elevated privileges are authrorized through
PolicyKit. On startup Moonraker will check for the necessary privileges
and warn users if they are not available. Warnings are presented in
`moonraker.log` and directly to the user through some clients.
To resolve these warnings users have two options:
1) Install the PolicyKit permissions with the `set-policykit-rules.sh` script,
for example:
```shell
cd ~/moonraker/scripts
./set-policykit-rules.sh
sudo service moonraker restart
```
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.
!!! tip
If you still get warnings after installing the PolKit rules, run the
install script with no options to make sure that all new dependencies
are installed.
## Plugin Configuration
The core plugins are configured via the primary configuration above. Optional
plugins each need their own configuration as outlined below.
```shell
cd ~/moonraker/scripts
./install-moonraker.sh
```
### PanelDue Plugin
2) Configure Moonraker to use the legacy backend implementations for
the `machine` and/or `update_manager` components, ie:
```
[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
```ini
# Use the systemd CLI provider rather than the DBus Provider
[machine]
provider: systemd_cli
# Edit your existing [update_manager] section to disable
# PackageKit. This will fallback to the APT CLI Package Update
# implementation.
[update_manager]
#..other update manager options
enable_packagekit: False
# Alternatively system updates can be disabled
[update_manager]
#..other update manager options
enable_system_updates: False
```
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
Previously installed PolicyKit rules can be removed by running
`set-policykit-rules.sh -c`
### Completing Privileged Upgrades
At times an update to Moonraker may require a change to the systemd service
file, which requires sudo permission to complete. Moonraker will present
an announcement when it need's the user's password and the process can
be completed by entering the password through Moonraker's landing page.
Some users prefer not to provide these credentials via the web browser and
instead would like to do so over ssh. These users may run
`scripts/finish-upgrade.sh` to provide Moonraker the necessary credentials
via ssh:
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) }
Utility to complete privileged upgrades for Moonraker
usage: finish-upgrade.sh [-h] [-a <address>] [-p <port>] [-k <api_key>]
optional arguments:
-h show this message
-a <address> address for Moonraker instance
-p <port> port for Moonraker instance
-k <api_key> API Key for authorization
```
### Power Control Plugin
By default the script will connect to a Moonraker instances on the local
machine at port 7125. If the instance is not bound to localhost or is
bound to another port the user may specify a custom address and port.
The API Key (`-k`) option is only necessary if the localhost is not authorized
to access Moonraker's API.
### Retrieving the API Key
Some clients may require an API Key to connect to Moonraker. After the
`[authorization]` component is first configured Moonraker will automatically
generate an API Key. There are two ways in which the key may be retrieved
by the user:
Retrieve the API Key via the command line (SSH):
```
[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.
cd ~/moonraker/scripts
./fetch-apikey.sh
```
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.
Retrieve the API Key via the browser from a trusted client:
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.
- Navigate to `http://{moonraker-host}/access/api_key`, where
`{moonraker-host}` is the host name or ip address of the desired
moonraker instance.
- The result will appear in the browser window in JSON format. Copy
The API Key without the quotes.
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
### LMDB Database Backup and Restore
Moonraker uses a [LMDB Database](http://www.lmdb.tech/doc/) for persistent
storage of procedurally generated data. LMDB database files are platform
dependent, and thus cannot be easily transferred between different machines.
A file generated on a Raspberry Pi cannot be directly transferred to an x86
machine. Likewise, a file generated on a 32-bit version of Linux cannot
be transferred to a 64-bit machine.
Moonraker includes two scripts, `backup-database.sh` and `restore-database.sh`
to help facilitate database backups and transfers.
```shell
~/moonraker/scripts/backup-database.sh -h
Moonraker Database Backup Utility
usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]
optional arguments:
-h show this message
-e <env path> Moonraker Python Environment
-d <database path> Moonraker LMDB database to backup
-o <output file> backup file to save to
```
```shell
~/moonraker/scripts/restore-database.sh -h
Moonraker Database Restore Utility
usage: restore-database.sh [-h] [-e <python env path>] [-d <database path>] [-i <input file>]
optional arguments:
-h show this message
-e <env path> Moonraker Python Environment
-d <database path> Moonraker LMDB database path to restore to
-i <input file> backup file to restore from
```
Both scripts include default values for the Moonraker Environment and Database
Path. These are `$HOME/moonraker-env` and `$HOME/printer_data/database`
respectively. The `backup` script defaults the output value to
`$HOME/database.backup`. The `restore` script requires that the user specify
the input file using the `-i` option.
To backup a database for a default Moonraker installation the user may ssh into
the machine and run the following command:
```shell
~/moonraker/scripts/backup-database.sh -o ~/moonraker-database.backup
```
And to restore the database:
```shell
sudo service moonraker stop
~/moonraker/scripts/restore-database.sh -i ~/moonraker-database.backup
sudo service moonraker start
```
The backup file contains [cdb like](https://manpages.org/cdb/5) entries
for each key/value pair in the database. All keys and values are base64
encoded, however the data is not encrypted. Moonraker's database may
contain credentials and other sensitive information, so users should treat
this file accordingly. It is not recommended to keep backups in any folder
served by Moonraker.
### Recovering a broken repo
Currently Moonraker is deployed using `git`. Without going into the gritty
details,`git` is effectively a file system, and as such is subject to
file system corruption in the event of a loss of power, bad sdcard, etc.
If this occurs, updates using the `[update_manager]` may fail. In most
cases Moonraker provides an automated method to recover, however in some
edge cases this is not possible and the user will need to do so manually.
This requires that you `ssh` into your machine. The example below assumes
the following:
- You are using a Raspberry Pi
- Moonraker and Klipper are installed at the default locations in the `home`
directory
- Both Moonraker and Klipper have been corrupted and need to be restored
The following commands may be used to restore Moonraker:
```shell
cd ~
rm -rf moonraker
git clone https://github.com/Arksine/moonraker.git
cd moonraker/scripts
./install-moonraker.sh
./set-policykit-rules.sh
sudo systemctl restart moonraker
```
And for Klipper:
```shell
cd ~
rm -rf klipper
git clone https://github.com/Klipper3d/klipper.git
sudo systemctl restart klipper
```
### Debug options for developers
Moonraker accepts several command line arguments that can be used to
assist both front end developers and developers interested in extending
Moonraker.
- The `-v` (`--verbose`) argument enables verbose logging. This includes
logging that reports information on all requests received and responses.
- The `-g` (`--debug`) argument enables Moonraker's debug features,
including:
- Debug endpoints
- The `update_manager` will bypass strict git repo validation, allowing
updates from unofficial remotes and repos in a `detached HEAD` state.
- The `-o` (`--asyncio-debug`) argument enables the asyncio debug flag. This
will substantially increase logging and is intended for low level debugging
of the asyncio event loop.
!!! Warning
The debug option should not be enabled in production environments. The
database debug endpoints grant read/write access to all namespaces,
including those typically exclusive to Moonraker. Items such as user
credentials are exposed.
Installations using systemd can enable debug options by editing `moonraker.env`
via ssh:
```
nano ~/printer_data/systemd/moonraker.env
```
Once the file is open, append the debug option(s) (`-v` and `-g` in this example) to the
value of `MOONRAKER_ARGS`:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log -v -g"
```
Save the file, exit the text editor, and restart the Moonraker service:
```
sudo systemctl restart moonraker
```
+29
View File
@@ -0,0 +1,29 @@
# Sample Moonraker Configuration File
#
# !!! Moonraker does not load this file. See configuration.md !!!
# !!! for details on path to Moonraker's configuration. !!!
#
[server]
# Bind server defaults of 0.0.0.0, port 7125
enable_debug_logging: False
[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]
# Default webcam config values:
# flip_h = false
# flip_v = false
# rotate_90 = false
# stream_url = /webcam/?action=stream
# webcam_enabled = true
-3
View File
@@ -1,3 +0,0 @@
## Plugins
Documentation Forthcoming
+385
View File
@@ -0,0 +1,385 @@
#
As mentioned in the API documentation, it is possible to
[query](web_api.md#query-printer-object-status) or
[subscribe](web_api.md#subscribe-to-printer-object-status)
to "Klipper Printer Objects." There are numerous printer objects in
Klipper, many of which are optional and only report status if they are
enabled by Klipper's configuration. Client's may retrieve 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 retrieving state for an object not listed here,
look in Klipper's source code for module you wish to query. If the module
contains a "get_status()" method, its return value will contain a dictionary
that reports state which can be queried.
## webhooks
```json
{
"state": "startup",
"state_message": "message"
}
```
The `webhooks` object contains the current printer state and the current
state message. These fields match those returned via the `/printer/info`
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
so they are asynchonously notified of a change to printer state. The `state`
may be `startup`, `ready`, `shutdown`, or `error`. The `state_message`
contains a message specific to the current printers state.
## gcode_move
```json
{
"speed_factor": 1.0,
"speed": 100.0,
"extrude_factor": 1.0,
"absolute_coordinates": true,
"absolute_extrude": false,
"homing_origin": [0.0, 0.0, 0.0, 0.0],
"position": [0.0, 0.0, 0.0, 0.0],
"gcode_position": [0.0, 0.0, 0.0, 0.0]
}
```
The `gcode_move` object reports the current gcode state:
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
- `speed`: The current gcode speed in mm/s.
- `extrude_factor`: AKA "extrusion multiplier".
- `absolute_coorinates`: true if the machine axes are moved using
absolute coordinates, false if using relative coordinates.
- `absolute_extrude`: true if the extruder is moved using absolute
coordinates, false if using relative coordinates.
- `homing_origin`: [X, Y, Z, E] - returns the "gcode offset" applied to
each axis. For example, the "Z" axis can be checked to determine how
much offset has been applied via "babystepping".
- `position`: [X, Y, Z, E] - The internal gcode position, including
any offsets (gcode_offset, G92, etc) added to an axis.
- `gcode_position`: [X, Y, Z, E] - The current gcode position
sans any offsets applied. For X, Y, and Z, this should match
the most recent "G1" or "G0" processed assuming the machine is
using absolute coordinates.
!!! Note
The printer's actual movement will lag behind the reported positional
coordinates due to lookahead.
## toolhead
```json
{
"homed_axes": "xyz",
"print_time": 0.0,
"estimated_print_time": 0.0,
"extruder": "extruder",
"position": [0.0, 0.0, 0.0, 0.0],
"max_velocity": 500.0,
"max_accel": 3000.0,
"max_accel_to_decel": 1500.0,
"square_corner_velocity": 5.0
}
```
The `toolhead` object reports state of the current tool:
- `homed_axes`: a string containing the axes that are homed. If no axes
are homed, returns a null string.
- `print_time`: internal value, not generally useful for clients
- `estimated_print_time`: internal value, not generally useful for clients.
- `extruder`: the name of the currently selected extruder, ie "extruder"
or "extruder1".
- `position`: [X, Y, Z, E] - This the the last position toward which the tool
was commanded to move. It includes any offsets applied via gcode as well
as any transforms made by modules such as "bed_mesh", "bed_tilt", or
"skew_correction".
- `max_velocity`: The currently set maximum velocity of the tool (mm/s^2).
- `max_accel`: The currently set maximum acceleration of the tool (mm/s^2).
- `max_accel_to_decel`: The currently set maximum accel to decel of the tool.
This value is the maximum rate at which the tool can transition from
acceleration to deceleration (mm/s^2).
- `square_corner_velocity`: The currently set square corner velocity. This
is the maximum velocity at which the tool may travel a 90 degree corner.
!!! tip
`max_velocity`, `max_accel`, `max_accel_to_decel`, and
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
`M204` can also change `max_accel`.
## configfile
```json
{
"config": {},
"settings": {},
"save_config_pending": false
}
```
The `configfile` object reports printer configuration state:
- `config`: This is an object containing the configuration as read from
printer.cfg. Each config section will be an object containing the
configured options. Values will ALWAYS be reported as
strings. Note that default values are not reported, only options
configured in printer.cfg are present.
- `settings`: Similar to `config`, however this object includes default
values that may not have been included in `printer.cfg`. It is possible
for a value to be a string, integer, boolean, or float.
- `save_config_pending`: True if the printer has taken an action which
has updated the internal configuration (ie: PID calibration, probe
calibration, bed mesh calibration). This allows clients to present
the user with the option to execute a SAVE_CONFIG gcode which will
save the configuration to printer.cfg and restart the Klippy Host.
## extruder
*Enabled when `[extruder]` is included in printer.cfg*
!!! note
If multiple extruders are configured, extruder 0 is available as
`extruder`, extruder 1 as `extruder1` and so on.
```json
{
"temperature": 0.0,
"target": 0.0,
"power": 0.0,
"pressure_advance": 0.0,
"smooth_time": 0.0
}
```
The `extruder` object reports state of an extruder:
- `temperature`: The extruder's current temperature (in C).
- `target`: The extruder's target temperature (in C).
- `power`: The current pwm value applied to the heater. This value is
expressed as a percentage from 0.0 to 1.0.
- `pressure_advance`: The extruder's current pressure advance value.
- `smooth_time`: The currently set time range to use when calculating the
average extruder velocity for pressure advance.
## heater_bed
*Enabled when `[heater_bed]` is included in printer.cfg*
```json
{
"temperature": 0.0,
"target": 0.0,
"power": 0.0,
}
```
The `heater_bed` object reports state of the heated bed:
- `temperature`: The bed's current temperature
- `target`: The bed's target temperature
- `power`: The current pwm value applied to the heater. This value is
expressed as a percentage from 0.0 to 1.0.
## fan
*Enabled when `[fan]` is included in printer.cfg*
```json
{
"speed": 0.0,
"rpm": 4000
}
```
The `fan` object returns state of the part cooling fan:
- `speed`: The current fan speed. This is reported as a
percentage of maximum speed in the range of 0.0 - 1.0.
- `rpm`: The fan's revolutions per minute if the tachometer
pin has been configured. Will report `null` if no tach
has been configured.
## idle_timeout
```json
{
"state": "Idle",
"printing_time": 0.0
}
```
The `idle_timeout` object reports the idle state of the printer:
- `state`: Can be `Idle`, `Ready`, or `Printing`. The printer will
transition to the `Printing` state whenever a gcode is issued that
commands the tool, this includes manual commands. Thus this should
not be used to determine if a gcode file print is in progress. It can
however be used to determine if the printer is busy.
- `printing_time`: The amount of time the printer has been in the
`Printing` state. This is reset to 0 whenever the printer transitions
from `Printing` to `Ready`.
## virtual_sdcard
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
```json
{
"progress": 0.0,
"is_active": false,
"file_position": 0
}
```
The `virtual_sdcard` object reports the state of the virtual sdcard:
- `progress`: The print progress reported as a percentage of the file
read, in the range of 0.0 - 1.0.
- `is_active`: Returns true if the virtual sdcard is currently processing
a file. Note that this will return false if a virtual sdcard print is
paused.
- `file_position`: The current file position in bytes. This will always
be an integer value
!!! Note
`progress` and `file_position` will persist after a print has
paused, completed, or errored. They are cleared when the user issues
a SDCARD_RESET_FILE gcode or when a new print has started.
## print_stats
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
```json
{
"filename": "",
"total_duration": 0.0,
"print_duration": 0.0,
"filament_used": 0.0,
"state": "standby",
"message": ""
}
```
The `print_stats` object reports `virtual_sdcard` print state:
- `filename`: The name of the current file loaded. This will be a null
string if no file is loaded. Note that name is a path relative to the
gcode folder, thus if the file is located in a subdirectory it would
be reported as "my_sub_dir/myprint.gcode".
- `total_duration`: The total time (in seconds) elapsed since a print
has started. This includes time spent paused.
- `print_duration`: The total time spent printing (in seconds). This is
equivalent to `total_duration` - time paused.
- `filament_used`: The amount of filament used during the current print
(in mm). Any extrusion during a pause is excluded.
- `state`: Current print state. Can be one of the following values:
- `"standby"`
- `"printing"`
- `"paused"`
- `"complete"`
- `"cancelled"`
- `"error"` - Note that if an error is detected the print will abort
- `message`: If an error is detected, this field contains the error
message generated. Otherwise it will be a null string.
!!! Note
After a print has started all of the values above will persist until
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
## display_status
*Enabled when `[display]` or `[display_status]` is included in printer.cfg*
```json
{
"message": "",
"progress": 0.0
}
```
The `display_status` object contains state typically used to update displays:
- `message`: The message set by a M117 gcode. If no message is set this will
be a null string.
- `progress`: The percentage of print progress, as reported by M73. This
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
will fallback to the eqivalent of `virtual_sdcard.progress`. Note that
progress updated via M73 has a timeout. If no M73 is received after 5
seconds, `progress` will be set to the fallback value.
## temperature_sensor sensor_name
*Enabled when `[temperature_sensor sensor_name]` is included in printer.cfg.
It is possible for multiple temperature sensors to be configured.*
```json
{
"temperature": 0.0,
"measured_min_temp": 0.0,
"measured_max_temp": 0.0
}
```
A `temperature_sensor` reports the following state:
- `temperature`: Sensor's current reported temperature
- `measured_min_temp`: The mimimum temperature read from the sensor
- `measured_max_temp`: The maximum temperature read from the sensor
## temperature_fan fan_name
*Enabled when `[temperature_fan fan_name]` is included in printer.cfg. It is
possible for multiple temperature fans to be configured.*
```json
{
"speed": 0.0,
"temperature": 0.0,
"target": 0.0
}
```
A `temperature_fan` reports the following state:
- `speed`: Current fan speed as a percentage of maximum speed, reported
in the range of 0.0 - 1.0
- `temperature`: Currently reported temperature of the sensor associated
with the fan
- `target`: The current target temperature for the `temperature_fan`.
## filament_switch_sensor sensor_name
*Enabled when `[filament_switch_sensor sensor_name]` is included in
printer.cfg. It is possible for multiple filament sensors to be configured.*
```json
{
"filament_detected": false,
"enabled": true
}
```
A `filament_switch_sensor` reports the following state:
- `filament_detected`: Set to true if the switch detects filament, otherwise
false
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
## output_pin pin_name
*Enabled when `[output_pin pin_name]` is included in printer.cfg.
It is possible for multiple output pins to be configured.*
```json
{
"value": 0.0
}
```
An `output_pin` reports the following state:
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
across the entire range.
## bed_mesh
*Enabled when `[bed_mesh]` is included in printer.cfg.*
```json
{
"profile_name": "",
"mesh_min": [0.0, 0.0],
"mesh_max": [0.0, 0.0],
"probed_matrix": [[]],
"mesh_matrix": [[]]
}
```
The `bed_mesh` printer object reports the following state:
- `profile_name`: The name of the currently loaded profile. If no profile is
loaded then this will report a null string. If the user is not using
bed_mesh profile management then this will report `default` after mesh
calibration completes.
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
values. If the matrix has not been probed the the result is `[[]]`.
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
no matrix has been generated the result is `[[]]`.
!!! tip
See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
of how to use this information to generate (X,Y,Z) coordinates.
## gcode_macro macro_name
*Enabled when `[gcode_macro macro_name]` is included in printer.cfg.
It is possible for multiple gcode macros to be configured.*
Gcode macros will report the state of configured `variables`.
While user defined macros likely won't report state that is useful
for a client, it is possible for client developers to recommend or
request a specific gcode_macro configuration, then have the client
take action based on the variables reported by the macro.
+177
View File
@@ -0,0 +1,177 @@
##
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### Februrary 8th 2023
- The `provider` option in the `[machine]` section no longer accepts
`supervisord` as an option. It has been renamed to `supervisord_cli`.
### January 2nd 2023
- The `bound_service` option for `[power]` devices has been deprecated in
favor of `bound_services`. Currently this change does not generate a
warning as it can be reliably resolved internally.
### October 14th 2022
- The systemd service file is now versioned. Moonraker can now detect when
the file is out of date and automate corrections as necessary.
- Moonraker's command line options are now specified in an environment file,
making it possible to change these options without modifying the service file
and reloading the systemd daemon. The default location of the environment
file is `~/printer_data/systemd/moonraker.env`.
- Moonraker now manages files and folders in a primary data folder supplied
by the `-d` (`--data-path`) command line option. As a result, the following
options have been deprecated:
- `ssl_certificate_path` in `[server]`
- `ssl_key_path` in `[server]`
- `database_path` in `[database]`
- `config_path` in `[file_manager]`
- `log_path` in `[file_manager]`
- `secrets_path` in `[secrets]`
- Debugging options are now supplied to Moonraker via the command line.
The `-v` (`--verbose`) option enables verbose logging, while the `-g`
(`--debug`) option enables debug features, including access to debug
endpoints and the repo debug feature in `update_manager`. As a result,
the following options are deprecated:
- `enable_debug_logging` in `[server]`
- `enable_repo_debug` in `[update_manager]`
### July 27th 2022
- The behavior of `[include]` directives has changed. Included files
are now parsed as they are encountered. If sections are duplicated
options in the last section parsed take precendence. If you are
using include directives to override configuration in `moonraker.conf`
the directives should be moved to the bottom of the file.
- Configuration files now support inline comments.
### April 6th 2022
- The ability to configure core components in the `[server]`section
is now deprecated. When legacy items are detected in `[server]` a
warning will be generated. It is crucially important to move configuration
to the correct section as in the future it will be a hard requirement.
### Feburary 22nd 2022
- The `on_when_upload_queued` option for [power] devices has been
deprecated in favor of `on_when_job_queued`. As the new option
name implies, this option will power on the device when any new
job is queued, not only when its sourced from an upload. The
`on_when_upload_queued` option will be treated as an alias to
`on_when_job_queued` until its removal.
### February 16th 2022
- Webcam settings can now be defined in the `moonraker.conf` file, under
the `[octoprint_compat]` section. The default values are being used as
default values.
Default values:
| Setting | Default value |
|---------|---------------|
| flip_h | False |
| flip_v | False |
| rotate_90 | False |
| stream_url | /webcam/?action=stream |
| webcam_enabled | True |
### January 22th 2022
- The `color_order` option in the `[wled]` section has been deprecated.
This is configured in wled directly. This is not a breaking change,
the setting will simply be ignored not affecting functionality.
### December 24th 2021
- The `password_file` option in the `[mqtt]` section has been deprecated.
Use the `password` option instead. This option may be a template, thus
can resolve secrets stored in the `[secrets]` module.
### November 7th 2021
- Previously all core components received configuration through
the `[server]` config section. As Moonraker's core functionality
has expanded this is becoming unsustainable, thus core components
should now be configured in their own section. For example, the
`config_path` and `log_path` should now be configured in the
`[file_manager]` section of `moonraker.conf`. See the
[configuration documentation](https://moonraker.readthedocs.io/en/latest/configuration/)
for details. This is not a breaking change, core components
will still fall back to checking the `[server]` section for
configuration.
### April 19th 2021
- The `[authorization]` module is now a component, thus is only
loaded if the user has it configured in `moonraker.conf`. This
deprecates the previous `enable` option, as it is enabled
if configured and disabled otherwise.
- The API Key is now stored in the database. This deprecates the
`api_key_file` option in the `[authorization]` module. Users can
no longer read the contents of the API Key file to retrieve the
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
print the API Key. Alternative a user can navigate to
`http://{moonraker-host}/access/api_key` from a trusted client
to retrieve the API Key.
### March 10th 2021
- The `cors_domain` option in the `[authoriztion]` section is now
checked for dangerous entries. If a domain entry contains a
wildcard in the top level domain (ie: `http://www.*`) then it
will be rejected, as malicious website can easily reproduce
this match.
### March 6th 2021
- The `enable_debug_logging` in the `[server]` section now defaults
to `False`. This dramatically reduces the amount of logging produced
by Moonraker for the typical user.
### March 4th 2021
- To enable OctoPrint compatibility with slicer uploads it is now
required to add `[octoprint_compat]` to `moonraker.conf`. After
making this change it is necessary to restart the Moonraker service
so the module is loaded.
### December 31st 2020
- The file manager no longer restricts the `config_path` to a folder
within the HOME directory. The path may not be the system root,
however it can reside anywhere else on the file system as long as
Moonraker has read and write access to the directory. This applies
to gcode path received from Klipper via the `virtual_sdcard` section
as well.
### December 6th 2020
- Moonraker is now installed as a systemd service. This allows logging
to stdout which can be viewed with the `journalctl -u moonraker` command.
This changes requires the user to rerun the install script. If
`moonraker.conf` is not located in the home directory, the command
will looks something like the following:
cd ~/moonraker
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
Otherwise you can run the install script with no arguments.
### November 19th 2020
- The install script (`install-moonraker.sh`) now has command-line
options:\
`-r` Rebuild the python virtual env\
`-f` Force an overwrite of `/etc/default/moonraker` during installation\
`-c /path/to/moonraker.conf` Allows user to specify the path to
moonraker.conf during configuration. Using this in conjunction with `-f`
will update the defaults file wih the new path.
- New dependencies have been added to Moonraker which require reinstallation.
Run the following command to reinstall and rebuild the virtualenv:
~/moonraker/scripts/install-moonraker.sh -r
- The power plugin configuration has changed. See the
[install guide](installation.md#power-control-plugin) for
details on the new configuration.
- Users transitioning from the previous version of the power plugin will need
to unexport any curently used pins. For example, the following command
may be used to unexport pin 19:
echo 19 > /sys/class/gpio/unexport
Alternatively one may reboot the machine after upgrading:
cd ~/moonraker/
git pull
~/moonraker/scripts/install-moonraker.sh -r
sudo reboot
Make sure that the power plugin configuration has been updated prior
to rebooting the machine.
+6838 -597
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
site_name: Moonraker
site_url: https://moonraker.readthedocs.io
repo_url: https://github.com/Arksine/moonraker
nav:
- 'User Documentation':
- Installation: installation.md
- Configuration : configuration.md
- 'Developer Documenation':
- Remote API: web_api.md
- Printer Objects: printer_objects.md
- Components: components.md
- 'Miscellaneous':
- Contributing: contributing.md
- Changelog: changelog.md
theme:
name: readthedocs
plugins:
- search
markdown_extensions:
- admonition
- pymdownx.superfences
- pymdownx.highlight:
use_pygments: false
- pymdownx.inlinehilite
+5
View File
@@ -0,0 +1,5 @@
# Top level package definition for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
+9
View File
@@ -0,0 +1,9 @@
# Package entry point for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from .server import main
main()
+968 -233
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
# Assets Package Definition
+500
View File
@@ -0,0 +1,500 @@
<html>
<head>
<title>Moonraker {{ version }}</title>
<style>
body {
background-color: rgb(48, 48, 48);
color: rgb(230, 230, 230);
font-family: Arial, Helvetica, sans-serif;
margin: 0px;
}
.nav-bar {
width: 100%;
overflow: hidden;
}
.nav-bar a {
float: right;
text-align: center;
padding: .5em .75em;
font-size: 1.2em;
text-decoration: none;
color: rgb(230, 230, 230);
}
.intro {
font-size: 1.1em;
margin-top: 7rem;
margin-left: auto;
margin-right: auto;
width: 60%;
}
.intro h1 {
font-size: 2.2rem;
text-align: center;
}
.status {
display: flex;
margin-top: 2rem;
margin-left: auto;
margin-right: auto;
width: 80%;
align-items: baseline;
justify-content: center;
column-gap: 1.5rem;
row-gap: 1.5rem;
flex-wrap: wrap;
}
.card {
background:none;
border: 0px;
border-radius: .75rem;
width: 25rem;
}
.card h1 {
background-color: #225353;
text-align: center;
line-height: 2.2rem;
font-size: 1.1rem;
height: 2.2rem;
margin: 0;
border-top-left-radius: .75rem;
border-top-right-radius: .75rem;
}
.card .content{
background-color: #1a1a1a;
border-bottom-left-radius: .75rem;
border-bottom-right-radius: .75rem;
padding: .5rem;
}
.card .entry {
display: inline-block;
width: 100%;
}
.card .entry:not(:last-child) {
margin-bottom: .4rem;
}
.card .value {
float: right;
display: inline;
}
.messages {
margin-top: 2rem;
width: 51.5rem;
padding: .5rem;
}
.messages .item {
padding: .5rem;
background: #242424;
border-radius: .4rem;
}
.messages .announcement {
cursor: pointer;
}
.messages .item:not(:last-child) {
margin-bottom: .5rem;
}
.messages .item a {
font-size: 1.2rem;
margin: 0;
font-weight: 600;
padding: 0rem;
margin-bottom: .1rem;
text-decoration: None;
color: rgb(230, 230, 230);
}
.messages .item:hover {
background-color: #3f3f3f;
}
.messages .item:hover a,
.messages .item a:hover {
color: rgb(235, 199, 0);
}
.messages .item p {
font-size: 1rem;
}
.warning h1 {
animation: glow 1s ease-in-out infinite alternate;
}
@keyframes glow {
from {
background-color: #225353;
}
to {
background-color: rgb(160, 64, 8);
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-card {
background: none;
position: relative;
border: 0px;
border-radius: 1rem;
background-color: #1a1a1a;
margin: 20% auto 2rem auto;
padding: 0rem;
border: 0px;
width: 50%;
animation-name: fadein;
animation-duration: .5s;
}
.modal-card h1 {
background-color: #006f7e;
text-align: center;
line-height: 3rem;
font-size: 1.1rem;
height: 3rem;
margin: 0;
border-top-left-radius: 1rem;
border-top-right-radius: 1rem;
}
.modal-content {
background-color: #3e3e3e;
padding: 1rem;
margin: 0;
height: auto
}
.modal-content .entry {
display: inline-block;
width: 100%;
}
.modal-content .entry:not(:last-child) {
margin-bottom: .5rem;
}
.modal-content .value {
float: right;
display: inline;
}
.modal-content input {
width: 100%;
padding: 8px;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 1rem; color: #222;
background: #F7F7F7;
}
.modal-footer {
display: inline-block;
background-color: #3e3e3e;
margin: 0;
height: auto;
width: 100%;
border-bottom-left-radius: 1rem;
border-bottom-right-radius: 1rem;
}
.modal-button {
float: right;
background: #cecece;
border: none;
width: auto;
overflow: visible;
font-size: 1rem;
font-weight: bold;
color: rgb(0, 0, 0);
padding: .4rem .5rem;
margin: 0rem .5rem .5rem 0rem;
border-radius: .5rem;
-webkit-border-radius: .5rem;
-moz-border-radius: .5rem;
}
.modal-button:hover {
color: rgb(8, 154, 45);
text-decoration: none;
cursor: pointer;
}
.modal-status {
display: none;
position: relative;
border: 0;
border-radius: 1rem;
background-color: #3e3e3e;
margin: auto;
padding: 0rem;
width: 50%;
animation-name: fadebottom;
animation-duration: .5s;
}
.modal-status:hover {
cursor: pointer;
}
.modal-status .content {
display: inline-block;
margin: 1rem;
}
@keyframes fadebottom {
from {top: 10em; opacity: 0}
to {top: 0em; opacity: 1}
}
@keyframes fadein {
from {opacity: 0}
to {opacity: 1}
}
</style>
<script>
function setClickable(id) {
const item = document.querySelector(`#${id}`);
const primary_link = item.querySelector("a");
const clickable = Array.from(item.querySelectorAll(".clickable"));
clickable.forEach((element) => {
element.addEventListener("click", (evt) => {
evt.stopPropagation();
})
});
function onItemClicked(evt) {
const noTextSelected = !window.getSelection().toString();
if (noTextSelected)
primary_link.click();
}
item.addEventListener("click", onItemClicked);
}
</script>
</head>
<body>
<main>
<div class="nav-bar">
<a href="https://github.com/Arksine/moonraker">GitHub</a>
<a href="https://moonraker.readthedocs.io">Documentation</a>
</div>
<div class="intro">
<h1>Welcome to Moonraker</h1>
<p>You may have intended
to navigate to one of Moonraker's front ends, if so check
that you entered the correct port in the address bar.
</p>
</div>
<div class="status">
<article class="card">
<h1>Authorization</h1>
<div class="content">
<div class="entry">
Request IP:
<div class="value">{{ remote_ip }}</div>
</div>
<div class="entry">
Authorized:
<div class="value">{{ authorized }}</div>
</div>
<div class="entry">
CORS Enabled:
<div class="value">{{ cors_enabled }}</div>
</div>
</div>
</article>
<article class="card">
<h1>Status</h1>
<div class="content">
<div class="entry">
Version:
<div class="value">{{ version }}</div>
</div>
<div class="entry">
Websocket Count:
<div class="value">{{ ws_count }}</div>
</div>
<div class="entry">
Klipper State:
<div class="value">{{ klippy_state }}</div>
</div>
</div>
</article>
{% if summary %}
<article class="card messages">
<h1>Summary</h1>
<div class="content">
{% for item in summary %}
<article class="item">{{ item }}</article>
{% endfor %}
</div>
</article>
{% endif %}
{% if announcements %}
<article class="card messages">
<h1>Announcements</h1>
<div class="content">
{% for item in announcements %}
{% set id = "announcement-" + item["entry_id"].replace("/", "-") %}
<article class="item announcement" id="{{ id }}">
{% set url = item["url"] %}
<a href="{{ url }}" class="clickable">{{ item["title"] }}</a>
<p>{{ item["description"] }}</p>
</article>
<script>
setClickable("{{ id }}");
</script>
{% endfor %}
</div>
</article>
{% endif %}
{% if warnings %}
<article class="card messages warning">
<h1>Warnings</h1>
<div class="content">
{% for warn in warnings %}
<article class="item">{{ warn }}</article>
{% endfor %}
</div>
</article>
{% endif %}
</div>
<div id="update_modal" class="modal">
<div class="modal-card">
<h1 id="modal_header_msg">
Moonraker Sudo Password Request
</h1>
<div id="modal_body" class="modal-content">
<div id="main_form">
<div class="entry">
Service Name:
<div class="value">
{{ service_name }}
</div>
</div>
<div class="entry">
Host Name:
<div class="value">
{{ hostname }}
</div>
</div>
<div class="entry">
Host IP Address:
<div class="value">
{{ local_ip }}
</div>
</div>
<div class="entry">
{{ sudo_request_message }}
Please enter the password for linux user <b>{{ linux_user }}</b>:
</div>
<div class="entry">
<input id="sudo_passwd" name="sudo_passwd" type="password" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="modal_close" class="modal-button">Cancel</button>
<button type="button" id="modal_submit" class="modal-button">Submit</button>
</div>
</div>
<div id="modal_status" class="modal-status">
<div id="status_msg" class="content">
Status Text
</div>
</div>
</div>
<script>
const modal = document.getElementById("update_modal");
{% if sudo_requested %}
modal.style.display = "block";
{% endif %}
const main_form = document.getElementById("main_form")
const status_item = document.getElementById("modal_status");
const status_div = document.getElementById("status_msg");
function update_modal(status_msg) {
status_div.innerHTML = status_msg
status_item.style.display = "block";
}
function dismiss_status() {
status_item.style.display = "none";
}
function check_success(req) {
return (req.status < 205 || req.status == 304);
}
function post_machine_password(passwd) {
let pwd_req = new XMLHttpRequest();
pwd_req.onload = () => {
if (check_success(pwd_req)) {
console.log("Successfully Set Sudo Password");
let resp = JSON.parse(pwd_req.responseText)
let msg = resp.result.sudo_responses.join("<br/>")
msg += "<br/><br/>You may close this window and return to the front end.";
update_modal(msg);
} else {
console.log("Password Request Error");
let err_msg = `Code ${pwd_req.status}: `;
let response = pwd_req.responseText;
try {
let json_resp = JSON.parse(response);
err_msg = json_resp.error.message;
} catch (error) {}
update_modal(
"Request failed with error:<br/><br/>" + err_msg +
"<br/><br/>You may need to manually update your installation."
);
}
};
pwd_req.onerror = () => {
console.log("Error setting password");
update_modal(
"Request to set sudo password failed with " +
"a network error."
)
};
pwd_req.open("POST", "/machine/sudo/password");
pwd_req.setRequestHeader("Content-Type", "application/json");
pwd_req.send(JSON.stringify({"password": passwd}));
}
const modal_submit = document.getElementById("modal_submit");
const pwd_input = document.getElementById("sudo_passwd");
const modal_close = document.getElementById("modal_close");
modal_submit.onclick = () => {
let val = pwd_input.value;
pwd_input.value = "";
dismiss_status();
post_machine_password(val);
};
pwd_input.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
event.preventDefault();
modal_submit.click();
}
});
modal_close.onclick = () => {
modal.style.display = "none";
};
status_item.onclick = () => {
dismiss_status();
}
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
};
</script>
</main>
</body>
</html>
-247
View File
@@ -1,247 +0,0 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import base64
import uuid
import os
import time
import ipaddress
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
TOKEN_TIMEOUT = 5
CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
class Authorization:
def __init__(self, api_key_file):
self.api_key_loc = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = True
self.trusted_ips = []
self.trusted_ranges = []
self.trusted_connections = {}
self.access_tokens = {}
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
def load_config(self, config):
self.auth_enabled = config.get("require_auth", self.auth_enabled)
# reset trusted ips
self.trusted_ips = []
trusted_ips = config.get("trusted_ips", [])
for ip in trusted_ips:
try:
ip_addr = ipaddress.ip_address(ip)
except ValueError:
logging.info("IP address <%s> invalid" % (ip))
continue
self.trusted_ips.append(ip_addr)
# reset trusted ranges
self.trusted_ranges = []
trusted_ranges = config.get("trusted_ranges", [])
for ip_range in trusted_ranges:
try:
ip_net = ipaddress.ip_network(ip_range)
except ValueError:
logging.info("IP range <%s> invalid" % (ip_range))
continue
self.trusted_ranges.append(ip_net)
self._reset_trusted_connections()
t_clients = [str(ip) for ip in self.trusted_ips] + \
[str(rng) for rng in self.trusted_ranges]
logging.info(
"Authorization Configuration Loaded\n"
"Auth Enabled: %s\n"
"Trusted Clients:\n%s" %
(self.auth_enabled, "\n".join(t_clients)))
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", None, ['GET', 'POST'],
self._handle_apikey_request, http_only=True)
app.register_local_handler(
"/access/oneshot_token", None, ['GET'],
self._handle_token_request, http_only=True)
async def _handle_apikey_request(self, path, method, args):
if method.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, path, method, args):
return self.get_access_token()
def _read_api_key(self):
if os.path.exists(self.api_key_loc):
with open(self.api_key_loc, 'r') as f:
api_key = f.read()
return api_key
# API Key file doesn't exist. Generate
# a new api key and create the file.
logging.info(
"No API Key file found, creating new one at:\n%s"
% (self.api_key_loc))
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_loc, 'w') as f:
f.write(api_key)
return api_key
def _reset_trusted_connections(self):
valid_conns = {}
for ip, access_time in self.trusted_connections.items():
if self._check_authorized_ip(ip):
valid_conns[ip] = access_time
else:
logging.info(
"Connection [%s] no longer trusted, removing" % (ip))
self.trusted_connections = valid_conns
def _check_authorized_ip(self, ip):
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
return False
def _prune_conn_handler(self):
cur_time = time.time()
expired_conns = []
for ip, access_time in self.trusted_connections.items():
if cur_time - access_time > CONNECTION_TIMEOUT:
expired_conns.append(ip)
for ip in expired_conns:
self.trusted_connections.pop(ip, None)
logging.info(
"Trusted Connection Expired, IP: %s" % (ip))
def _token_expire_handler(self, token):
self.access_tokens.pop(token, None)
def is_enabled(self):
return self.auth_enabled
def get_access_token(self):
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
self.access_tokens[token] = ioloop.call_later(
TOKEN_TIMEOUT, self._token_expire_handler, token)
return token
def _check_trusted_connection(self, ip):
if ip is not None:
if ip in self.trusted_connections:
self.trusted_connections[ip] = time.time()
return True
elif self._check_authorized_ip(ip):
logging.info(
"Trusted Connection Detected, IP: %s" % (ip))
self.trusted_connections[ip] = time.time()
return True
return False
def _check_access_token(self, token):
if token in self.access_tokens:
token_handler = self.access_tokens.pop(token, None)
IOLoop.current().remove_timeout(token_handler)
return True
else:
return False
def check_authorized(self, request):
# Authorization is disabled, request may pass
if not self.auth_enabled:
return True
# Check if IP is trusted
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
"Unable to Create IP Address %s" % (request.remote_ip))
ip = None
if self._check_trusted_connection(ip):
return True
# Check API Key Header
key = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return True
# Check one-shot access token
token = request.arguments.get('token', [b""])[0].decode()
if self._check_access_token(token):
return True
return False
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self, server, auth):
self.server = server
self.auth = auth
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, server, auth, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = server
self.auth = auth
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
@@ -1,5 +1,5 @@
# Package definition for the plugins directory
# Package definition for the components directory
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
+541
View File
@@ -0,0 +1,541 @@
# Support for Moonraker/Klipper/Client announcements
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import datetime
import pathlib
import asyncio
import logging
import email.utils
import xml.etree.ElementTree as etree
from typing import (
TYPE_CHECKING,
Awaitable,
List,
Dict,
Any,
Optional,
Union
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .http_client import HttpClient
from .database import MoonrakerDatabase
MOONLIGHT_URL = "https://arksine.github.io/moonlight"
UPDATE_CHECK_TIME = 1800.
etree.register_namespace("moonlight", MOONLIGHT_URL)
class Announcements:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.entry_mgr = EntryManager(config)
self.eventloop = self.server.get_event_loop()
self.update_timer = self.eventloop.register_timer(
self._handle_update_timer
)
self.request_lock = asyncio.Lock()
self.dev_mode = config.getboolean("dev_mode", False)
self.subscriptions: Dict[str, RssFeed] = {
"moonraker": RssFeed("moonraker", self.entry_mgr, self.dev_mode),
"klipper": RssFeed("klipper", self.entry_mgr, self.dev_mode)
}
self.stored_feeds: List[str] = []
sub_list: List[str] = config.getlist("subscriptions", [])
self.configured_feeds: List[str] = ["moonraker", "klipper"]
for sub in sub_list:
sub = sub.lower()
if sub in self.subscriptions:
continue
self.configured_feeds.append(sub)
self.subscriptions[sub] = RssFeed(
sub, self.entry_mgr, self.dev_mode
)
self.server.register_endpoint(
"/server/announcements/list", ["GET"],
self._list_announcements
)
self.server.register_endpoint(
"/server/announcements/dismiss", ["POST"],
self._handle_dismiss_request
)
self.server.register_endpoint(
"/server/announcements/update", ["POST"],
self._handle_update_request
)
self.server.register_endpoint(
"/server/announcements/feed", ["POST", "DELETE"],
self._handle_feed_request
)
self.server.register_endpoint(
"/server/announcements/feeds", ["GET"],
self._handle_list_feeds
)
self.server.register_notification(
"announcements:dismissed", "announcement_dismissed"
)
self.server.register_notification(
"announcements:entries_updated", "announcement_update"
)
self.server.register_notification(
"announcements:dismiss_wake", "announcement_wake"
)
async def component_init(self) -> None:
db: MoonrakerDatabase = self.server.lookup_component("database")
stored_feeds: List[str] = await db.get_item(
"moonraker", "announcements.stored_feeds", []
)
self.stored_feeds = stored_feeds
for name in stored_feeds:
if name in self.subscriptions:
continue
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
self.subscriptions[name] = feed
async with self.request_lock:
await self.entry_mgr.initialize()
for sub in self.subscriptions.values():
await sub.initialize()
self.update_timer.start()
async def _handle_update_timer(self, eventtime: float) -> float:
changed = False
entries: List[Dict[str, Any]] = []
async with self.request_lock:
for sub in self.subscriptions.values():
ret = await sub.update_entries()
changed |= ret
if changed:
entries = await self.entry_mgr.list_entries()
self.server.send_event(
"announcements:entries_updated", {"entries": entries}
)
return eventtime + UPDATE_CHECK_TIME
async def _handle_dismiss_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
entry_id: str = web_request.get_str("entry_id")
wake_time: Optional[int] = web_request.get_int("wake_time", None)
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
return {
"entry_id": entry_id
}
async def _list_announcements(
self, web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
incl_dsm = web_request.get_boolean("include_dismissed", True)
entries = await self.entry_mgr.list_entries(incl_dsm)
return {
"entries": entries,
"feeds": list(self.subscriptions.keys())
}
async def _handle_update_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
subs: Optional[Union[str, List[str]]]
subs = web_request.get("subscriptions", None)
if isinstance(subs, str):
subs = [sub.strip() for sub in subs.split(",") if sub.strip()]
elif subs is None:
subs = list(self.subscriptions.keys())
for sub in subs:
if sub not in self.subscriptions:
raise self.server.error(f"No subscription for {sub}")
async with self.request_lock:
changed = False
for sub in subs:
ret = await self.subscriptions[sub].update_entries()
changed |= ret
entries = await self.entry_mgr.list_entries()
if changed:
self.eventloop.delay_callback(
.05, self.server.send_event,
"announcements:entries_updated",
{"entries": entries})
return {
"entries": entries,
"modified": changed
}
async def _handle_list_feeds(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"feeds": list(self.subscriptions.keys())}
async def _handle_feed_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
name: str = web_request.get("name")
name = name.lower()
changed: bool = False
db: MoonrakerDatabase = self.server.lookup_component("database")
result = "skipped"
if action == "POST":
if name not in self.subscriptions:
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
self.subscriptions[name] = feed
await feed.initialize()
changed = await feed.update_entries()
self.stored_feeds.append(name)
db.insert_item(
"moonraker", "announcements.stored_feeds", self.stored_feeds
)
result = "added"
elif action == "DELETE":
if name not in self.stored_feeds:
raise self.server.error(f"Feed '{name}' not stored")
if name in self.configured_feeds:
raise self.server.error(
f"Feed '{name}' exists in the configuration, cannot remove"
)
self.stored_feeds.remove(name)
db.insert_item(
"moonraker", "announcements.stored_feeds", self.stored_feeds
)
if name in self.subscriptions:
del self.subscriptions[name]
changed = await self.entry_mgr.prune_by_feed(name)
logging.info(f"Removed Announcement Feed: {name}")
result = "removed"
else:
raise self.server.error(f"Feed does not exist: {name}")
if changed:
entries = await self.entry_mgr.list_entries()
self.eventloop.delay_callback(
.05, self.server.send_event, "announcements:entries_updated",
{"entries": entries}
)
return {
"feed": name,
"action": result
}
def add_internal_announcement(
self, title: str, desc: str, url: str, priority: str, feed: str
) -> Dict[str, Any]:
date = datetime.datetime.utcnow()
entry_id: str = f"{feed}/{date.isoformat(timespec='seconds')}"
entry = {
"entry_id": entry_id,
"url": url,
"title": title,
"description": desc,
"priority": priority,
"date": date.timestamp(),
"dismissed": False,
"date_dismissed": None,
"dismiss_wake": None,
"source": "internal",
"feed": feed
}
self.entry_mgr.add_entry(entry)
return entry
async def remove_announcement(self, entry_id: str) -> None:
ret = await self.entry_mgr.remove_entry(entry_id)
if ret is not None:
entries = await self.entry_mgr.list_entries()
self.server.send_event(
"announcements:entries_updated", {"entries": entries}
)
async def dismiss_announcement(
self, entry_id, wake_time: Optional[int] = None
) -> None:
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
async def get_announcements(
self, include_dismissed: bool = False
) -> List[Dict[str, Any]]:
return await self.entry_mgr.list_entries(include_dismissed)
def close(self):
self.entry_mgr.close()
class EntryManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
database: MoonrakerDatabase
database = self.server.lookup_component("database")
database.register_local_namespace("announcements")
self.announce_db = database.wrap_namespace("announcements")
self.entry_id_map: Dict[str, str] = {}
self.next_key = 0
self.dismiss_handles: Dict[str, asyncio.TimerHandle] = {}
async def initialize(self) -> None:
last_key = ""
eventloop = self.server.get_event_loop()
curtime = datetime.datetime.utcnow().timestamp()
for key, entry in await self.announce_db.items():
last_key = key
aid = entry["entry_id"]
self.entry_id_map[aid] = key
if entry["dismissed"]:
wake_time: Optional[float] = entry.get("dismiss_wake")
if wake_time is not None:
time_diff = wake_time - curtime
if time_diff - 10. < 0.:
# announcement is near or past wake time
entry["dismissed"] = False
entry["date_dismissed"] = None
entry["dismiss_wake"] = None
self.announce_db[key] = entry
else:
self.dismiss_handles[key] = eventloop.delay_callback(
time_diff, self._wake_dismissed, key
)
if last_key:
self.next_key = int(last_key, 16) + 1
async def list_entries(
self, include_dismissed: bool = True
) -> List[Dict[str, Any]]:
vals: List[Dict[str, Any]] = await self.announce_db.values()
vals = sorted(vals, key=lambda x: x["date"], reverse=True)
if include_dismissed:
return vals
return [val for val in vals if not val["dismissed"]]
def has_entry(self, entry_id: str) -> bool:
return entry_id in self.entry_id_map
def add_entry(self, entry: Dict[str, Any]) -> Awaitable[None]:
aid = entry["entry_id"]
key = f"{self.next_key:06X}"
self.next_key += 1
self.entry_id_map[aid] = key
return self.announce_db.insert(key, entry)
def remove_entry(self, entry_id: str) -> Awaitable[Any]:
key = self.entry_id_map.pop(entry_id, None)
if key is None:
raise self.server.error(f"No key matching entry id: {entry_id}")
return self.announce_db.pop(key, None)
async def dismiss_entry(
self, entry_id: str, wake_time: Optional[int] = None
) -> None:
key = self.entry_id_map.get(entry_id)
if key is None:
raise self.server.error(f"No key matching entry id: {entry_id}")
entry = await self.announce_db[key]
is_dismissed = entry["dismissed"]
if is_dismissed:
return
entry["dismissed"] = True
eventloop = self.server.get_event_loop()
curtime = datetime.datetime.utcnow().timestamp()
entry["date_dismissed"] = curtime
if wake_time is not None:
entry["dismiss_wake"] = curtime + wake_time
self.dismiss_handles[key] = eventloop.delay_callback(
wake_time, self._wake_dismissed, key
)
self.announce_db[key] = entry
eventloop.delay_callback(
.05, self.server.send_event, "announcements:dismissed",
{"entry_id": entry_id}
)
async def _wake_dismissed(self, key: str) -> None:
self.dismiss_handles.pop(key, None)
entry = await self.announce_db.get(key, None)
if entry is None:
return
if not entry["dismissed"]:
return
entry["dismissed"] = False
entry["date_dismissed"] = None
entry["dismiss_wake"] = None
self.announce_db[key] = entry
self.server.send_event(
"announcements:dismiss_wake", {"entry_id": entry["entry_id"]}
)
def prune_by_prefix(self, prefix: str, valid_ids: List[str]) -> bool:
del_keys: List[str] = []
for entry_id in list(self.entry_id_map.keys()):
if not entry_id.startswith(prefix) or entry_id in valid_ids:
continue
# Entry is no longer valid and should be removed
key = self.entry_id_map.pop(entry_id, None)
if key is not None:
del_keys.append(key)
if del_keys:
self.announce_db.delete_batch(del_keys)
return True
return False
async def prune_by_feed(self, feed: str) -> bool:
entries = await self.list_entries()
del_keys: List[str] = []
for entry in entries:
if entry["feed"].lower() == feed:
key = self.entry_id_map.pop(entry["entry_id"], None)
if key is not None:
del_keys.append(key)
if del_keys:
self.announce_db.delete_batch(del_keys)
return True
return False
def close(self):
for handle in self.dismiss_handles.values():
handle.cancel()
class RssFeed:
def __init__(
self, name: str, entry_mgr: EntryManager, dev_mode: bool
) -> None:
self.server = entry_mgr.server
self.name = name
self.entry_mgr = entry_mgr
self.client: HttpClient = self.server.lookup_component("http_client")
self.database: MoonrakerDatabase
self.database = self.server.lookup_component("database")
self.xml_file = f"{self.name}.xml"
self.asset_url = f"{MOONLIGHT_URL}/assets/{self.xml_file}"
self.last_modified: int = 0
self.etag: Optional[str] = None
self.dev_xml_path: Optional[pathlib.Path] = None
if dev_mode:
res_dir = pathlib.Path(__file__).parent.parent.parent.resolve()
res_path = res_dir.joinpath(".devel/announcement_xml")
self.dev_xml_path = res_path.joinpath(self.xml_file)
async def initialize(self) -> None:
self.etag = await self.database.get_item(
"moonraker", f"announcements.{self.name}.etag", None
)
async def update_entries(self) -> bool:
if self.dev_xml_path is None:
xml_data = await self._fetch_moonlight()
else:
xml_data = await self._fetch_local_folder()
if not xml_data:
return False
return self._parse_xml(xml_data)
async def _fetch_moonlight(self) -> str:
headers = {"Accept": "application/xml"}
if self.etag is not None:
headers["If-None-Match"] = self.etag
resp = await self.client.get(
self.asset_url, headers, attempts=5,
retry_pause_time=.5, enable_cache=False,
)
if resp.has_error():
logging.info(
f"Failed to update subscription '{self.name}': {resp.error}"
)
return ""
if resp.status_code == 304:
logging.debug(f"Content at {self.xml_file} not modified")
return ""
# update etag
self.etag = resp.etag
try:
if self.etag is not None:
self.database.insert_item(
"moonraker", f"announcements.{self.name}.etag", resp.etag
)
else:
self.database.delete_item(
"moonraker", f"announcements.{self.name}.etag",
)
except self.server.error:
pass
return resp.text
async def _fetch_local_folder(self) -> str:
if self.dev_xml_path is None:
return ""
if not self.dev_xml_path.is_file():
logging.info(f"No file at path {self.dev_xml_path}")
return ""
mtime = self.dev_xml_path.stat().st_mtime_ns
if mtime <= self.last_modified:
logging.debug(f"Content at {self.xml_file} not modified")
return ""
try:
eventloop = self.server.get_event_loop()
xml_data = await eventloop.run_in_thread(
self.dev_xml_path.read_text)
except Exception:
logging.exception(f"Unable read xml file {self.dev_xml_path}")
return ""
self.last_modified = mtime
return xml_data
def _parse_xml(self, xml_data: str) -> bool:
root = etree.fromstring(xml_data)
channel = root.find("channel")
if channel is None:
root_str = etree.tostring(root, encoding="unicode")
logging.debug(f"Feed {self.name}: no channel found\n{root_str}")
return False
# extract prefix
prefix = channel.findtext("title", "").lower()
if not prefix:
logging.info(f"Feed {self.name}: No prefix found")
items = channel.findall("item")
valid_ids: List[str] = []
changed: bool = False
for item in items:
guid = item.findtext("guid")
if guid is None:
item_str = etree.tostring(item, encoding="unicode")
logging.debug(f"Feed {self.name}: Invalid Item\n{item_str}")
continue
if not prefix:
# fall back to first guid prefix
prefix = "/".join(guid.split("/")[:2])
elif not guid.startswith(prefix):
logging.debug(
f"Feed {self.name}: Guid {guid} is not "
f"prefixed with {prefix}")
valid_ids.append(guid)
if self.entry_mgr.has_entry(guid):
continue
try:
rfc_date = item.findtext("pubDate", "")
dt = email.utils.parsedate_to_datetime(rfc_date)
except Exception:
dt = datetime.datetime.utcnow()
entry: Dict[str, Any] = {
"entry_id": guid,
"url": item.findtext("link"),
"title": item.findtext("title"),
"description": item.findtext("description"),
"priority": item.findtext("category"),
"date": dt.timestamp(),
"dismissed": False,
"date_dismissed": None,
"dismiss_wake": None,
"source": "moonlight",
"feed": self.name
}
changed = True
self.entry_mgr.add_entry(entry)
logging.debug(f"Feed {self.name}: found entries {valid_ids}")
if prefix:
pruned = self.entry_mgr.prune_by_prefix(prefix, valid_ids)
changed = changed or pruned
return changed
def load_component(config: ConfigHelper) -> Announcements:
return Announcements(config)
+874
View File
@@ -0,0 +1,874 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import base64
import uuid
import hashlib
import secrets
import os
import time
import datetime
import ipaddress
import re
import socket
import logging
import json
from tornado.web import HTTPError
from libnacl.sign import Signer, Verifier
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Set,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest, WebsocketManager
from tornado.httputil import HTTPServerRequest
from tornado.web import RequestHandler
from .database import MoonrakerDatabase as DBComp
from .ldap import MoonrakerLDAP
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], asyncio.Handle]
# Helpers for base64url encoding and decoding
def base64url_encode(data: bytes) -> bytes:
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data: str) -> bytes:
pad_cnt = len(data) % 4
if pad_cnt:
data += "=" * (4 - pad_cnt)
return base64.urlsafe_b64decode(data)
ONESHOT_TIMEOUT = 5
TRUSTED_CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300.
AUTH_SOURCES = ["moonraker", "ldap"]
HASH_ITER = 100000
API_USER = "_API_KEY_USER_"
TRUSTED_USER = "_TRUSTED_USER_"
RESERVED_USERS = [API_USER, TRUSTED_USER]
JWT_EXP_TIME = datetime.timedelta(hours=1)
JWT_HEADER = {
'alg': "EdDSA",
'typ': "JWT"
}
class Authorization:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.login_timeout = config.getint('login_timeout', 90)
self.force_logins = config.getboolean('force_logins', False)
self.default_source = config.get('default_source', "moonraker").lower()
self.enable_api_key = config.getboolean('enable_api_key', True)
self.max_logins = config.getint("max_login_attempts", None, above=0)
self.failed_logins: Dict[IPAddr, int] = {}
if self.default_source not in AUTH_SOURCES:
raise config.error(
"[authorization]: option 'default_source' - Invalid "
f"value '{self.default_source}'"
)
self.ldap: Optional[MoonrakerLDAP] = None
if config.has_section("ldap"):
self.ldap = self.server.load_component(config, "ldap", None)
if self.default_source == "ldap" and self.ldap is None:
self.server.add_warning(
"[authorization]: Option 'default_source' set to 'ldap',"
" however [ldap] section failed to load or not configured"
)
database: DBComp = self.server.lookup_component('database')
database.register_local_namespace('authorized_users', forbidden=True)
self.user_db = database.wrap_namespace('authorized_users')
self.users: Dict[str, Dict[str, Any]] = self.user_db.as_dict()
api_user: Optional[Dict[str, Any]] = self.users.get(API_USER, None)
if api_user is None:
self.api_key = uuid.uuid4().hex
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
else:
self.api_key = api_user['api_key']
hi = self.server.get_host_info()
self.issuer = f"http://{hi['hostname']}:{hi['port']}"
self.public_jwks: Dict[str, Dict[str, Any]] = {}
for username, user_info in list(self.users.items()):
if username == API_USER:
# Validate the API User
for item in ["username", "api_key", "created_on"]:
if item not in user_info:
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
break
continue
else:
# validate created users
valid = True
for item in ["username", "password", "salt", "created_on"]:
if item not in user_info:
logging.info(
f"Authorization: User {username} does not "
f"contain field {item}, removing")
del self.users[username]
valid = False
break
if not valid:
continue
# generate jwks for valid users
if 'jwt_secret' in user_info:
try:
priv_key = self._load_private_key(user_info['jwt_secret'])
jwk_id = user_info['jwk_id']
except (self.server.error, KeyError):
logging.info("Invalid key found for user, removing")
user_info.pop('jwt_secret', None)
user_info.pop('jwk_id', None)
self.users[username] = user_info
continue
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
# sync user changes to the database
self.user_db.sync(self.users)
self.trusted_users: Dict[IPAddr, Any] = {}
self.oneshot_tokens: Dict[str, OneshotToken] = {}
self.permitted_paths: Set[str] = set()
# Get allowed cors domains
self.cors_domains: List[str] = []
for domain in config.getlist('cors_domains', []):
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.")
if domain.endswith("/"):
self.server.add_warning(
f"[authorization]: Invalid domain '{domain}' in option "
"'cors_domains'. Domain's cannot contain a trailing "
"slash.")
else:
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips: List[IPAddr] = []
self.trusted_ranges: List[IPNetwork] = []
self.trusted_domains: List[str] = []
for val in config.getlist('trusted_clients', []):
# Check IP address
try:
tc = ipaddress.ip_address(val)
except ValueError:
pass
else:
self.trusted_ips.append(tc)
continue
# Check ip network
try:
tn = ipaddress.ip_network(val)
except ValueError as e:
if "has host bits set" in str(e):
self.server.add_warning(
f"[authorization]: Invalid CIDR expression '{val}' "
"in option 'trusted_clients'")
continue
pass
else:
self.trusted_ranges.append(tn)
continue
# Check hostname
match = re.match(r"([a-z0-9]+(-[a-z0-9]+)*\.?)+[a-z]{2,}$", val)
if match is not None:
self.trusted_domains.append(val.lower())
else:
self.server.add_warning(
f"[authorization]: Invalid domain name '{val}' "
"in option 'trusted_clients'")
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges] +
self.trusted_domains)
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
eventloop = self.server.get_event_loop()
self.prune_timer = eventloop.register_timer(
self._prune_conn_handler)
# Register Authorization Endpoints
self.permitted_paths.add("/server/redirect")
self.permitted_paths.add("/access/login")
self.permitted_paths.add("/access/refresh_jwt")
self.permitted_paths.add("/access/info")
self.server.register_endpoint(
"/access/login", ['POST'], self._handle_login,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/logout", ['POST'], self._handle_logout,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/user", ['GET', 'POST', 'DELETE'],
self._handle_user_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/users/list", ['GET'], self._handle_list_request,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/oneshot_token", ['GET'],
self._handle_oneshot_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/info", ['GET'],
self._handle_info_request, transports=['http', 'websocket'])
wsm: WebsocketManager = self.server.lookup_component("websockets")
wsm.register_notification("authorization:user_created")
wsm.register_notification(
"authorization:user_deleted", event_type="logout"
)
wsm.register_notification(
"authorization:user_logged_out", event_type="logout"
)
def register_permited_path(self, path: str) -> None:
self.permitted_paths.add(path)
def is_path_permitted(self, path: str) -> bool:
return path in self.permitted_paths
def _sync_user(self, username: str) -> None:
self.user_db[username] = self.users[username]
async def component_init(self) -> None:
self.prune_timer.start(delay=PRUNE_CHECK_TIME)
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = uuid.uuid4().hex
self.users[API_USER]['api_key'] = self.api_key
self._sync_user(API_USER)
return self.api_key
async def _handle_oneshot_request(self, web_request: WebRequest) -> str:
ip = web_request.get_ip_address()
assert ip is not None
user_info = web_request.get_current_user()
return self.get_oneshot_token(ip, user_info)
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
ip = web_request.get_ip_address()
if ip is not None and self.check_logins_maxed(ip):
raise HTTPError(
401, "Unauthorized, Maximum Login Attempts Reached"
)
try:
ret = await self._login_jwt_user(web_request)
except asyncio.CancelledError:
raise
except Exception:
if ip is not None:
failed = self.failed_logins.get(ip, 0)
self.failed_logins[ip] = failed + 1
raise
if ip is not None:
self.failed_logins.pop(ip, None)
return ret
async def _handle_logout(self, web_request: WebRequest) -> Dict[str, str]:
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No user logged in")
username: str = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid log out request for user {username}")
self.users[username].pop("jwt_secret", None)
jwk_id: str = self.users[username].pop("jwk_id", None)
self._sync_user(username)
self.public_jwks.pop(jwk_id, None)
eventloop = self.server.get_event_loop()
eventloop.delay_callback(
.005, self.server.send_event, "authorization:user_logged_out",
{'username': username}
)
return {
"username": username,
"action": "user_logged_out"
}
async def _handle_info_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
sources = ["moonraker"]
if self.ldap is not None:
sources.append("ldap")
return {
"default_source": self.default_source,
"available_sources": sources
}
async def _handle_refresh_jwt(self,
web_request: WebRequest
) -> Dict[str, str]:
refresh_token: str = web_request.get_str('refresh_token')
try:
user_info = self.decode_jwt(refresh_token, token_type="refresh")
except Exception:
raise self.server.error("Invalid Refresh Token", 401)
username: str = user_info['username']
if 'jwt_secret' not in user_info or "jwk_id" not in user_info:
raise self.server.error("User not logged in", 401)
private_key = self._load_private_key(user_info['jwt_secret'])
jwk_id: str = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
return {
'username': username,
'token': token,
'source': user_info.get("source", "moonraker"),
'action': 'user_jwt_refresh'
}
async def _handle_user_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "GET":
user = web_request.get_current_user()
if user is None:
return {
'username': None,
'source': None,
'created_on': None,
}
else:
return {
'username': user['username'],
'source': user.get("source", "moonraker"),
'created_on': user.get('created_on')
}
elif action == "POST":
# Create User
return await self._login_jwt_user(web_request, create=True)
elif action == "DELETE":
# Delete User
return self._delete_jwt_user(web_request)
raise self.server.error("Invalid Request Method")
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
user_list = []
for user in self.users.values():
if user['username'] == API_USER:
continue
user_list.append({
'username': user['username'],
'source': user.get("source", "moonraker"),
'created_on': user['created_on']
})
return {
'users': user_list
}
async def _handle_password_reset(self,
web_request: WebRequest
) -> Dict[str, str]:
password: str = web_request.get_str('password')
new_pass: str = web_request.get_str('new_password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
if user_info.get("source", "moonraker") == "ldap":
raise self.server.error(
f"Can´t Reset password for ldap user {username}")
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Reset Request for user {username}")
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
new_hashed_pass = hashlib.pbkdf2_hmac(
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
self.users[username]['password'] = new_hashed_pass
self._sync_user(username)
return {
'username': username,
'action': "user_password_reset"
}
async def _login_jwt_user(
self, web_request: WebRequest, create: bool = False
) -> Dict[str, Any]:
username: str = web_request.get_str('username')
password: str = web_request.get_str('password')
source: str = web_request.get_str(
'source', self.default_source
).lower()
if source not in AUTH_SOURCES:
raise self.server.error(f"Invalid 'source': {source}")
user_info: Dict[str, Any]
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for user {username}")
if source == "ldap":
if create:
raise self.server.error("Cannot Create LDAP User")
if self.ldap is None:
raise self.server.error(
"LDAP authentication not available", 401
)
await self.ldap.authenticate_ldap_user(username, password)
if username not in self.users:
create = True
if create:
if username in self.users:
raise self.server.error(f"User {username} already exists")
salt = secrets.token_bytes(32)
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
user_info = {
'username': username,
'password': hashed_pass,
'salt': salt.hex(),
'source': source,
'created_on': time.time()
}
self.users[username] = user_info
self._sync_user(username)
action = "user_created"
if source == "ldap":
# Dont notify user created
action = "user_logged_in"
create = False
else:
if username not in self.users:
raise self.server.error(f"Unregistered User: {username}")
user_info = self.users[username]
auth_src = user_info.get("source", "moonraker")
if auth_src != source:
raise self.server.error(
f"Moonraker cannot authenticate user '{username}', must "
f"specify source '{auth_src}'", 401
)
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
action = "user_logged_in"
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
jwt_secret_hex: Optional[str] = user_info.get('jwt_secret', None)
if jwt_secret_hex is None:
private_key = Signer()
jwk_id = base64url_encode(secrets.token_bytes()).decode()
user_info['jwt_secret'] = private_key.hex_seed().decode()
user_info['jwk_id'] = jwk_id
self.users[username] = user_info
self._sync_user(username)
self.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
else:
private_key = self._load_private_key(jwt_secret_hex)
jwk_id = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
refresh_token = self._generate_jwt(
username, jwk_id, private_key, token_type="refresh",
exp_time=datetime.timedelta(days=self.login_timeout))
conn = web_request.get_client_connection()
if create:
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.005, self.server.send_event,
"authorization:user_created",
{'username': username})
elif conn is not None:
conn.user_info = user_info
return {
'username': username,
'token': token,
'source': user_info.get("source", "moonraker"),
'refresh_token': refresh_token,
'action': action
}
def _delete_jwt_user(self, web_request: WebRequest) -> Dict[str, str]:
username: str = web_request.get_str('username')
current_user = web_request.get_current_user()
if current_user is not None:
curname = current_user.get('username', None)
if curname is not None and curname == username:
raise self.server.error(
f"Cannot delete logged in user {curname}")
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for reserved user {username}")
user_info: Optional[Dict[str, Any]] = self.users.get(username)
if user_info is None:
raise self.server.error(f"No registered user: {username}")
if 'jwk_id' in user_info:
self.public_jwks.pop(user_info['jwk_id'], None)
del self.users[username]
del self.user_db[username]
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.005, self.server.send_event,
"authorization:user_deleted",
{'username': username})
return {
"username": username,
"action": "user_deleted"
}
def _generate_jwt(self,
username: str,
jwk_id: str,
private_key: Signer,
token_type: str = "access",
exp_time: datetime.timedelta = JWT_EXP_TIME
) -> str:
curtime = int(time.time())
payload = {
'iss': self.issuer,
'aud': "Moonraker",
'iat': curtime,
'exp': curtime + int(exp_time.total_seconds()),
'username': username,
'token_type': token_type
}
header = {'kid': jwk_id}
header.update(JWT_HEADER)
jwt_header = base64url_encode(json.dumps(header).encode())
jwt_payload = base64url_encode(json.dumps(payload).encode())
jwt_msg = b".".join([jwt_header, jwt_payload])
sig = private_key.signature(jwt_msg)
jwt_sig = base64url_encode(sig)
return b".".join([jwt_msg, jwt_sig]).decode()
def decode_jwt(
self, token: str, token_type: str = "access"
) -> Dict[str, Any]:
message, sig = token.rsplit('.', maxsplit=1)
enc_header, enc_payload = message.split('.')
header: Dict[str, Any] = json.loads(base64url_decode(enc_header))
sig_bytes = base64url_decode(sig)
# verify header
if header.get('typ') != "JWT" or header.get('alg') != "EdDSA":
raise self.server.error("Invalid JWT header")
jwk_id = header.get('kid')
if jwk_id not in self.public_jwks:
raise self.server.error("Invalid key ID")
# validate signature
public_key = self._public_key_from_jwk(self.public_jwks[jwk_id])
public_key.verify(sig_bytes + message.encode())
# validate claims
payload: Dict[str, Any] = json.loads(base64url_decode(enc_payload))
if payload['token_type'] != token_type:
raise self.server.error(
f"JWT Token type mismatch: Expected {token_type}, "
f"Recd: {payload['token_type']}", 401)
if payload['iss'] != self.issuer:
raise self.server.error("Invalid JWT Issuer", 401)
if payload['aud'] != "Moonraker":
raise self.server.error("Invalid JWT Audience", 401)
if payload['exp'] < int(time.time()):
raise self.server.error("JWT Expired", 401)
# get user
user_info: Optional[Dict[str, Any]] = self.users.get(
payload.get('username', ""), None)
if user_info is None:
raise self.server.error("Unknown user", 401)
return user_info
def validate_jwt(self, token: str) -> Dict[str, Any]:
try:
user_info = self.decode_jwt(token)
except Exception as e:
if isinstance(e, self.server.error):
raise
raise self.server.error(
f"Failed to decode JWT: {e}", 401
) from e
return user_info
def validate_api_key(self, api_key: str) -> Dict[str, Any]:
if not self.enable_api_key:
raise self.server.error("API Key authentication is disabled", 401)
if api_key and api_key == self.api_key:
return self.users[API_USER]
raise self.server.error("Invalid API Key", 401)
def _load_private_key(self, secret: str) -> Signer:
try:
key = Signer(bytes.fromhex(secret))
except Exception:
raise self.server.error(
"Error decoding private key, user data may"
" be corrupt", 500) from None
return key
def _generate_public_jwk(self, private_key: Signer) -> Dict[str, Any]:
public_key = private_key.vk
return {
'x': base64url_encode(public_key).decode(),
'kty': "OKP",
'crv': "Ed25519",
'use': "sig"
}
def _public_key_from_jwk(self, jwk: Dict[str, Any]) -> Verifier:
if jwk.get('kty') != "OKP":
raise self.server.error("Not an Octet Key Pair")
if jwk.get('crv') != "Ed25519":
raise self.server.error("Invalid Curve")
if 'x' not in jwk:
raise self.server.error("No 'x' argument in jwk")
key = base64url_decode(jwk['x'])
return Verifier(key.hex().encode())
def _prune_conn_handler(self, eventtime: float) -> float:
cur_time = time.time()
for ip, user_info in list(self.trusted_users.items()):
exp_time: float = user_info['expires_at']
if cur_time >= exp_time:
self.trusted_users.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
return eventtime + PRUNE_CHECK_TIME
def _oneshot_token_expire_handler(self, token):
self.oneshot_tokens.pop(token, None)
def get_oneshot_token(self,
ip_addr: IPAddr,
user: Optional[Dict[str, Any]]
) -> str:
token = base64.b32encode(os.urandom(20)).decode()
event_loop = self.server.get_event_loop()
hdl = event_loop.delay_callback(
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
self.oneshot_tokens[token] = (ip_addr, user, hdl)
return token
def _check_json_web_token(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
auth_token: Optional[str] = request.headers.get("Authorization")
if auth_token is None:
auth_token = request.headers.get("X-Access-Token")
if auth_token is None:
qtoken = request.query_arguments.get('access_token', None)
if qtoken is not None:
auth_token = qtoken[-1].decode()
elif auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
else:
return None
if auth_token:
try:
return self.decode_jwt(auth_token)
except Exception:
logging.exception(f"JWT Decode Error {auth_token}")
raise HTTPError(401, "JWT Decode Error")
return None
def _check_authorized_ip(self, ip: IPAddr) -> bool:
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
fqdn = socket.getfqdn(str(ip)).lower()
if fqdn in self.trusted_domains:
return True
return False
def _check_trusted_connection(self,
ip: Optional[IPAddr]
) -> Optional[Dict[str, Any]]:
if ip is not None:
curtime = time.time()
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
if ip in self.trusted_users:
self.trusted_users[ip]['expires_at'] = exp_time
return self.trusted_users[ip]
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_users[ip] = {
'username': TRUSTED_USER,
'password': None,
'created_on': curtime,
'expires_at': exp_time
}
return self.trusted_users[ip]
return None
def _check_oneshot_token(self,
token: str,
cur_ip: Optional[IPAddr]
) -> Optional[Dict[str, Any]]:
if token in self.oneshot_tokens:
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
hdl.cancel()
if cur_ip != ip_addr:
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
f", Recd: {cur_ip}")
return None
return user
else:
return None
def check_logins_maxed(self, ip_addr: IPAddr) -> bool:
if self.max_logins is None:
return False
return self.failed_logins.get(ip_addr, 0) >= self.max_logins
def check_authorized(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
if (
request.path in self.permitted_paths
or request.method == "OPTIONS"
):
return None
# Check JSON Web Token
jwt_user = self._check_json_web_token(request)
if jwt_user is not None:
return jwt_user
try:
ip = ipaddress.ip_address(request.remote_ip) # type: ignore
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
# Check oneshot access token
ost: Optional[List[bytes]] = request.arguments.get('token', None)
if ost is not None:
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
if ost_user is not None:
return ost_user
# Check API Key Header
if self.enable_api_key:
key: Optional[str] = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return self.users[API_USER]
# If the force_logins option is enabled and at least one
# user is created this is an unauthorized request
if self.force_logins and len(self.users) > 1:
raise HTTPError(401, "Unauthorized, Force Logins Enabled")
# Check if IP is trusted
trusted_user = self._check_trusted_connection(ip)
if trusted_user is not None:
return trusted_user
raise HTTPError(401, "Unauthorized")
def check_cors(self,
origin: Optional[str],
req_hdlr: Optional[RequestHandler] = None
) -> bool:
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, req_hdlr)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, req_hdlr)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self,
origin: str,
req_hdlr: Optional[RequestHandler]
) -> None:
if req_hdlr is None:
return
req_hdlr.set_header("Access-Control-Allow-Origin", origin)
if req_hdlr.request.method == "OPTIONS":
req_hdlr.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
req_hdlr.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token, Authorization, X-Access-Token, "
"X-Api-Key")
if req_hdlr.request.headers.get(
"Access-Control-Request-Private-Network", None) == "true":
req_hdlr.set_header(
"Access-Control-Allow-Private-Network",
"true")
def cors_enabled(self) -> bool:
return self.cors_domains is not None
def close(self) -> None:
self.prune_timer.stop()
def load_component(config: ConfigHelper) -> Authorization:
return Authorization(config)
+130
View File
@@ -0,0 +1,130 @@
# Support for GPIO Button actions
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .gpio import GpioFactory
from ..app import InternalTransport as ITransport
class ButtonManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.buttons: Dict[str, GpioButton] = {}
prefix_sections = config.get_prefix_sections("button")
logging.info(f"Loading Buttons: {prefix_sections}")
for section in prefix_sections:
cfg = config[section]
# Reserve the "type" option for future use
btn_type = cfg.get('type', "gpio")
try:
btn = GpioButton(cfg)
except Exception as e:
msg = f"Failed to load button [{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
self.buttons[btn.name] = btn
self.server.register_notification("button:button_event")
def component_init(self) -> None:
for btn in self.buttons.values():
btn.initialize()
class GpioButton:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.eventloop = self.server.get_event_loop()
self.name = config.get_name().split()[-1]
self.itransport: ITransport = self.server.lookup_component(
'internal_transport')
self.mutex = asyncio.Lock()
gpio: GpioFactory = self.server.load_component(config, 'gpio')
self.gpio_event = gpio.register_gpio_event(
config.get('pin'), self._on_gpio_event)
min_event_time = config.getfloat(
'minimum_event_time', .05, minval=.010)
self.gpio_event.setup_debounce(min_event_time, self._on_gpio_error)
self.press_template = config.gettemplate(
"on_press", None, is_async=True)
self.release_template = config.gettemplate(
"on_release", None, is_async=True)
if (
self.press_template is None and
self.release_template is None
):
raise config.error(
f"[{config.get_name()}]: No template option configured")
self.notification_sent: bool = False
self.user_data: Dict[str, Any] = {}
self.context: Dict[str, Any] = {
'call_method': self.itransport.call_method,
'send_notification': self._send_notification,
'event': {
'elapsed_time': 0.,
'received_time': 0.,
'render_time': 0.,
'pressed': False,
},
'user_data': self.user_data
}
def initialize(self) -> None:
self.gpio_event.start()
self.context['event']['pressed'] = bool(self.gpio_event.get_value())
def get_status(self) -> Dict[str, Any]:
return {
'name': self.name,
'type': "gpio",
'event': self.context['event'],
}
def _send_notification(self, result: Any = None) -> None:
if self.notification_sent:
# Only allow execution once per template
return
self.notification_sent = True
data = self.get_status()
data['aux'] = result
self.server.send_event("button:button_event", data)
async def _on_gpio_event(self,
eventtime: float,
elapsed_time: float,
pressed: int
) -> None:
template = self.press_template if pressed else self.release_template
if template is None:
return
async with self.mutex:
self.notification_sent = False
event_info: Dict[str, Any] = {
'elapsed_time': elapsed_time,
'received_time': eventtime,
'render_time': self.eventloop.get_loop_time(),
'pressed': bool(pressed)
}
self.context['event'] = event_info
try:
await template.render_async(self.context)
except Exception:
action = "on_press" if pressed else "on_release"
logging.exception(
f"Button {self.name}: '{action}' template error")
def _on_gpio_error(self, message: str) -> None:
self.server.add_warning(f"Button {self.name}: {message}")
def load_component(config: ConfigHelper) -> ButtonManager:
return ButtonManager(config)
+170
View File
@@ -0,0 +1,170 @@
# Klipper data logging and storage storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from collections import deque
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Tuple,
Deque,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI as APIComp
GCQueue = Deque[Dict[str, Any]]
TempStore = Dict[str, Dict[str, Deque[float]]]
TEMP_UPDATE_TIME = 1.
class DataStore:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.temp_store_size = config.getint('temperature_store_size', 1200)
self.gcode_store_size = config.getint('gcode_store_size', 1000)
# Temperature Store Tracking
self.last_temps: Dict[str, Tuple[float, ...]] = {}
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
self.temperature_store: TempStore = {}
eventloop = self.server.get_event_loop()
self.temp_update_timer = eventloop.register_timer(
self._update_temperature_store)
# 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)
self.server.register_event_handler(
"klippy_connection:gcode_received", self._store_gcode_command
)
# Register endpoints
self.server.register_endpoint(
"/server/temperature_store", ['GET'],
self._handle_temp_store_request)
self.server.register_endpoint(
"/server/gcode_store", ['GET'],
self._handle_gcode_store_request)
async def _init_sensors(self) -> None:
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
# Fetch sensors
try:
result: Dict[str, Any]
result = await klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f"Error Configuring Sensors: {e}")
return
sensors: List[str]
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub: Dict[str, Optional[List[str]]] = {s: None for s in sensors}
try:
status: Dict[str, Any]
status = await klippy_apis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to sensors: {e}")
return
logging.info(f"Configuring available sensors: {sensors}")
new_store: TempStore = {}
for sensor in sensors:
fields = list(status.get(sensor, {}).keys())
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=self.temp_store_size)}
for item in ["target", "power", "speed"]:
if item in fields:
new_store[sensor][f"{item}s"] = deque(
maxlen=self.temp_store_size)
if sensor not in self.last_temps:
self.last_temps[sensor] = (0., 0., 0., 0.)
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
if sensor not in self.temperature_store:
del self.last_temps[sensor]
# Update initial temperatures
self._set_current_temps(status)
self.temp_update_timer.start()
else:
logging.info("No sensors found")
self.last_temps = {}
self.temperature_store = {}
self.temp_update_timer.stop()
def _set_current_temps(self, data: Dict[str, Any]) -> None:
for sensor in self.temperature_store:
if sensor in data:
last_val = self.last_temps[sensor]
self.last_temps[sensor] = (
round(data[sensor].get('temperature', last_val[0]), 2),
data[sensor].get('target', last_val[1]),
data[sensor].get('power', last_val[2]),
data[sensor].get('speed', last_val[3]))
def _update_temperature_store(self, eventtime: float) -> float:
# 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)
return eventtime + TEMP_UPDATE_TIME
async def _handle_temp_store_request(self,
web_request: WebRequest
) -> Dict[str, Dict[str, List[float]]]:
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
return store
async def close(self) -> None:
self.temp_update_timer.stop()
def _update_gcode_store(self, response: str) -> None:
curtime = time.time()
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def _store_gcode_command(self, script: str) -> None:
curtime = time.time()
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
self.gcode_queue.append(
{'message': script, 'time': curtime, 'type': "command"})
async def _handle_gcode_store_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
count = web_request.get_int("count", None)
if count is not None:
gc_responses = list(self.gcode_queue)[-count:]
else:
gc_responses = list(self.gcode_queue)
return {'gcode_store': gc_responses}
def load_component(config: ConfigHelper) -> DataStore:
return DataStore(config)
+942
View File
@@ -0,0 +1,942 @@
# Mimimal database for moonraker storage
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import pathlib
import json
import struct
import operator
import logging
from asyncio import Future, Task
from io import BytesIO
from functools import reduce
from threading import Lock as ThreadLock
import lmdb
from ..utils import Sentinel, ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Mapping,
TypeVar,
Tuple,
Optional,
Union,
Dict,
List,
cast
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
DBRecord = Union[int, float, bool, str, List[Any], Dict[str, Any]]
DBType = Optional[DBRecord]
_T = TypeVar("_T")
DATABASE_VERSION = 1
MAX_NAMESPACES = 100
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.loads(bytes(x)),
ord("{"): lambda x: json.loads(bytes(x)),
}
def getitem_with_default(item: Dict, field: Any) -> Any:
if not isinstance(item, Dict):
raise ServerError(
f"Cannot reduce a value of type {type(item)}")
if field not in item:
item[field] = {}
return item[field]
class MoonrakerDatabase:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.eventloop = self.server.get_event_loop()
self.namespaces: Dict[str, object] = {}
self.thread_lock = ThreadLock()
app_args = self.server.get_app_args()
dep_path = config.get("database_path", None, deprecate=True)
db_path = pathlib.Path(app_args["data_path"]).joinpath("database")
if (
app_args["is_default_data_path"] and
not db_path.joinpath("data.mdb").exists()
):
# Allow configured DB fallback
dep_path = dep_path or "~/.moonraker_database"
legacy_db = pathlib.Path(dep_path).expanduser().resolve()
try:
same = legacy_db.samefile(db_path)
except Exception:
same = False
if not same and legacy_db.exists():
logging.info(
f"Reverting to legacy database path: {legacy_db}"
)
db_path = legacy_db
if not db_path.is_dir():
db_path.mkdir()
self.database_path = str(db_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
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
key = bytes(cursor.key())
self.namespaces[key.decode()] = self.lmdb_env.open_db(
key, txn)
remaining = cursor.next()
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)
# Iterate through all records, checking for invalid keys
for ns, db in self.namespaces.items():
with txn.cursor(db=db) as cursor:
remaining = cursor.first()
while remaining:
key_buf = cursor.key()
try:
decoded_key = bytes(key_buf).decode()
except Exception:
logging.info("Database Key Decode Error")
decoded_key = ''
if not decoded_key:
hex_key = bytes(key_buf).hex()
try:
invalid_val = self._decode_value(cursor.value())
except Exception:
invalid_val = ""
logging.info(
f"Invalid Key '{hex_key}' found in namespace "
f"'{ns}', dropping value: {repr(invalid_val)}")
try:
remaining = cursor.delete()
except Exception:
logging.exception("Error Deleting LMDB Key")
else:
continue
remaining = cursor.next()
# Protected Namespaces have read-only API access. Write access can
# be granted by enabling the debug option. Forbidden namespaces
# have no API access. This cannot be overridden.
self.protected_namespaces = set(self.get_item(
"moonraker", "database.protected_namespaces",
["moonraker"]).result())
self.forbidden_namespaces = set(self.get_item(
"moonraker", "database.forbidden_namespaces",
[]).result())
# Initialize Debug Counter
config.getboolean("enable_database_debug", False, deprecate=True)
self.debug_counter: Dict[str, int] = {"get": 0, "post": 0, "delete": 0}
db_counter: Optional[Dict[str, int]] = self.get_item(
"moonraker", "database.debug_counter", None
).result()
if isinstance(db_counter, dict):
self.debug_counter.update(db_counter)
self.server.add_log_rollover_item(
"database_debug_counter",
f"Database Debug Counter: {self.debug_counter}"
)
# Track unsafe shutdowns
unsafe_shutdowns: int = self.get_item(
"moonraker", "database.unsafe_shutdowns", 0).result()
msg = f"Unsafe Shutdown Count: {unsafe_shutdowns}"
self.server.add_log_rollover_item("database", msg)
# Increment unsafe shutdown counter. This will be reset if
# moonraker is safely restarted
self.insert_item("moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns + 1)
self.server.register_endpoint(
"/server/database/list", ['GET'], self._handle_list_request)
self.server.register_endpoint(
"/server/database/item", ["GET", "POST", "DELETE"],
self._handle_item_request)
self.server.register_debug_endpoint(
"/debug/database/list", ['GET'], self._handle_list_request)
self.server.register_debug_endpoint(
"/debug/database/item", ["GET", "POST", "DELETE"],
self._handle_item_request)
def get_database_path(self) -> str:
return self.database_path
def _run_command(self,
command_func: Callable[..., _T],
*args
) -> Future[_T]:
def func_wrapper():
with self.thread_lock:
return command_func(*args)
if self.server.is_running():
return cast(Future, self.eventloop.run_in_thread(func_wrapper))
else:
ret = func_wrapper()
fut = self.eventloop.create_future()
fut.set_result(ret)
return fut
# *** Nested Database operations***
# The insert_item(), delete_item(), and get_item() methods may operate on
# nested objects within a namespace. Each operation takes a key argument
# that may either be a string or a list of strings. If the argument is
# a string nested keys may be delitmted by a "." by which the string
# will be split into a list of strings. The first key in the list must
# identify the database record. Subsequent keys are optional and are
# used to access elements in the deserialized objects.
def insert_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> Future[None]:
return self._run_command(self._insert_impl, namespace, key, value)
def _insert_impl(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
record = value
if len(key_list) > 1:
record = self._get_record(namespace, key_list[0], force=True)
if not isinstance(record, dict):
prev_type = type(record)
record = {}
logging.info(
f"Warning: Key {key_list[0]} contains a value of type "
f"{prev_type}. Overwriting with an object.")
item: Dict[str, Any] = reduce(
getitem_with_default, key_list[1:-1], record)
if not isinstance(item, dict):
rpt_key = ".".join(key_list[:-1])
raise self.server.error(
f"Item at key '{rpt_key}' in namespace '{namespace}'is "
"not a dictionary object, cannot insert"
)
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error inserting key '{key}' in namespace '{namespace}'")
def update_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> Future[None]:
return self._run_command(self._update_impl, namespace, key, value)
def _update_impl(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
record = self._get_record(namespace, key_list[0])
if len(key_list) == 1:
if isinstance(record, dict) and isinstance(value, dict):
record.update(value)
else:
if value is None:
raise self.server.error(
f"Item at key '{key}', namespace '{namespace}': "
"Cannot assign a record level null value")
record = value
else:
try:
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found",
404)
if not isinstance(item, dict) or key_list[-1] not in item:
rpt_key = ".".join(key_list[:-1])
raise self.server.error(
f"Item at key '{rpt_key}' in namespace '{namespace}'is "
"not a dictionary object, cannot update"
)
if isinstance(item[key_list[-1]], dict) \
and isinstance(value, dict):
item[key_list[-1]].update(value)
else:
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error updating key '{key}' in namespace '{namespace}'")
def delete_item(self,
namespace: str,
key: Union[List[str], str],
drop_empty_db: bool = False
) -> Future[Any]:
return self._run_command(self._delete_impl, namespace, key,
drop_empty_db)
def _delete_impl(self,
namespace: str,
key: Union[List[str], str],
drop_empty_db: bool = False
) -> Any:
key_list = self._process_key(key)
val = record = self._get_record(namespace, key_list[0])
remove_record = True
if len(key_list) > 1:
try:
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
val = item.pop(key_list[-1])
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found",
404)
remove_record = False if record else True
if remove_record:
db = self.namespaces[namespace]
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.delete(key_list[0].encode())
with txn.cursor() as 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 "
f"'{namespace}'")
return val
def get_item(self,
namespace: str,
key: Optional[Union[List[str], str]] = None,
default: Any = Sentinel.MISSING
) -> Future[Any]:
return self._run_command(self._get_impl, namespace, key, default)
def _get_impl(self,
namespace: str,
key: Optional[Union[List[str], str]] = None,
default: Any = Sentinel.MISSING
) -> Any:
try:
if key is None:
return self._get_namespace(namespace)
key_list = self._process_key(key)
ns = self._get_record(namespace, key_list[0])
val = reduce(operator.getitem, # type: ignore
key_list[1:], ns)
except Exception as e:
if default is not Sentinel.MISSING:
return default
if isinstance(e, self.server.error):
raise
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return val
# *** Batch operations***
# The insert_batch(), move_batch(), delete_batch(), and get_batch()
# methods can be used to perform record level batch operations on
# a namespace in a single transaction.
def insert_batch(self,
namespace: str,
records: Dict[str, Any]
) -> Future[None]:
return self._run_command(self._insert_batch_impl, namespace, records)
def _insert_batch_impl(self,
namespace: str,
records: Dict[str, Any]
) -> None:
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
db = self.namespaces[namespace]
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
for key, val in records.items():
ret = txn.put(key.encode(), self._encode_value(val))
if not ret:
logging.info(f"Error inserting record {key} into "
f"namespace {namespace}")
def move_batch(self,
namespace: str,
source_keys: List[str],
dest_keys: List[str]
) -> Future[None]:
return self._run_command(self._move_batch_impl, namespace,
source_keys, dest_keys)
def _move_batch_impl(self,
namespace: str,
source_keys: List[str],
dest_keys: List[str]
) -> None:
db = self._get_db(namespace)
if len(source_keys) != len(dest_keys):
raise self.server.error(
"Source key list and destination key list must "
"be of the same length")
with self.lmdb_env.begin(write=True, db=db) as txn:
for source, dest in zip(source_keys, dest_keys):
val = txn.pop(source.encode())
if val is not None:
txn.put(dest.encode(), val)
def delete_batch(self,
namespace: str,
keys: List[str]
) -> Future[Dict[str, Any]]:
return self._run_command(self._del_batch_impl, namespace, keys)
def _del_batch_impl(self,
namespace: str,
keys: List[str]
) -> Dict[str, Any]:
db = self._get_db(namespace)
result: Dict[str, Any] = {}
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
for key in keys:
val = txn.pop(key.encode())
if val is not None:
result[key] = self._decode_value(val)
return result
def get_batch(self,
namespace: str,
keys: List[str]
) -> Future[Dict[str, Any]]:
return self._run_command(self._get_batch_impl, namespace, keys)
def _get_batch_impl(self,
namespace: str,
keys: List[str]
) -> Dict[str, Any]:
db = self._get_db(namespace)
result: Dict[str, Any] = {}
encoded_keys: List[bytes] = [k.encode() for k in keys]
with self.lmdb_env.begin(buffers=True, db=db) as txn:
with txn.cursor() as cursor:
vals = cursor.getmulti(encoded_keys)
result = {bytes(k).decode(): self._decode_value(v)
for k, v in vals}
return result
# *** Namespace level operations***
def update_namespace(self,
namespace: str,
value: Mapping[str, DBRecord]
) -> Future[None]:
return self._run_command(self._update_ns_impl, namespace, value)
def _update_ns_impl(self,
namespace: str,
value: Mapping[str, DBRecord]
) -> None:
if not value:
return
db = self._get_db(namespace)
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
# We only need to update the keys that changed
for key, val in value.items():
stored = txn.get(key.encode())
if stored is not None:
decoded = self._decode_value(stored)
if val == decoded:
continue
ret = txn.put(key.encode(), self._encode_value(val))
if not ret:
logging.info(f"Error inserting key '{key}' "
f"in namespace '{namespace}'")
def clear_namespace(self,
namespace: str,
drop_empty_db: bool = False
) -> Future[None]:
return self._run_command(self._clear_ns_impl, namespace, drop_empty_db)
def _clear_ns_impl(self,
namespace: str,
drop_empty_db: bool = False
) -> None:
db = self._get_db(namespace)
with self.lmdb_env.begin(write=True, db=db) as txn:
txn.drop(db, delete=drop_empty_db)
if drop_empty_db:
del self.namespaces[namespace]
def sync_namespace(self,
namespace: str,
value: Mapping[str, DBRecord]
) -> Future[None]:
return self._run_command(self._sync_ns_impl, namespace, value)
def _sync_ns_impl(self,
namespace: str,
value: Mapping[str, DBRecord]
) -> None:
if not value:
raise self.server.error("Cannot sync to an empty value")
db = self._get_db(namespace)
new_keys = set(value.keys())
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
bkey, bval = cursor.item()
key = bytes(bkey).decode()
if key not in value:
remaining = cursor.delete()
else:
decoded = self._decode_value(bval)
if decoded != value[key]:
new_val = self._encode_value(value[key])
txn.put(key.encode(), new_val)
new_keys.remove(key)
remaining = cursor.next()
for key in new_keys:
val = value[key]
ret = txn.put(key.encode(), self._encode_value(val))
if not ret:
logging.info(f"Error inserting key '{key}' "
f"in namespace '{namespace}'")
def ns_length(self, namespace: str) -> Future[int]:
return self._run_command(self._ns_length_impl, namespace)
def _ns_length_impl(self, namespace: str) -> int:
db = self._get_db(namespace)
with self.lmdb_env.begin(db=db) as txn:
stats = txn.stat(db)
return stats['entries']
def ns_keys(self, namespace: str) -> Future[List[str]]:
return self._run_command(self._ns_keys_impl, namespace)
def _ns_keys_impl(self, namespace: str) -> List[str]:
keys: List[str] = []
db = self._get_db(namespace)
with self.lmdb_env.begin(db=db) as txn:
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
keys.append(cursor.key().decode())
remaining = cursor.next()
return keys
def ns_values(self, namespace: str) -> Future[List[Any]]:
return self._run_command(self._ns_values_impl, namespace)
def _ns_values_impl(self, namespace: str) -> List[Any]:
values: List[Any] = []
db = self._get_db(namespace)
with self.lmdb_env.begin(db=db, buffers=True) as txn:
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
values.append(self._decode_value(cursor.value()))
remaining = cursor.next()
return values
def ns_items(self, namespace: str) -> Future[List[Tuple[str, Any]]]:
return self._run_command(self._ns_items_impl, namespace)
def _ns_items_impl(self, namespace: str) -> List[Tuple[str, Any]]:
ns = self._get_namespace(namespace)
return list(ns.items())
def ns_contains(self,
namespace: str,
key: Union[List[str], str]
) -> Future[bool]:
return self._run_command(self._ns_contains_impl, namespace, key)
def _ns_contains_impl(self,
namespace: str,
key: Union[List[str], str]
) -> bool:
self._get_db(namespace)
try:
key_list = self._process_key(key)
record = self._get_record(namespace, key_list[0])
if len(key_list) == 1:
return True
reduce(operator.getitem, # type: ignore
key_list[1:], record)
except Exception:
return False
return True
def register_local_namespace(self,
namespace: str,
forbidden: bool = False
) -> None:
if self.server.is_running():
raise self.server.error(
"Cannot register a namespace while the "
"server is running")
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
if forbidden:
if namespace not in self.forbidden_namespaces:
self.forbidden_namespaces.add(namespace)
self.insert_item(
"moonraker", "database.forbidden_namespaces",
list(self.forbidden_namespaces))
elif namespace not in self.protected_namespaces:
self.protected_namespaces.add(namespace)
self.insert_item("moonraker", "database.protected_namespaces",
sorted(self.protected_namespaces))
def wrap_namespace(self,
namespace: str,
parse_keys: bool = True
) -> NamespaceWrapper:
if self.server.is_running():
raise self.server.error(
"Cannot wrap a namespace while the "
"server is running")
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
return NamespaceWrapper(namespace, self, parse_keys)
def _get_db(self, namespace: str) -> object:
if namespace not in self.namespaces:
raise self.server.error(f"Namespace '{namespace}' not found", 404)
return self.namespaces[namespace]
def _process_key(self, key: Union[List[str], str]) -> List[str]:
try:
key_list = key if isinstance(key, list) else key.split('.')
except Exception:
key_list = []
if not key_list or "" in key_list:
raise self.server.error(f"Invalid Key Format: '{key}'")
return key_list
def _insert_record(self, namespace: str, key: str, val: DBType) -> bool:
db = self._get_db(namespace)
if val is None:
return False
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.put(key.encode(), self._encode_value(val))
return ret
def _get_record(self,
namespace: str,
key: str,
force: bool = False
) -> DBRecord:
db = self._get_db(namespace)
with self.lmdb_env.begin(buffers=True, db=db) as txn:
value = txn.get(key.encode())
if value is None:
if force:
return {}
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return self._decode_value(value)
def _get_namespace(self, namespace: str) -> Dict[str, Any]:
db = self._get_db(namespace)
result = {}
invalid_key_result = None
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
with txn.cursor() as cursor:
has_remaining = cursor.first()
while has_remaining:
db_key, value = cursor.item()
k = bytes(db_key).decode()
if not k:
invalid_key_result = self._decode_value(value)
logging.info(
f"Invalid Key '{db_key}' found in namespace "
f"'{namespace}', dropping value: "
f"{repr(invalid_key_result)}")
try:
has_remaining = cursor.delete()
except Exception:
logging.exception("Error Deleting LMDB Key")
has_remaining = cursor.next()
else:
result[k] = self._decode_value(value)
has_remaining = cursor.next()
return result
def _encode_value(self, value: DBRecord) -> bytes:
try:
enc_func = RECORD_ENCODE_FUNCS[type(value)]
return enc_func(value)
except Exception:
raise self.server.error(
f"Error encoding val: {value}, type: {type(value)}")
def _decode_value(self, bvalue: Union[bytes, memoryview]) -> DBRecord:
fmt = bvalue[0]
try:
decode_func = RECORD_DECODE_FUNCS[fmt]
return decode_func(bvalue)
except Exception:
val = bytes(bvalue).decode()
raise self.server.error(
f"Error decoding value {val}, format: {chr(fmt)}")
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[str]]:
path = web_request.get_endpoint()
await self.eventloop.run_in_thread(self.thread_lock.acquire)
try:
ns_list = set(self.namespaces.keys())
if not path.startswith("/debug/"):
ns_list -= self.forbidden_namespaces
finally:
self.thread_lock.release()
return {'namespaces': list(ns_list)}
async def _handle_item_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
is_debug = web_request.get_endpoint().startswith("/debug/")
namespace = web_request.get_str("namespace")
if namespace in self.forbidden_namespaces and not is_debug:
raise self.server.error(
f"Read/Write access to namespace '{namespace}'"
" is forbidden", 403)
key: Any
valid_types: Tuple[type, ...]
if action != "GET":
if namespace in self.protected_namespaces and not is_debug:
raise self.server.error(
f"Write access to namespace '{namespace}'"
" is forbidden", 403)
key = web_request.get("key")
valid_types = (list, str)
else:
key = web_request.get("key", None)
valid_types = (list, str, type(None))
if not isinstance(key, valid_types):
raise self.server.error(
"Value for argument 'key' is an invalid type: "
f"{type(key).__name__}")
if action == "GET":
val = await self.get_item(namespace, key)
elif action == "POST":
val = web_request.get("value")
await self.insert_item(namespace, key, val)
elif action == "DELETE":
val = await self.delete_item(namespace, key, drop_empty_db=True)
if is_debug:
self.debug_counter[action.lower()] += 1
await self.insert_item(
"moonraker", "database.debug_counter", self.debug_counter
)
self.server.add_log_rollover_item(
"database_debug_counter",
f"Database Debug Counter: {self.debug_counter}",
log=False
)
return {'namespace': namespace, 'key': key, 'value': val}
async def close(self) -> None:
# Decrement unsafe shutdown counter
unsafe_shutdowns: int = await self.get_item(
"moonraker", "database.unsafe_shutdowns", 0)
await self.insert_item(
"moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns - 1)
await self.eventloop.run_in_thread(self.thread_lock.acquire)
try:
# 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()
finally:
self.thread_lock.release()
class NamespaceWrapper:
def __init__(self,
namespace: str,
database: MoonrakerDatabase,
parse_keys: bool
) -> None:
self.namespace = namespace
self.db = database
self.eventloop = database.eventloop
self.server = database.server
# If parse keys is true, keys of a string type
# will be passed straight to the DB methods.
self.parse_keys = parse_keys
def insert(self,
key: Union[List[str], str],
value: DBType
) -> Awaitable[None]:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.insert_item(self.namespace, key, value)
def update_child(self,
key: Union[List[str], str],
value: DBType
) -> Awaitable[None]:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.update_item(self.namespace, key, value)
def update(self, value: Mapping[str, DBRecord]) -> Awaitable[None]:
return self.db.update_namespace(self.namespace, value)
def sync(self, value: Mapping[str, DBRecord]) -> Awaitable[None]:
return self.db.sync_namespace(self.namespace, value)
def get(self,
key: Union[List[str], str],
default: Any = None
) -> Future[Any]:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.get_item(self.namespace, key, default)
def delete(self, key: Union[List[str], str]) -> Future[Any]:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.delete_item(self.namespace, key)
def insert_batch(self, records: Dict[str, Any]) -> Future[None]:
return self.db.insert_batch(self.namespace, records)
def move_batch(self,
source_keys: List[str],
dest_keys: List[str]
) -> Future[None]:
return self.db.move_batch(self.namespace, source_keys, dest_keys)
def delete_batch(self, keys: List[str]) -> Future[Dict[str, Any]]:
return self.db.delete_batch(self.namespace, keys)
def get_batch(self, keys: List[str]) -> Future[Dict[str, Any]]:
return self.db.get_batch(self.namespace, keys)
def length(self) -> Future[int]:
return self.db.ns_length(self.namespace)
def as_dict(self) -> Dict[str, Any]:
self._check_sync_method("as_dict")
return self.db._get_namespace(self.namespace)
def __getitem__(self, key: Union[List[str], str]) -> Future[Any]:
return self.get(key, default=Sentinel.MISSING)
def __setitem__(self,
key: Union[List[str], str],
value: DBType
) -> None:
self.insert(key, value)
def __delitem__(self, key: Union[List[str], str]):
self.delete(key)
def __contains__(self, key: Union[List[str], str]) -> bool:
self._check_sync_method("__contains__")
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key).result()
def contains(self, key: Union[List[str], str]) -> Future[bool]:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key)
def keys(self) -> Future[List[str]]:
return self.db.ns_keys(self.namespace)
def values(self) -> Future[List[Any]]:
return self.db.ns_values(self.namespace)
def items(self) -> Future[List[Tuple[str, Any]]]:
return self.db.ns_items(self.namespace)
def pop(self,
key: Union[List[str], str],
default: Any = Sentinel.MISSING
) -> Union[Future[Any], Task[Any]]:
if not self.server.is_running():
try:
val = self.delete(key).result()
except Exception:
if default is Sentinel.MISSING:
raise
val = default
fut = self.eventloop.create_future()
fut.set_result(val)
return fut
async def _do_pop() -> Any:
try:
val = await self.delete(key)
except Exception:
if default is Sentinel.MISSING:
raise
val = default
return val
return self.eventloop.create_task(_do_pop())
def clear(self) -> Awaitable[None]:
return self.db.clear_namespace(self.namespace)
def _check_sync_method(self, func_name: str) -> None:
if self.server.is_running():
raise self.server.error(
f"Cannot call method {func_name} while "
"the eventloop is running")
def load_component(config: ConfigHelper) -> MoonrakerDatabase:
return MoonrakerDatabase(config)
+136
View File
@@ -0,0 +1,136 @@
# DBus Connection Management
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import logging
import dbus_next
from dbus_next.aio import MessageBus, ProxyInterface
from dbus_next.constants import BusType
# Annotation imports
from typing import (
TYPE_CHECKING,
List,
Optional,
Any,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
STAT_PATH = "/proc/self/stat"
DOC_URL = (
"https://moonraker.readthedocs.io/en/latest/"
"installation/#policykit-permissions"
)
class DbusManager:
Variant = dbus_next.Variant
DbusError = dbus_next.errors.DBusError
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.bus: Optional[MessageBus] = None
self.polkit: Optional[ProxyInterface] = None
self.warned: bool = False
st_path = pathlib.Path(STAT_PATH)
self.polkit_subject: List[Any] = []
if not st_path.is_file():
return
proc_data = st_path.read_text()
start_clk_ticks = int(proc_data.split()[21])
self.polkit_subject = [
"unix-process",
{
"pid": dbus_next.Variant("u", os.getpid()),
"start-time": dbus_next.Variant("t", start_clk_ticks)
}
]
def is_connected(self) -> bool:
return self.bus is not None and self.bus.connected
async def component_init(self) -> None:
try:
self.bus = MessageBus(bus_type=BusType.SYSTEM)
await self.bus.connect()
except Exception:
logging.info("Unable to Connect to D-Bus")
return
# Make sure that all required actions are register
try:
self.polkit = await self.get_interface(
"org.freedesktop.PolicyKit1",
"/org/freedesktop/PolicyKit1/Authority",
"org.freedesktop.PolicyKit1.Authority")
except self.DbusError:
self.server.add_warning(
"Unable to find DBus PolKit Interface, this suggests PolKit "
"is not installed on your OS.")
async def check_permission(self,
action: str,
err_msg: str = ""
) -> bool:
if self.polkit is None:
return False
try:
ret = await self.polkit.call_check_authorization( # type: ignore
self.polkit_subject, action, {}, 0, "")
except Exception as e:
self._check_warned()
self.server.add_warning(
f"Error checking authorization for action [{action}]: {e}. "
"This suggests that a dependency is not installed or "
f"up to date. {err_msg}.")
return False
if not ret[0]:
self._check_warned()
self.server.add_warning(
"Moonraker not authorized for PolicyKit action: "
f"[{action}], {err_msg}")
return ret[0]
def _check_warned(self):
if not self.warned:
self.server.add_warning(
f"PolKit warnings detected. See {DOC_URL} for instructions "
"on how to resolve.")
self.warned = True
async def get_interface(self,
bus_name: str,
bus_path: str,
interface_name: str
) -> ProxyInterface:
ret = await self.get_interfaces(bus_name, bus_path,
[interface_name])
return ret[0]
async def get_interfaces(self,
bus_name: str,
bus_path: str,
interface_names: List[str]
) -> List[ProxyInterface]:
if self.bus is None:
raise self.server.error("Bus not avaialable")
interfaces: List[ProxyInterface] = []
introspection = await self.bus.introspect(bus_name, bus_path)
proxy_obj = self.bus.get_proxy_object(bus_name, bus_path,
introspection)
for ifname in interface_names:
intf = proxy_obj.get_interface(ifname)
interfaces.append(intf)
return interfaces
async def close(self):
if self.bus is not None and self.bus.connected:
self.bus.disconnect()
await self.bus.wait_for_disconnect()
def load_component(config: ConfigHelper) -> DbusManager:
return DbusManager(config)
+237
View File
@@ -0,0 +1,237 @@
# Moonraker extension management
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import pathlib
import logging
import json
from ..websockets import BaseSocketClient
from ..utils import get_unix_peer_credentials
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Union,
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from ..klippy_connection import KlippyConnection as Klippy
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
class ExtensionManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.agents: Dict[str, BaseSocketClient] = {}
self.uds_server: Optional[asyncio.AbstractServer] = None
self.server.register_endpoint(
"/connection/send_event", ["POST"], self._handle_agent_event,
transports=["websocket"]
)
self.server.register_endpoint(
"/server/extensions/list", ["GET"], self._handle_list_extensions
)
self.server.register_endpoint(
"/server/extensions/request", ["POST"], self._handle_call_agent
)
def register_agent(self, connection: BaseSocketClient) -> None:
data = connection.client_data
name = data["name"]
client_type = data["type"]
if client_type != "agent":
raise self.server.error(
f"Cannot register client type '{client_type}' as an agent"
)
if name in self.agents:
raise self.server.error(
f"Agent '{name}' already registered and connected'"
)
self.agents[name] = connection
data = connection.client_data
evt: Dict[str, Any] = {
"agent": name, "event": "connected", "data": data
}
connection.send_notification("agent_event", [evt])
def remove_agent(self, connection: BaseSocketClient) -> None:
name = connection.client_data["name"]
if name in self.agents:
del self.agents[name]
evt: Dict[str, Any] = {"agent": name, "event": "disconnected"}
connection.send_notification("agent_event", [evt])
async def _handle_agent_event(self, web_request: WebRequest) -> str:
conn = web_request.get_client_connection()
if conn is None:
raise self.server.error("No connection detected")
if conn.client_data["type"] != "agent":
raise self.server.error(
"Only connections of the 'agent' type can send events"
)
name = conn.client_data["name"]
evt_name = web_request.get_str("event")
if evt_name in ["connected", "disconnected"]:
raise self.server.error(f"Event '{evt_name}' is reserved")
data: Optional[Union[List, Dict[str, Any]]]
data = web_request.get("data", None)
evt: Dict[str, Any] = {"agent": name, "event": evt_name}
if data is not None:
evt["data"] = data
conn.send_notification("agent_event", [evt])
return "ok"
async def _handle_list_extensions(
self, web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
agents: List[Dict[str, Any]]
agents = [agt.client_data for agt in self.agents.values()]
return {"agents": agents}
async def _handle_call_agent(self, web_request: WebRequest) -> Any:
agent = web_request.get_str("agent")
method: str = web_request.get_str("method")
args: Optional[Union[List, Dict[str, Any]]]
args = web_request.get("arguments", None)
if args is not None and not isinstance(args, (list, dict)):
raise self.server.error(
"The 'arguments' field must contain an object or a list"
)
if agent not in self.agents:
raise self.server.error(f"Agent {agent} not connected")
conn = self.agents[agent]
return await conn.call_method(method, args)
async def start_unix_server(self) -> None:
data_path = pathlib.Path(self.server.get_app_args()["data_path"])
comms_path = data_path.joinpath("comms")
if not comms_path.exists():
comms_path.mkdir()
sock_path = comms_path.joinpath("moonraker.sock")
logging.info(f"Creating Unix Domain Socket at '{sock_path}'")
self.uds_server = await asyncio.start_unix_server(
self.on_unix_socket_connected, sock_path, limit=UNIX_BUFFER_LIMIT
)
def on_unix_socket_connected(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
peercred = get_unix_peer_credentials(writer, "Unix Client Connection")
UnixSocketClient(self.server, reader, writer, peercred)
async def close(self) -> None:
if self.uds_server is not None:
self.uds_server.close()
await self.uds_server.wait_closed()
self.uds_server = None
class UnixSocketClient(BaseSocketClient):
def __init__(
self,
server: Server,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
peercred: Dict[str, int]
) -> None:
self.on_create(server)
self.writer = writer
self._peer_cred = peercred
self._connected_time = self.eventloop.get_loop_time()
pid = self._peer_cred.get("process_id")
uid = self._peer_cred.get("user_id")
gid = self._peer_cred.get("group_id")
self.wsm.add_client(self)
logging.info(
f"Unix Socket Opened - Client ID: {self.uid}, "
f"Process ID: {pid}, User ID: {uid}, Group ID: {gid}"
)
self.eventloop.register_callback(self._read_messages, reader)
async def _read_messages(self, reader: asyncio.StreamReader) -> None:
errors_remaining: int = 10
while not reader.at_eof():
try:
data = await reader.readuntil(b'\x03')
decoded = data[:-1].decode(encoding="utf-8")
except (ConnectionError, asyncio.IncompleteReadError):
break
except asyncio.CancelledError:
logging.exception("Unix Client Stream Read Cancelled")
raise
except Exception:
logging.exception("Unix Client Stream Read Error")
errors_remaining -= 1
if not errors_remaining or self.is_closed:
break
continue
errors_remaining = 10
self.eventloop.register_callback(self._process_message, decoded)
logging.debug("Unix Socket Disconnection From _read_messages()")
await self._on_close(reason="Read Exit")
async def write_to_socket(
self, message: Union[str, Dict[str, Any]]
) -> None:
if isinstance(message, dict):
data = json.dumps(message).encode() + b"\x03"
else:
data = message.encode() + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
raise
except Exception:
logging.debug("Unix Socket Disconnection From write_to_socket()")
await self._on_close(reason="Write Exception")
async def _on_close(
self,
code: Optional[int] = None,
reason: Optional[str] = None
) -> None:
if self.is_closed:
return
self.is_closed = True
kconn: Klippy = self.server.lookup_component("klippy_connection")
kconn.remove_subscription(self)
if not self.writer.is_closing():
self.writer.close()
try:
await self.writer.wait_closed()
except Exception:
pass
self.message_buf = []
for resp in self.pending_responses.values():
resp.set_exception(
self.server.error("Client Socket Disconnected", 500)
)
self.pending_responses = {}
logging.info(
f"Unix Socket Closed: ID: {self.uid}, "
f"Close Code: {code}, "
f"Close Reason: {reason}"
)
if self._client_data["type"] == "agent":
extensions: ExtensionManager
extensions = self.server.lookup_component("extensions")
extensions.remove_agent(self)
self.wsm.remove_client(self)
def close_socket(self, code: int, reason: str) -> None:
if not self.is_closed:
self.eventloop.register_callback(self._on_close, code, reason)
def load_component(config: ConfigHelper) -> ExtensionManager:
return ExtensionManager(config)
@@ -0,0 +1,15 @@
# Package definition for the file_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import file_manager as fm
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> fm.FileManager:
return fm.load_component(config)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+285
View File
@@ -0,0 +1,285 @@
# GPIO Factory helper
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
from ..utils import load_system_module
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..eventloop import EventLoop
GPIO_CALLBACK = Callable[[float, float, int], Optional[Awaitable[None]]]
class GpioFactory:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.gpiod: Any = load_system_module("gpiod")
GpioEvent.init_constants(self.gpiod)
self.chips: Dict[str, Any] = {}
self.reserved_gpios: Dict[str, GpioBase] = {}
version: str = self.gpiod.version_string()
self.gpiod_version = tuple(int(v) for v in version.split('.'))
self.server.add_log_rollover_item(
"gpiod_version", f"libgpiod version: {version}")
def _get_gpio_chip(self, chip_name) -> Any:
if chip_name in self.chips:
return self.chips[chip_name]
chip = self.gpiod.Chip(chip_name, self.gpiod.Chip.OPEN_BY_NAME)
self.chips[chip_name] = chip
return chip
def setup_gpio_out(self,
pin_name: str,
initial_value: int = 0
) -> GpioOutputPin:
initial_value = int(not not initial_value)
pparams = self._parse_pin(pin_name)
pparams['initial_value'] = initial_value
line = self._request_gpio(pparams)
try:
gpio_out = GpioOutputPin(line, pparams)
except Exception:
logging.exception("Error Instantiating GpioOutputPin")
line.release()
raise
full_name = pparams['full_name']
self.reserved_gpios[full_name] = gpio_out
return gpio_out
def register_gpio_event(self,
pin_name: str,
callback: GPIO_CALLBACK
) -> GpioEvent:
pin_params = self._parse_pin(pin_name, type="event")
line = self._request_gpio(pin_params)
event_loop = self.server.get_event_loop()
try:
gpio_event = GpioEvent(event_loop, line, pin_params, callback)
except Exception:
logging.exception("Error Instantiating GpioEvent")
line.release()
raise
full_name = pin_params['full_name']
self.reserved_gpios[full_name] = gpio_event
return gpio_event
def _request_gpio(self, pin_params: Dict[str, Any]) -> Any:
full_name = pin_params['full_name']
if full_name in self.reserved_gpios:
raise self.server.error(f"GPIO {full_name} already reserved")
try:
chip = self._get_gpio_chip(pin_params['chip_id'])
line = chip.get_line(pin_params['pin_id'])
args: Dict[str, Any] = {
'consumer': "moonraker",
'type': pin_params['request_type']
}
if 'flags' in pin_params:
args['flags'] = pin_params['flags']
if 'initial_value' in pin_params:
if self.gpiod_version < (1, 3):
args['default_vals'] = [pin_params['initial_value']]
else:
args['default_val'] = pin_params['initial_value']
line.request(**args)
except Exception:
logging.exception(
f"Unable to init {full_name}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise
return line
def _parse_pin(self,
pin_name: str,
type: str = "out"
) -> Dict[str, Any]:
params: Dict[str, Any] = {
'orig': pin_name,
'invert': False,
}
pin = pin_name
if type == "event":
params['request_type'] = self.gpiod.LINE_REQ_EV_BOTH_EDGES
flag: str = "disable"
if pin[0] == "^":
pin = pin[1:]
flag = "pullup"
elif pin[0] == "~":
pin = pin[1:]
flag = "pulldown"
if self.gpiod_version >= (1, 5):
flag_to_enum = {
"disable": self.gpiod.LINE_REQ_FLAG_BIAS_DISABLE,
"pullup": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_UP,
"pulldown": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_DOWN
}
params['flags'] = flag_to_enum[flag]
elif flag != "disable":
raise self.server.error(
f"Flag {flag} configured for event GPIO '{pin_name}'"
" requires libgpiod version 1.5 or later. "
f"Current Version: {self.gpiod.version_string()}")
elif type == "out":
params['request_type'] = self.gpiod.LINE_REQ_DIR_OUT
if pin[0] == "!":
pin = pin[1:]
params['invert'] = True
if 'flags' in params:
params['flags'] |= self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
else:
params['flags'] = self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
chip_id: str = "gpiochip0"
pin_parts = pin.split("/")
if len(pin_parts) == 2:
chip_id, pin = pin_parts
elif len(pin_parts) == 1:
pin = pin_parts[0]
# Verify pin
if not chip_id.startswith("gpiochip") or \
not chip_id[-1].isdigit() or \
not pin.startswith("gpio") or \
not pin[4:].isdigit():
raise self.server.error(
f"Invalid Gpio Pin: {pin_name}")
pin_id = int(pin[4:])
params['pin_id'] = pin_id
params['chip_id'] = chip_id
params['full_name'] = f"{chip_id}:{pin}"
return params
def close(self) -> None:
for line in self.reserved_gpios.values():
line.release()
for chip in self.chips.values():
chip.close()
class GpioBase:
def __init__(self,
line: Any,
pin_params: Dict[str, Any]
) -> None:
self.orig: str = pin_params['orig']
self.name: str = pin_params['full_name']
self.inverted: bool = pin_params['invert']
self.line: Any = line
self.value: int = pin_params.get('initial_value', 0)
def release(self) -> None:
self.line.release()
def is_inverted(self) -> bool:
return self.inverted
def get_value(self) -> int:
return self.value
def get_name(self) -> str:
return self.name
def __str__(self) -> str:
return self.orig
class GpioOutputPin(GpioBase):
def write(self, value: int) -> None:
self.value = int(not not value)
self.line.set_value(self.value)
MAX_ERRORS = 50
ERROR_RESET_TIME = 5.
class GpioEvent(GpioBase):
EVENT_FALLING_EDGE = 0
EVENT_RISING_EDGE = 1
def __init__(self,
event_loop: EventLoop,
line: Any,
pin_params: Dict[str, Any],
callback: GPIO_CALLBACK
) -> None:
super().__init__(line, pin_params)
self.event_loop = event_loop
self.fd = line.event_get_fd()
self.callback = callback
self.on_error: Optional[Callable[[str], None]] = None
self.min_evt_time = 0.
self.last_event_time = 0.
self.error_count = 0
self.last_error_reset = 0.
self.started = False
@classmethod
def init_constants(cls, gpiod: Any) -> None:
cls.EVENT_RISING_EDGE = gpiod.LineEvent.RISING_EDGE
cls.EVENT_FALLING_EDGE = gpiod.LineEvent.FALLING_EDGE
def setup_debounce(self,
min_evt_time: float,
err_callback: Optional[Callable[[str], None]]
) -> None:
self.min_evt_time = max(min_evt_time, 0.)
self.on_error = err_callback
def start(self) -> None:
if not self.started:
self.value = self.line.get_value()
self.last_event_time = self.event_loop.get_loop_time()
self.event_loop.add_reader(self.fd, self._on_event_trigger)
self.started = True
logging.debug(f"GPIO {self.name}: Listening for events, "
f"current state: {self.value}")
def stop(self) -> None:
if self.started:
self.event_loop.remove_reader(self.fd)
self.started = False
def release(self) -> None:
self.stop()
self.line.release()
def _on_event_trigger(self) -> None:
evt = self.line.event_read()
last_val = self.value
if evt.type == self.EVENT_RISING_EDGE:
self.value = 1
elif evt.type == self.EVENT_FALLING_EDGE:
self.value = 0
eventtime = self.event_loop.get_loop_time()
evt_duration = eventtime - self.last_event_time
if last_val == self.value or evt_duration < self.min_evt_time:
self._increment_error(eventtime)
return
self.last_event_time = eventtime
self.error_count = 0
ret = self.callback(eventtime, evt_duration, self.value)
if ret is not None:
self.event_loop.create_task(ret) # type: ignore
def _increment_error(self, eventtime: float) -> None:
if eventtime - self.last_error_reset > ERROR_RESET_TIME:
self.error_count = 0
self.last_error_reset = eventtime
self.error_count += 1
if self.error_count >= MAX_ERRORS:
self.stop()
if self.on_error is not None:
self.on_error("Too Many Consecutive Errors, "
f"GPIO Event Disabled on {self.name}")
def load_component(config: ConfigHelper) -> GpioFactory:
return GpioFactory(config)
+401
View File
@@ -0,0 +1,401 @@
# History cache for printer jobs
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import time
import logging
from asyncio import Lock
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .database import MoonrakerDatabase as DBComp
from .job_state import JobState
from .file_manager.file_manager import FileManager
HIST_NAMESPACE = "history"
MAX_JOBS = 10000
class History:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.file_manager: FileManager = self.server.lookup_component(
'file_manager')
self.request_lock = Lock()
database: DBComp = self.server.lookup_component("database")
self.job_totals: Dict[str, float] = database.get_item(
"moonraker", "history.job_totals",
{
'total_jobs': 0,
'total_time': 0.,
'total_print_time': 0.,
'total_filament_used': 0.,
'longest_job': 0.,
'longest_print': 0.
}).result()
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_event_handler(
"job_state:started", self._on_job_started)
self.server.register_event_handler(
"job_state:complete", self._on_job_complete)
self.server.register_event_handler(
"job_state:cancelled", self._on_job_cancelled)
self.server.register_event_handler(
"job_state:standby", self._on_job_standby)
self.server.register_event_handler(
"job_state:error", self._on_job_error)
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)
self.server.register_endpoint(
"/server/history/reset_totals", ['POST'],
self._handle_job_total_reset)
database.register_local_namespace(HIST_NAMESPACE)
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
parse_keys=False)
self.current_job: Optional[PrinterJob] = None
self.current_job_id: Optional[str] = None
self.next_job_id: int = 0
self.cached_job_ids = self.history_ns.keys().result()
if self.cached_job_ids:
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
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 = await self.history_ns[job_id]
return {"job": self._prep_requested_job(job, job_id)}
if action == "DELETE":
all = web_request.get_boolean("all", False)
if all:
deljobs = self.cached_job_ids
self.history_ns.clear()
self.cached_job_ids = []
self.next_job_id = 0
return {'deleted_jobs': deljobs}
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
self.delete_job(job_id)
return {'deleted_jobs': [job_id]}
raise self.server.error("Invalid Request Method")
async def _handle_jobs_list(self,
web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
i = 0
count = 0
end_num = len(self.cached_job_ids)
jobs: List[Dict[str, Any]] = []
start_num = 0
before = web_request.get_float("before", -1)
since = web_request.get_float("since", -1)
limit = web_request.get_int("limit", 50)
start = web_request.get_int("start", 0)
order = web_request.get_str("order", "desc")
if order not in ["asc", "desc"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
reverse_order = (order == "desc")
# cached jobs is asc order, find lower and upper boundary
if since != -1:
while start_num < end_num:
job_id = self.cached_job_ids[start_num]
job: Dict[str, Any] = await self.history_ns[job_id]
if job['start_time'] > since:
break
start_num += 1
if before != -1:
while end_num > 0:
job_id = self.cached_job_ids[end_num-1]
job = await self.history_ns[job_id]
if job['end_time'] < before:
break
end_num -= 1
if start_num >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
i = start
count = end_num - start_num
if limit == 0:
limit = MAX_JOBS
while i < count and len(jobs) < limit:
if reverse_order:
job_id = self.cached_job_ids[end_num - i - 1]
else:
job_id = self.cached_job_ids[start_num + i]
job = await self.history_ns[job_id]
jobs.append(self._prep_requested_job(job, job_id))
i += 1
return {"count": count, "jobs": jobs}
async def _handle_job_totals(self,
web_request: WebRequest
) -> Dict[str, Dict[str, float]]:
return {'job_totals': self.job_totals}
async def _handle_job_total_reset(self,
web_request: WebRequest,
) -> Dict[str, Dict[str, float]]:
if self.current_job is not None:
raise self.server.error(
"Job in progress, cannot reset totals")
last_totals = dict(self.job_totals)
self.job_totals = {
'total_jobs': 0,
'total_time': 0.,
'total_print_time': 0.,
'total_filament_used': 0.,
'longest_job': 0.,
'longest_print': 0.
}
database: DBComp = self.server.lookup_component("database")
await database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
return {'last_totals': last_totals}
def _on_job_started(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
if self.current_job is not None:
# Finish with the previous state
self.finish_job("cancelled", prev_stats)
self.add_job(PrinterJob(new_stats))
def _on_job_complete(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("completed", new_stats)
def _on_job_cancelled(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("cancelled", new_stats)
def _on_job_error(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("error", new_stats)
def _on_job_standby(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
# Backward compatibility with
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
self.finish_job("cancelled", prev_stats)
def _handle_shutdown(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("klippy_shutdown", last_ps)
def _handle_disconnect(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("klippy_disconnect", last_ps)
def add_job(self, job: PrinterJob) -> None:
if len(self.cached_job_ids) >= MAX_JOBS:
self.delete_job(self.cached_job_ids[0])
job_id = f"{self.next_job_id:06X}"
self.current_job = job
self.current_job_id = job_id
self.grab_job_metadata()
self.history_ns[job_id] = job.get_stats()
self.cached_job_ids.append(job_id)
self.next_job_id += 1
logging.debug(
f"History Job Added - Id: {job_id}, File: {job.filename}"
)
self.send_history_event("added")
def delete_job(self, job_id: Union[int, str]) -> None:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
if job_id in self.cached_job_ids:
del self.history_ns[job_id]
self.cached_job_ids.remove(job_id)
def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
if self.current_job is None:
return
cj = self.current_job
if (
pstats.get('filename') != cj.get('filename') or
pstats.get('total_duration', 0.) < cj.get('total_duration')
):
# Print stats have been reset, do not update this job with them
pstats = {}
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()
logging.debug(
f"History Job Finished - Id: {self.current_job_id}, "
f"File: {self.current_job.filename}, "
f"Status: {status}"
)
self.send_history_event("finished")
self.current_job = None
self.current_job_id = None
async def get_job(self,
job_id: Union[int, str]
) -> Optional[Dict[str, Any]]:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
return await self.history_ns.get(job_id, None)
def grab_job_metadata(self) -> None:
if self.current_job is None:
return
filename: str = self.current_job.get("filename")
mdst = self.file_manager.get_metadata_storage()
metadata: Dict[str, Any] = mdst.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
})
mdst.insert(filename, metadata.copy())
# We don't need to store these fields in the
# job metadata, as they are redundant
metadata.pop('print_start_time', None)
metadata.pop('job_id', None)
if "thumbnails" in metadata:
thumb: Dict[str, Any]
for thumb in metadata['thumbnails']:
thumb.pop('data', None)
self.current_job.set("metadata", metadata)
def save_current_job(self) -> None:
if self.current_job is None or self.current_job_id is None:
return
self.history_ns[self.current_job_id] = self.current_job.get_stats()
def _update_job_totals(self) -> None:
if self.current_job is None:
return
job = self.current_job
self.job_totals['total_jobs'] += 1
self.job_totals['total_time'] += job.get('total_duration')
self.job_totals['total_print_time'] += job.get('print_duration')
self.job_totals['total_filament_used'] += job.get('filament_used')
self.job_totals['longest_job'] = max(
self.job_totals['longest_job'], job.get('total_duration'))
self.job_totals['longest_print'] = max(
self.job_totals['longest_print'], job.get('print_duration'))
database: DBComp = self.server.lookup_component("database")
database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
def send_history_event(self, evt_action: str) -> None:
if self.current_job is None or self.current_job_id is None:
return
job = self._prep_requested_job(
self.current_job.get_stats(), self.current_job_id)
self.server.send_event("history:history_changed",
{'action': evt_action, 'job': job})
def _prep_requested_job(self,
job: Dict[str, Any],
job_id: str
) -> Dict[str, Any]:
job['job_id'] = job_id
job['exists'] = self.file_manager.check_file_exists(
"gcodes", job['filename'])
return job
def on_exit(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("server_exit", last_ps)
class PrinterJob:
def __init__(self, data: Dict[str, Any] = {}) -> None:
self.end_time: Optional[float] = None
self.filament_used: float = 0
self.filename: Optional[str] = None
self.metadata: Optional[Dict[str, Any]] = None
self.print_duration: float = 0.
self.status: str = "in_progress"
self.start_time = time.time()
self.total_duration: float = 0.
self.update_from_ps(data)
def finish(self,
status: str,
print_stats: Dict[str, Any] = {}
) -> None:
self.end_time = time.time()
self.status = status
self.update_from_ps(print_stats)
def get(self, name: str) -> Any:
if not hasattr(self, name):
return None
return getattr(self, name)
def get_stats(self) -> Dict[str, Any]:
return self.__dict__.copy()
def set(self, name: str, val: Any) -> None:
if not hasattr(self, name):
return
setattr(self, name, val)
def update_from_ps(self, data: Dict[str, Any]) -> None:
for i in data:
if hasattr(self, i):
setattr(self, i, data[i])
def load_component(config: ConfigHelper) -> History:
return History(config)
+470
View File
@@ -0,0 +1,470 @@
# Wrapper around Tornado's HTTP Client with a "requests-like" interface
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import re
import json
import time
import asyncio
import pathlib
import tempfile
import logging
from ..utils import ServerError
from tornado.escape import url_escape, url_unescape
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError
from tornado.httputil import HTTPHeaders
from typing import (
TYPE_CHECKING,
Callable,
Optional,
Tuple,
Union,
Dict,
List,
Any
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from io import BufferedWriter
StrOrPath = Union[str, pathlib.Path]
MAX_BODY_SIZE = 512 * 1024 * 1024
AsyncHTTPClient.configure(
None, defaults=dict(user_agent="Moonraker"),
max_body_size=MAX_BODY_SIZE
)
GITHUB_PREFIX = "https://api.github.com/"
class HttpClient:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.client = AsyncHTTPClient()
self.response_cache: Dict[str, HttpResponse] = {}
self.gh_rate_limit: Optional[int] = None
self.gh_limit_remaining: Optional[int] = None
self.gh_limit_reset_time: Optional[float] = None
def register_cached_url(
self,
url: str,
etag: Optional[str] = None,
last_modified: Optional[str] = None
) -> None:
headers = HTTPHeaders()
if etag is not None:
headers["etag"] = etag
if last_modified is not None:
headers["last-modified"] = last_modified
if len(headers) == 0:
raise self.server.error(
"Either an Etag or Last Modified Date must be specified")
empty_resp = HttpResponse(url, url, 200, b"", headers, None)
self.response_cache[url] = empty_resp
async def request(
self,
method: str,
url: str,
body: Optional[Union[str, List[Any], Dict[str, Any]]] = None,
headers: Optional[Dict[str, Any]] = None,
connect_timeout: float = 5.,
request_timeout: float = 10.,
attempts: int = 1,
retry_pause_time: float = .1,
enable_cache: bool = False,
send_etag: bool = True,
send_if_modified_since: bool = True
) -> HttpResponse:
cache_key = url.split("?", 1)[0]
method = method.upper()
# prepare the body if required
req_headers: Dict[str, Any] = {}
if isinstance(body, (list, dict)):
body = json.dumps(body)
req_headers["Content-Type"] = "application/json"
cached: Optional[HttpResponse] = None
if enable_cache:
cached = self.response_cache.get(cache_key)
if cached is not None and send_etag:
if cached.etag is not None and send_etag:
req_headers["If-None-Match"] = cached.etag
if cached.last_modified and send_if_modified_since:
req_headers["If-Modified-Since"] = cached.last_modified
if headers is not None:
headers.update(req_headers)
elif req_headers:
headers = req_headers
timeout = 1 + connect_timeout + request_timeout
request = HTTPRequest(url, method, headers, body=body,
request_timeout=request_timeout,
connect_timeout=connect_timeout)
err: Optional[BaseException] = None
for i in range(attempts):
if i:
await asyncio.sleep(retry_pause_time)
try:
fut = self.client.fetch(request, raise_error=False)
resp = await asyncio.wait_for(fut, timeout)
except asyncio.CancelledError:
raise
except Exception as e:
err = e
else:
err = resp.error
if resp.code == 304:
err = None
if cached is None:
if enable_cache:
logging.info(
"Request returned 304, however no cached "
"item was found")
result = b""
else:
logging.debug(f"Request returned from cache: {url}")
result = cached.content
elif resp.error is not None and attempts - i != 1:
continue
else:
result = resp.body
ret = HttpResponse(
url, resp.effective_url, resp.code, result,
resp.headers, err
)
break
else:
ret = HttpResponse(url, url, 500, b"", HTTPHeaders(), err)
if enable_cache and ret.is_cachable():
logging.debug(f"Caching HTTP Response: {url}")
self.response_cache[cache_key] = ret
else:
self.response_cache.pop(cache_key, None)
return ret
async def get(
self, url: str, headers: Optional[Dict[str, Any]] = None, **kwargs
) -> HttpResponse:
if "enable_cache" not in kwargs:
kwargs["enable_cache"] = True
return await self.request("GET", url, None, headers, **kwargs)
async def post(
self,
url: str,
body: Union[str, List[Any], Dict[str, Any]] = "",
headers: Optional[Dict[str, Any]] = None,
**kwargs
) -> HttpResponse:
return await self.request("POST", url, body, headers, **kwargs)
async def delete(
self,
url: str,
headers: Optional[Dict[str, Any]] = None,
**kwargs
) -> HttpResponse:
return await self.request("DELETE", url, None, headers, **kwargs)
async def github_api_request(
self,
resource: str,
attempts: int = 1,
retry_pause_time: float = .1
) -> HttpResponse:
url = f"{GITHUB_PREFIX}{resource.strip('/')}"
if (
self.gh_limit_reset_time is not None and
self.gh_limit_remaining == 0
):
curtime = time.time()
if curtime < self.gh_limit_reset_time:
reset_time = time.ctime(self.gh_limit_reset_time)
raise self.server.error(
f"GitHub Rate Limit Reached\n"
f"Request: {url}\n"
f"Limit Reset Time: {reset_time}"
)
headers = {"Accept": "application/vnd.github.v3+json"}
resp = await self.get(
url, headers, attempts=attempts,
retry_pause_time=retry_pause_time)
resp_hdrs = resp.headers
if 'X-Ratelimit-Limit' in resp_hdrs:
self.gh_rate_limit = int(resp_hdrs['X-Ratelimit-Limit'])
self.gh_limit_remaining = int(
resp_hdrs['X-Ratelimit-Remaining'])
self.gh_limit_reset_time = float(
resp_hdrs['X-Ratelimit-Reset'])
return resp
def github_api_stats(self) -> Dict[str, Any]:
return {
'github_rate_limit': self.gh_rate_limit,
'github_requests_remaining': self.gh_limit_remaining,
'github_limit_reset_time': self.gh_limit_reset_time,
}
async def get_file(
self,
url: str,
content_type: str,
connect_timeout: float = 5.,
request_timeout: float = 180.,
attempts: int = 1,
retry_pause_time: float = .1,
enable_cache: bool = False,
) -> bytes:
headers = {"Accept": content_type}
resp = await self.get(
url, headers, connect_timeout=connect_timeout,
request_timeout=request_timeout, attempts=attempts,
retry_pause_time=retry_pause_time, enable_cache=enable_cache
)
resp.raise_for_status()
return resp.content
async def download_file(
self,
url: str,
content_type: str,
destination_path: Optional[StrOrPath] = None,
download_size: int = -1,
progress_callback: Optional[Callable[[int, int, int], None]] = None,
connect_timeout: float = 5.,
request_timeout: float = 180.,
attempts: int = 1,
retry_pause_time: float = 1.
) -> pathlib.Path:
for i in range(attempts):
dl = StreamingDownload(
self.server, destination_path, download_size,
progress_callback)
try:
fut = self.client.fetch(
url, headers={"Accept": content_type},
connect_timeout=connect_timeout,
request_timeout=request_timeout,
streaming_callback=dl.on_chunk_recd,
header_callback=dl.on_headers_recd)
timeout = connect_timeout + request_timeout + 1.
resp = await asyncio.wait_for(fut, timeout)
except asyncio.CancelledError:
raise
except Exception:
if i + 1 == attempts:
raise
await asyncio.sleep(retry_pause_time)
continue
finally:
await dl.close()
if resp.code < 400:
return dl.dest_file
raise self.server.error(f"Retries exceeded for request: {url}")
def close(self):
self.client.close()
class HttpResponse:
def __init__(self,
url: str,
final_url: str,
code: int,
result: bytes,
response_headers: HTTPHeaders,
error: Optional[BaseException]
) -> None:
self._url = url
self._final_url = final_url
self._code = code
self._result: bytes = result
self._encoding: str = "utf-8"
self._response_headers: HTTPHeaders = response_headers
self._etag: Optional[str] = response_headers.get("etag", None)
self._error = error
self._last_modified: Optional[str] = response_headers.get(
"last-modified", None)
def json(self, **kwargs) -> Union[List[Any], Dict[str, Any]]:
return json.loads(self._result, **kwargs)
def is_cachable(self) -> bool:
return self._last_modified is not None or self._etag is not None
def has_error(self) -> bool:
return self._error is not None
def raise_for_status(self, message: Optional[str] = None) -> None:
if self._error is not None:
code = 500
msg = f"HTTP Request Error: {self.url}"
if isinstance(self._error, HTTPError):
code = self._code
if self._error.message is not None:
msg = self._error.message
if message is not None:
msg = message
raise ServerError(msg, code) from self._error
@property
def encoding(self) -> str:
return self._encoding
@encoding.setter
def encoding(self, new_enc: str) -> None:
self._encoding = new_enc
@property
def text(self) -> str:
return self._result.decode(encoding=self._encoding)
@property
def content(self) -> bytes:
return self._result
@property
def url(self) -> str:
return self._url
@property
def final_url(self) -> str:
return self._final_url
@property
def status_code(self) -> int:
return self._code
@property
def headers(self) -> HTTPHeaders:
return self._response_headers
@property
def last_modified(self) -> Optional[str]:
return self._last_modified
@property
def etag(self) -> Optional[str]:
return self._etag
@property
def error(self) -> Optional[BaseException]:
return self._error
class StreamingDownload:
def __init__(
self,
server: Server,
dest_path: Optional[StrOrPath],
download_size: int,
progress_callback: Optional[Callable[[int, int, int], None]]
) -> None:
self.server = server
self.event_loop = server.get_event_loop()
self.need_content_length: bool = True
self.need_content_disposition: bool = False
self.request_ok: bool = False
if dest_path is None:
# If no destination is provided initialize to a procedurally
# generated temp file. We will attempt to extract the filename
# from the Content-Disposition Header
tmp_dir = tempfile.gettempdir()
loop_time = int(self.event_loop.get_loop_time())
tmp_fname = f"moonraker.download-{loop_time}.mrd"
self.dest_file = pathlib.Path(tmp_dir).joinpath(tmp_fname)
self.need_content_disposition = True
elif isinstance(dest_path, str):
self.dest_file = pathlib.Path(dest_path)
else:
self.dest_file = dest_path
self.filename = self.dest_file.name
self.file_hdl: Optional[BufferedWriter] = None
self.total_recd: int = 0
self.download_size: int = download_size
self.pct_done: int = 0
self.chunk_buffer: List[bytes] = []
self.progress_callback = progress_callback
self.busy_evt: asyncio.Event = asyncio.Event()
self.busy_evt.set()
def on_headers_recd(self, line: str) -> None:
if not self.need_content_length and not self.need_content_disposition:
return
line = line.strip()
rc_match = re.match(r"HTTP/\d.?\d? (\d+)", line)
if rc_match is not None:
self.request_ok = rc_match.group(1) == "200"
return
if not self.request_ok:
return
parts = line.split(":", 1)
if len(parts) < 2:
return
hname = parts[0].strip().lower()
hval = parts[1].strip()
if hname == "content-length" and self.need_content_length:
self.download_size = int(hval)
self.need_content_length = False
logging.debug(
f"Content-Length header received: "
f"size = {self.download_size}")
elif (
hname == "content-disposition" and
self.need_content_disposition
):
fnr = r"filename[^;\n=]*=(['\"])?(utf-8\'\')?([^\n;]*)(?(1)\1|)"
matches: List[Tuple[str, str, str]] = re.findall(fnr, hval)
is_utf8 = False
for (_, encoding, fname) in matches:
if encoding.startswith("utf-8"):
# Prefer the utf8 filename if included
self.filename = url_unescape(
fname, encoding="utf-8", plus=False)
is_utf8 = True
break
self.filename = fname
self.need_content_disposition = False
# Use the filename extracted from the content-disposition header
self.dest_file = self.dest_file.parent.joinpath(self.filename)
logging.debug(
"Content-Disposition header received: filename = "
f"{self.filename}, utf8: {is_utf8}")
def on_chunk_recd(self, chunk: bytes) -> None:
if not chunk:
return
self.chunk_buffer.append(chunk)
if not self.busy_evt.is_set():
return
self.busy_evt.clear()
self.event_loop.register_callback(self._process_buffer)
async def close(self):
await self.busy_evt.wait()
if self.file_hdl is not None:
await self.event_loop.run_in_thread(self.file_hdl.close)
async def _process_buffer(self):
if self.file_hdl is None:
self.file_hdl = await self.event_loop.run_in_thread(
self.dest_file.open, "wb")
while self.chunk_buffer:
chunk = self.chunk_buffer.pop(0)
await self.event_loop.run_in_thread(self.file_hdl.write, chunk)
self.total_recd += len(chunk)
if self.download_size > 0 and self.progress_callback is not None:
pct = int(self.total_recd / self.download_size * 100 + .5)
pct = min(100, pct)
if pct != self.pct_done:
self.pct_done = pct
self.progress_callback(
pct, self.download_size, self.total_recd)
self.busy_evt.set()
def load_component(config: ConfigHelper) -> HttpClient:
return HttpClient(config)
+337
View File
@@ -0,0 +1,337 @@
# Print Job Queue Implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import time
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Union,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI
from .file_manager.file_manager import FileManager
class JobQueue:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.queued_jobs: Dict[str, QueuedJob] = {}
self.lock = asyncio.Lock()
self.load_on_start = config.getboolean("load_on_startup", False)
self.automatic = config.getboolean("automatic_transition", False)
self.queue_state: str = "ready" if self.automatic else "paused"
self.job_delay = config.getfloat("job_transition_delay", 0.01)
if self.job_delay <= 0.:
raise config.error(
"Value for option 'job_transition_delay' in section [job_queue]"
" must be above 0.0")
self.job_transition_gcode = config.get(
"job_transition_gcode", "").strip()
self.pop_queue_handle: Optional[asyncio.TimerHandle] = None
self.server.register_event_handler(
"server:klippy_ready", self._handle_ready)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_event_handler(
"job_state:complete", self._on_job_complete)
self.server.register_event_handler(
"job_state:error", self._on_job_abort)
self.server.register_event_handler(
"job_state:cancelled", self._on_job_abort)
self.server.register_notification("job_queue:job_queue_changed")
self.server.register_remote_method("pause_job_queue", self.pause_queue)
self.server.register_remote_method("start_job_queue",
self.start_queue)
self.server.register_endpoint(
"/server/job_queue/job", ['POST', 'DELETE'],
self._handle_job_request)
self.server.register_endpoint(
"/server/job_queue/pause", ['POST'], self._handle_pause_queue)
self.server.register_endpoint(
"/server/job_queue/start", ['POST'], self._handle_start_queue)
self.server.register_endpoint(
"/server/job_queue/status", ['GET'], self._handle_queue_status)
self.server.register_endpoint(
"/server/job_queue/jump", ['POST'], self._handle_jump)
async def _handle_ready(self) -> None:
async with self.lock:
if not self.load_on_start or not self.queued_jobs:
return
# start a queued print
if self.queue_state in ['ready', 'paused']:
event_loop = self.server.get_event_loop()
self._set_queue_state("loading")
self.pop_queue_handle = event_loop.delay_callback(
1., self._pop_job, False)
async def _handle_shutdown(self) -> None:
await self.pause_queue()
if not self.queued_jobs and self.automatic:
self._set_queue_state("ready")
async def _on_job_complete(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
async with self.lock:
# Transition to the next job in the queue
if self.queue_state == "ready" and self.queued_jobs:
event_loop = self.server.get_event_loop()
self._set_queue_state("loading")
self.pop_queue_handle = event_loop.delay_callback(
self.job_delay, self._pop_job)
async def _on_job_abort(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
async with self.lock:
if self.queued_jobs:
self._set_queue_state("paused")
async def _pop_job(self, need_transition: bool = True) -> None:
self.pop_queue_handle = None
async with self.lock:
if self.queue_state == "paused":
return
if not self.queued_jobs:
qs = "ready" if self.automatic else "paused"
self._set_queue_state(qs)
return
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
uid, job = list(self.queued_jobs.items())[0]
filename = str(job)
can_print = await self._check_can_print()
if not can_print or self.queue_state != "loading":
self._set_queue_state("paused")
return
try:
if self.job_transition_gcode and need_transition:
await kapis.run_gcode(self.job_transition_gcode)
# Check to see if the queue was paused while running
# the job transition gcode
if self.queue_state != "loading":
raise self.server.error(
"Queue State Changed during Transition Gcode")
self._set_queue_state("starting")
await kapis.start_print(filename, wait_klippy_started=True)
except self.server.error:
logging.exception(f"Error Loading print: {filename}")
self._set_queue_state("paused")
else:
self.queued_jobs.pop(uid, None)
if self.queue_state == "starting":
# If the queue was not paused while starting the print,
set_ready = not self.queued_jobs or self.automatic
self.queue_state = "ready" if set_ready else "paused"
self._send_queue_event(action="job_loaded")
async def _check_can_print(self) -> bool:
# Query the latest stats
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
try:
result = await kapis.query_objects({"print_stats": None})
except Exception:
# Klippy not connected
return False
if 'print_stats' not in result:
return False
state: str = result['print_stats']['state']
if state in ["printing", "paused"]:
return False
return True
async def queue_job(self,
filenames: Union[str, List[str]],
check_exists: bool = True,
reset: bool = False
) -> None:
async with self.lock:
# Make sure that the file exists
if isinstance(filenames, str):
filenames = [filenames]
if check_exists:
# Make sure all files exist before adding them to the queue
for fname in filenames:
self._check_job_file(fname)
if reset:
self.queued_jobs.clear()
for fname in filenames:
queued_job = QueuedJob(fname)
self.queued_jobs[queued_job.job_id] = queued_job
self._send_queue_event(action="jobs_added")
async def delete_job(self,
job_ids: Union[str, List[str]],
all: bool = False
) -> None:
async with self.lock:
if not self.queued_jobs:
# No jobs in queue, nothing to delete
return
if all:
self.queued_jobs.clear()
elif job_ids:
if isinstance(job_ids, str):
job_ids = [job_ids]
for uid in job_ids:
self.queued_jobs.pop(uid, None)
else:
# Don't notify, nothing was deleted
return
self._send_queue_event(action="jobs_removed")
async def pause_queue(self) -> None:
self._set_queue_state("paused")
if self.pop_queue_handle is not None:
self.pop_queue_handle.cancel()
self.pop_queue_handle = None
# Acquire the lock to wait for any pending operations to
# complete
await self.lock.acquire()
self.lock.release()
async def start_queue(self) -> None:
async with self.lock:
if self.queue_state != "loading":
if self.queued_jobs and await self._check_can_print():
self._set_queue_state("loading")
event_loop = self.server.get_event_loop()
self.pop_queue_handle = event_loop.delay_callback(
0.01, self._pop_job)
else:
self._set_queue_state("ready")
def _job_map_to_list(self) -> List[Dict[str, Any]]:
cur_time = time.time()
return [job.as_dict(cur_time) for
job in self.queued_jobs.values()]
def _check_job_file(self, job_name: str) -> None:
fm: FileManager = self.server.lookup_component('file_manager')
if not fm.check_file_exists("gcodes", job_name):
raise self.server.error(
f"G-Code File {job_name} does not exist")
def _set_queue_state(self, new_state: str) -> None:
if new_state != self.queue_state:
self.queue_state = new_state
self._send_queue_event()
def _send_queue_event(self, action: str = "state_changed"):
updated_queue: Optional[List[Dict[str, Any]]] = None
if action != "state_changed":
updated_queue = self._job_map_to_list()
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.05, self.server.send_event, "job_queue:job_queue_changed",
{
'action': action,
'updated_queue': updated_queue,
'queue_state': self.queue_state
})
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "POST":
files: Union[List[str], str] = web_request.get('filenames')
reset = web_request.get_boolean("reset", False)
if isinstance(files, str):
files = [f.strip() for f in files.split(',') if f.strip()]
# Validate that all files exist before queueing
await self.queue_job(files, reset=reset)
elif action == "DELETE":
if web_request.get_boolean("all", False):
await self.delete_job([], all=True)
else:
job_ids: Union[List[str], str] = web_request.get('job_ids')
if isinstance(job_ids, str):
job_ids = [f.strip() for f in job_ids.split(',')
if f.strip()]
await self.delete_job(job_ids)
else:
raise self.server.error(f"Invalid action: {action}")
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_pause_queue(self,
web_request: WebRequest
) -> Dict[str, Any]:
await self.pause_queue()
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_start_queue(self,
web_request: WebRequest
) -> Dict[str, Any]:
await self.start_queue()
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_queue_status(self,
web_request: WebRequest
) -> Dict[str, Any]:
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_jump(self, web_request: WebRequest) -> Dict[str, Any]:
job_id: str = web_request.get("job_id")
async with self.lock:
job = self.queued_jobs.pop(job_id, None)
if job is None:
raise self.server.error(f"Invalid job id: {job_id}")
new_queue = {job_id: job}
new_queue.update(self.queued_jobs)
self.queued_jobs = new_queue
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def close(self):
await self.pause_queue()
class QueuedJob:
def __init__(self, filename: str) -> None:
self.filename = filename
self.job_id = f"{id(self):016X}"
self.time_added = time.time()
def __str__(self) -> str:
return self.filename
def as_dict(self, cur_time: float) -> Dict[str, Any]:
return {
'filename': self.filename,
'job_id': self.job_id,
'time_added': self.time_added,
'time_in_queue': cur_time - self.time_added
}
def load_component(config: ConfigHelper) -> JobQueue:
return JobQueue(config)
+95
View File
@@ -0,0 +1,95 @@
# Klippy job state event handlers
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .klippy_apis import KlippyAPI
class JobState:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.last_print_stats: Dict[str, Any] = {}
self.server.register_event_handler(
"server:klippy_started", self._handle_started)
self.server.register_event_handler(
"server:status_update", self._status_update)
async def _handle_started(self, state: str) -> None:
if state != "ready":
return
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
sub: Dict[str, Optional[List[str]]] = {"print_stats": None}
try:
result = await kapis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to print_stats")
self.last_print_stats = result.get("print_stats", {})
if "state" in self.last_print_stats:
state = self.last_print_stats["state"]
logging.info(f"Job state initialized: {state}")
async def _status_update(self, data: Dict[str, Any]) -> None:
if 'print_stats' not in data:
return
ps = data['print_stats']
if "state" in ps:
prev_ps = dict(self.last_print_stats)
old_state: str = prev_ps['state']
new_state: str = ps['state']
new_ps = dict(self.last_print_stats)
new_ps.update(ps)
if new_state is not old_state:
if new_state == "printing":
# The "printing" state needs some special handling
# to detect "resets" and a transition from pause to resume
if self._check_resumed(prev_ps, new_ps):
new_state = "resumed"
else:
logging.info(
f"Job Started: {new_ps['filename']}"
)
new_state = "started"
logging.debug(
f"Job State Changed - Prev State: {old_state}, "
f"New State: {new_state}"
)
self.server.send_event(
f"job_state:{new_state}", prev_ps, new_ps)
if "info" in ps:
cur_layer: Optional[int] = ps["info"].get("current_layer")
if cur_layer is not None:
total: int = ps["info"].get("total_layer", 0)
self.server.send_event(
"job_state:layer_changed", cur_layer, total
)
self.last_print_stats.update(ps)
def _check_resumed(self,
prev_ps: Dict[str, Any],
new_ps: Dict[str, Any]
) -> bool:
return (
prev_ps['state'] == "paused" and
prev_ps['filename'] == new_ps['filename'] and
prev_ps['total_duration'] < new_ps['total_duration']
)
def get_last_stats(self) -> Dict[str, Any]:
return dict(self.last_print_stats)
def load_component(config: ConfigHelper) -> JobState:
return JobState(config)
+242
View File
@@ -0,0 +1,242 @@
# Helper for Moonraker to Klippy API calls.
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from ..utils import Sentinel
from ..websockets import WebRequest, Subscribable
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
TypeVar,
Mapping,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from ..klippy_connection import KlippyConnection as Klippy
Subscription = Dict[str, Optional[List[Any]]]
_T = TypeVar("_T")
INFO_ENDPOINT = "info"
ESTOP_ENDPOINT = "emergency_stop"
LIST_EPS_ENDPOINT = "list_endpoints"
GC_OUTPUT_ENDPOINT = "gcode/subscribe_output"
GCODE_ENDPOINT = "gcode/script"
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
STATUS_ENDPOINT = "objects/query"
OBJ_LIST_ENDPOINT = "objects/list"
REG_METHOD_ENDPOINT = "register_remote_method"
class KlippyAPI(Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
app_args = self.server.get_app_args()
self.version = app_args.get('software_version')
# Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them
self.host_subscription: Subscription = {}
# Register GCode Aliases
self.server.register_endpoint(
"/printer/print/pause", ['POST'], self._gcode_pause)
self.server.register_endpoint(
"/printer/print/resume", ['POST'], self._gcode_resume)
self.server.register_endpoint(
"/printer/print/cancel", ['POST'], self._gcode_cancel)
self.server.register_endpoint(
"/printer/print/start", ['POST'], self._gcode_start_print)
self.server.register_endpoint(
"/printer/restart", ['POST'], self._gcode_restart)
self.server.register_endpoint(
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
async def _gcode_pause(self, web_request: WebRequest) -> str:
return await self.pause_print()
async def _gcode_resume(self, web_request: WebRequest) -> str:
return await self.resume_print()
async def _gcode_cancel(self, web_request: WebRequest) -> str:
return await self.cancel_print()
async def _gcode_start_print(self, web_request: WebRequest) -> str:
filename: str = web_request.get_str('filename')
return await self.start_print(filename)
async def _gcode_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(
self,
method: str,
params: Dict[str, Any],
default: Any = Sentinel.MISSING
) -> Any:
try:
req = WebRequest(method, params, conn=self)
result = await self.klippy.request(req)
except self.server.error:
if default is Sentinel.MISSING:
raise
result = default
return result
async def run_gcode(self,
script: str,
default: Any = Sentinel.MISSING
) -> str:
params = {'script': script}
result = await self._send_klippy_request(
GCODE_ENDPOINT, params, default)
return result
async def start_print(
self, filename: str, wait_klippy_started: bool = False
) -> str:
# WARNING: Do not call this method from within the following
# event handlers when "wait_klippy_started" is set to True:
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
# Doing so will result in "wait_started" blocking for the specifed
# timeout (default 20s) and returning False.
# 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}"'
if wait_klippy_started:
await self.klippy.wait_started()
return await self.run_gcode(script)
async def pause_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:pause_requested")
return await self._send_klippy_request(
"pause_resume/pause", {}, default)
async def resume_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:resume_requested")
return await self._send_klippy_request(
"pause_resume/resume", {}, default)
async def cancel_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:cancel_requested")
return await self._send_klippy_request(
"pause_resume/cancel", {}, default)
async def do_restart(
self, gc: str, wait_klippy_started: bool = False
) -> str:
# WARNING: Do not call this method from within the following
# event handlers when "wait_klippy_started" is set to True:
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
# Doing so will result in "wait_started" blocking for the specifed
# timeout (default 20s) and returning False.
if wait_klippy_started:
await self.klippy.wait_started()
try:
result = await self.run_gcode(gc)
except self.server.error as e:
if str(e) == "Klippy Disconnected":
result = "ok"
else:
raise
return result
async def list_endpoints(self,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, List[str]]]:
return await self._send_klippy_request(
LIST_EPS_ENDPOINT, {}, default)
async def emergency_stop(self) -> str:
return await self._send_klippy_request(ESTOP_ENDPOINT, {})
async def get_klippy_info(self,
send_id: bool = False,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
params = {}
if send_id:
ver = self.version
params = {'client_info': {'program': "Moonraker", 'version': ver}}
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
async def get_object_list(self,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, List[str]]:
result = await self._send_klippy_request(
OBJ_LIST_ENDPOINT, {}, default)
if isinstance(result, dict) and 'objects' in result:
return result['objects']
return result
async def query_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
params = {'objects': objects}
result = await self._send_klippy_request(
STATUS_ENDPOINT, params, default)
if isinstance(result, dict) and 'status' in result:
return result['status']
return result
async def subscribe_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
for obj, items in objects.items():
if obj in self.host_subscription:
prev = self.host_subscription[obj]
if items is None or prev is None:
self.host_subscription[obj] = None
else:
uitems = list(set(prev) | set(items))
self.host_subscription[obj] = uitems
else:
self.host_subscription[obj] = items
params = {'objects': self.host_subscription}
result = await self._send_klippy_request(
SUBSCRIPTION_ENDPOINT, params, default)
if isinstance(result, dict) and 'status' in result:
return result['status']
return result
async def subscribe_gcode_output(self) -> str:
template = {'response_template':
{'method': "process_gcode_response"}}
return await self._send_klippy_request(GC_OUTPUT_ENDPOINT, template)
async def register_method(self, method_name: str) -> str:
return await self._send_klippy_request(
REG_METHOD_ENDPOINT,
{'response_template': {"method": method_name},
'remote_method': method_name})
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
self.server.send_event("server:status_update", status)
def load_component(config: ConfigHelper) -> KlippyAPI:
return KlippyAPI(config)
+129
View File
@@ -0,0 +1,129 @@
# LDAP authentication for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
# Copyright (C) 2022 Luca Schöneberg <luca-schoeneberg@outlook.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import logging
import ldap3
from ldap3.core.exceptions import LDAPExceptionError
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ldap3.abstract.entry import Entry
class MoonrakerLDAP:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ldap_host = config.get('ldap_host')
self.ldap_port = config.getint("ldap_port", None)
self.ldap_secure = config.getboolean("ldap_secure", False)
base_dn_template = config.gettemplate('base_dn')
self.base_dn = base_dn_template.render()
self.group_dn: Optional[str] = None
group_dn_template = config.gettemplate("group_dn", None)
if group_dn_template is not None:
self.group_dn = group_dn_template.render()
self.active_directory = config.getboolean('is_active_directory', False)
self.bind_dn: Optional[str] = None
self.bind_password: Optional[str] = None
bind_dn_template = config.gettemplate('bind_dn', None)
bind_pass_template = config.gettemplate('bind_password', None)
if bind_dn_template is not None:
self.bind_dn = bind_dn_template.render()
if bind_pass_template is None:
raise config.error(
"Section [ldap]: Option 'bind_password' is "
"required when 'bind_dn' is provided"
)
self.bind_password = bind_pass_template.render()
self.user_filter: Optional[str] = None
user_filter_template = config.gettemplate('user_filter', None)
if user_filter_template is not None:
self.user_filter = user_filter_template.render()
if "USERNAME" not in self.user_filter:
raise config.error(
"Section [ldap]: Option 'user_filter' is "
"is missing required token USERNAME"
)
self.lock = asyncio.Lock()
async def authenticate_ldap_user(self, username, password) -> None:
eventloop = self.server.get_event_loop()
async with self.lock:
await eventloop.run_in_thread(
self._perform_ldap_auth, username, password
)
def _perform_ldap_auth(self, username, password) -> None:
server = ldap3.Server(
self.ldap_host, self.ldap_port, use_ssl=self.ldap_secure,
connect_timeout=10.
)
conn_args = {
"user": self.bind_dn,
"password": self.bind_password,
"auto_bind": ldap3.AUTO_BIND_NO_TLS,
}
attr_name = "sAMAccountName" if self.active_directory else "uid"
ldfilt = f"(&(objectClass=Person)({attr_name}={username}))"
if self.user_filter:
ldfilt = self.user_filter.replace("USERNAME", username)
try:
with ldap3.Connection(server, **conn_args) as conn:
ret = conn.search(
self.base_dn, ldfilt, attributes=["memberOf"]
)
if not ret:
raise self.server.error(
f"LDAP User '{username}' Not Found", 401
)
user: Entry = conn.entries[0]
rebind_success = conn.rebind(user.entry_dn, password)
if not rebind_success:
# Server may not allow rebinding, attempt to start
# a new connection to validate credentials
logging.debug(
"LDAP Rebind failed, attempting to validate credentials "
"with new connection."
)
conn_args["user"] = user.entry_dn
conn_args["password"] = password
with ldap3.Connection(server, **conn_args) as conn:
if self._validate_group(username, user):
return
elif self._validate_group(username, user):
return
except LDAPExceptionError:
err_msg = "LDAP authentication failed"
else:
err_msg = "Invalid LDAP Username or Password"
raise self.server.error(err_msg, 401)
def _validate_group(self, username: str, user: Entry) -> bool:
if self.group_dn is None:
logging.debug(f"LDAP User {username} login successful")
return True
if not hasattr(user, "memberOf"):
return False
for group in user.memberOf.values:
if group == self.group_dn:
logging.debug(
f"LDAP User {username} group match success, "
"login successful"
)
return True
return False
def load_component(config: ConfigHelper) -> MoonrakerLDAP:
return MoonrakerLDAP(config)
File diff suppressed because it is too large. Load diff
+786
View File
@@ -0,0 +1,786 @@
# MQTT client implementation for Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import socket
import asyncio
import logging
import json
import pathlib
import ssl
from collections import deque
import paho.mqtt.client as paho_mqtt
from ..websockets import Subscribable, WebRequest, JsonRPC, APITransport
# Annotation imports
from typing import (
List,
Optional,
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Union,
Tuple,
Awaitable,
Deque,
)
if TYPE_CHECKING:
from ..app import APIDefinition
from ..confighelper import ConfigHelper
from ..klippy_connection import KlippyConnection as Klippy
FlexCallback = Callable[[bytes], Optional[Coroutine]]
RPCCallback = Callable[..., Coroutine]
DUP_API_REQ_CODE = -10000
MQTT_PROTOCOLS = {
'v3.1': paho_mqtt.MQTTv31,
'v3.1.1': paho_mqtt.MQTTv311,
'v5': paho_mqtt.MQTTv5
}
class ExtPahoClient(paho_mqtt.Client):
# Override reconnection to take a connected socket. This allows Moonraker
# create the socket connection asynchronously
def reconnect(self, sock: Optional[socket.socket] = None):
"""Reconnect the client after a disconnect. Can only be called after
connect()/connect_async()."""
if len(self._host) == 0:
raise ValueError('Invalid host.')
if self._port <= 0:
raise ValueError('Invalid port number.')
if hasattr(self, "_out_packet_mutex"):
# Paho Mqtt Version < 1.6.x
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"",
"to_process": 0,
"pos": 0
}
with self._out_packet_mutex:
self._out_packet = deque() # type: ignore
with self._current_out_packet_mutex:
self._current_out_packet = None
else:
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": bytearray(b""),
"to_process": 0,
"pos": 0
}
self._out_packet = deque() # type: ignore
with self._msgtime_mutex:
self._last_msg_in = paho_mqtt.time_func()
self._last_msg_out = paho_mqtt.time_func()
self._ping_t = 0
self._state = paho_mqtt.mqtt_cs_new
self._sock_close()
# Put messages in progress in a valid state.
self._messages_reconnect_reset()
if sock is None:
sock = self._create_socket_connection()
if self._ssl:
# SSL is only supported when SSLContext is available
# (implies Python >= 2.7.9 or >= 3.2)
verify_host = not self._tls_insecure
try:
# Try with server_hostname, even it's not supported in
# certain scenarios
sock = self._ssl_context.wrap_socket(
sock,
server_hostname=self._host,
do_handshake_on_connect=False,
)
except ssl.CertificateError:
# CertificateError is derived from ValueError
raise
except ValueError:
# Python version requires SNI in order to handle
# server_hostname, but SNI is not available
sock = self._ssl_context.wrap_socket(
sock,
do_handshake_on_connect=False,
)
else:
# If SSL context has already checked hostname, then don't need
# to do it again
if (hasattr(self._ssl_context, 'check_hostname') and
self._ssl_context.check_hostname):
verify_host = False
assert isinstance(sock, ssl.SSLSocket)
sock.settimeout(self._keepalive)
sock.do_handshake()
if verify_host:
ssl.match_hostname(sock.getpeercert(), self._host)
if self._transport == "websockets":
sock.settimeout(self._keepalive)
sock = paho_mqtt.WebsocketWrapper(
sock, self._host, self._port, self._ssl,
self._websocket_path, self._websocket_extra_headers
)
self._sock = sock
assert self._sock is not None
self._sock.setblocking(False)
self._registered_write = False
self._call_socket_open()
return self._send_connect(self._keepalive)
class SubscriptionHandle:
def __init__(self, topic: str, callback: FlexCallback) -> None:
self.callback = callback
self.topic = topic
class BrokerAckLogger:
def __init__(self, topics: List[str], action: str) -> None:
self.topics = topics
self.action = action
def __call__(self, fut: asyncio.Future) -> None:
if self.action == "subscribe":
res: Union[List[int], List[paho_mqtt.ReasonCodes]]
res = fut.result()
log_msg = "MQTT Subscriptions Acknowledged"
if len(res) != len(self.topics):
log_msg += "\nTopic / QOS count mismatch, " \
f"\nTopics: {self.topics} " \
f"\nQoS responses: {res}"
else:
for topic, qos in zip(self.topics, res):
log_msg += f"\n Topic: {topic} | "
if isinstance(qos, paho_mqtt.ReasonCodes):
log_msg += qos.getName()
else:
log_msg += f"Granted QoS {qos}"
elif self.action == "unsubscribe":
log_msg = "MQTT Unsubscribe Acknowledged"
for topic in self.topics:
log_msg += f"\n Topic: {topic}"
else:
log_msg = f"Unknown action: {self.action}"
logging.debug(log_msg)
SubscribedDict = Dict[str, Tuple[int, List[SubscriptionHandle]]]
class AIOHelper:
def __init__(self, client: paho_mqtt.Client) -> None:
self.loop = asyncio.get_running_loop()
self.client = client
self.client.on_socket_open = self._on_socket_open
self.client.on_socket_close = self._on_socket_close
self.client._on_socket_register_write = self._on_socket_register_write
self.client._on_socket_unregister_write = \
self._on_socket_unregister_write
self.misc_task: Optional[asyncio.Task] = None
def _on_socket_open(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Opened")
self.loop.add_reader(sock, client.loop_read)
self.misc_task = self.loop.create_task(self.misc_loop())
def _on_socket_close(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Closed")
self.loop.remove_reader(sock)
if self.misc_task is not None:
self.misc_task.cancel()
def _on_socket_register_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.add_writer(sock, client.loop_write)
def _on_socket_unregister_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.remove_writer(sock)
async def misc_loop(self) -> None:
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break
logging.info("MQTT Misc Loop Complete")
class MQTTClient(APITransport, Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.event_loop = self.server.get_event_loop()
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
self.address: str = config.get('address')
self.port: int = config.getint('port', 1883)
user = config.gettemplate('username', None)
self.user_name: Optional[str] = None
if user:
self.user_name = user.render()
pw_file_path = config.get('password_file', None, deprecate=True)
pw_template = config.gettemplate('password', None)
self.password: Optional[str] = None
if pw_file_path is not None:
pw_file = pathlib.Path(pw_file_path).expanduser().absolute()
if not pw_file.exists():
raise config.error(
f"Password file '{pw_file}' does not exist")
self.password = pw_file.read_text().strip()
if pw_template is not None:
self.password = pw_template.render()
protocol = config.get('mqtt_protocol', "v3.1.1")
self.protocol = MQTT_PROTOCOLS.get(protocol, None)
if self.protocol is None:
raise config.error(
f"Invalid value '{protocol}' for option 'mqtt_protocol' "
"in section [mqtt]. Must be one of "
f"{MQTT_PROTOCOLS.values()}")
self.instance_name = config.get('instance_name', socket.gethostname())
if '+' in self.instance_name or '#' in self.instance_name:
raise config.error(
"Option 'instance_name' in section [mqtt] cannot "
"contain a wildcard.")
self.qos = config.getint("default_qos", 0)
if self.qos > 2 or self.qos < 0:
raise config.error(
"Option 'default_qos' in section [mqtt] must be "
"between 0 and 2")
self.publish_split_status = \
config.getboolean("publish_split_status", False)
self.client = ExtPahoClient(protocol=self.protocol)
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
self.client.on_publish = self._on_publish
self.client.on_subscribe = self._on_subscribe
self.client.on_unsubscribe = self._on_unsubscribe
self.connect_evt: asyncio.Event = asyncio.Event()
self.disconnect_evt: Optional[asyncio.Event] = None
self.connect_task: Optional[asyncio.Task] = None
self.subscribed_topics: SubscribedDict = {}
self.pending_responses: List[asyncio.Future] = []
self.pending_acks: Dict[int, asyncio.Future] = {}
self.server.register_endpoint(
"/server/mqtt/publish", ["POST"],
self._handle_publish_request,
transports=["http", "websocket", "internal"])
self.server.register_endpoint(
"/server/mqtt/subscribe", ["POST"],
self._handle_subscription_request,
transports=["http", "websocket", "internal"])
# Subscribe to API requests
self.json_rpc = JsonRPC(self.server, transport="MQTT")
self.api_request_topic = f"{self.instance_name}/moonraker/api/request"
self.api_resp_topic = f"{self.instance_name}/moonraker/api/response"
self.klipper_status_topic = f"{self.instance_name}/klipper/status"
self.klipper_state_prefix = f"{self.instance_name}/klipper/state"
self.moonraker_status_topic = f"{self.instance_name}/moonraker/status"
status_cfg: Dict[str, Any] = config.getdict("status_objects", {},
allow_empty_fields=True)
self.status_objs: Dict[str, Any] = {}
for key, val in status_cfg.items():
if val is not None:
self.status_objs[key] = [v.strip() for v in val.split(',')
if v.strip()]
else:
self.status_objs[key] = None
if status_cfg:
logging.debug(f"MQTT: Status Objects Set: {self.status_objs}")
self.server.register_event_handler(
"server:klippy_started", self._handle_klippy_started
)
self.timestamp_deque: Deque = deque(maxlen=20)
self.api_qos = config.getint('api_qos', self.qos)
if config.getboolean("enable_moonraker_api", True):
api_cache = self.server.register_api_transport("mqtt", self)
for api_def in api_cache.values():
if "mqtt" in api_def.supported_transports:
self.register_api_handler(api_def)
self.subscribe_topic(self.api_request_topic,
self._process_api_request,
self.api_qos)
self.server.register_remote_method("publish_mqtt_topic",
self._publish_from_klipper)
logging.info(
f"\nReserved MQTT topics:\n"
f"API Request: {self.api_request_topic}\n"
f"API Response: {self.api_resp_topic}\n"
f"Moonraker Status: {self.moonraker_status_topic}\n"
f"Klipper Status: {self.klipper_status_topic}")
async def component_init(self) -> None:
# We must wait for the IOLoop (asyncio event loop) to start
# prior to retrieving it
self.helper = AIOHelper(self.client)
if self.user_name is not None:
self.client.username_pw_set(self.user_name, self.password)
self.client.will_set(self.moonraker_status_topic,
payload=json.dumps({'server': 'offline'}),
qos=self.qos, retain=True)
self.client.connect_async(self.address, self.port)
self.connect_task = self.event_loop.create_task(
self._do_reconnect(first=True)
)
async def _handle_klippy_started(self, state: str) -> None:
if self.status_objs:
args = {'objects': self.status_objs}
try:
await self.klippy.request(
WebRequest("objects/subscribe", args, conn=self))
except self.server.error:
pass
def _on_message(self,
client: str,
user_data: Any,
message: paho_mqtt.MQTTMessage
) -> None:
topic = message.topic
if topic in self.subscribed_topics:
cb_hdls = self.subscribed_topics[topic][1]
for hdl in cb_hdls:
self.event_loop.register_callback(
hdl.callback, message.payload)
else:
logging.debug(
f"Unregistered MQTT Topic Received: {topic}, "
f"payload: {message.payload.decode()}")
def _on_connect(self,
client: paho_mqtt.Client,
user_data: Any,
flags: Dict[str, Any],
reason_code: Union[int, paho_mqtt.ReasonCodes],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
logging.info("MQTT Client Connected")
if reason_code == 0:
self.publish_topic(self.moonraker_status_topic,
{'server': 'online'}, retain=True)
subs = [(k, v[0]) for k, v in self.subscribed_topics.items()]
if subs:
res, msg_id = client.subscribe(subs)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
topics = list(self.subscribed_topics.keys())
sub_fut.add_done_callback(
BrokerAckLogger(topics, "subscribe"))
self.pending_acks[msg_id] = sub_fut
self.connect_evt.set()
self.server.send_event("mqtt:connected")
else:
if isinstance(reason_code, int):
err_str = paho_mqtt.connack_string(reason_code)
else:
err_str = reason_code.getName()
self.server.set_failed_component("mqtt")
self.server.add_warning(f"MQTT Connection Failed: {err_str}")
def _on_disconnect(self,
client: paho_mqtt.Client,
user_data: Any,
reason_code: int,
properties: Optional[paho_mqtt.Properties] = None
) -> None:
if self.disconnect_evt is not None:
self.disconnect_evt.set()
elif self.is_connected():
# The server connection was dropped, attempt to reconnect
logging.info("MQTT Server Disconnected, reason: "
f"{paho_mqtt.error_string(reason_code)}")
if self.connect_task is None:
self.connect_task = asyncio.create_task(self._do_reconnect())
self.server.send_event("mqtt:disconnected")
self.connect_evt.clear()
def _on_publish(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int
) -> None:
pub_fut = self.pending_acks.pop(msg_id, None)
if pub_fut is not None and not pub_fut.done():
pub_fut.set_result(None)
def _on_subscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
flex: Union[List[int], List[paho_mqtt.ReasonCodes]],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
sub_fut = self.pending_acks.pop(msg_id, None)
if sub_fut is not None and not sub_fut.done():
sub_fut.set_result(flex)
def _on_unsubscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
properties: Optional[paho_mqtt.Properties] = None,
reasoncodes: Optional[paho_mqtt.ReasonCodes] = None
) -> None:
unsub_fut = self.pending_acks.pop(msg_id, None)
if unsub_fut is not None and not unsub_fut.done():
unsub_fut.set_result(None)
async def _do_reconnect(self, first: bool = False) -> None:
logging.info("Attempting MQTT Connect/Reconnect")
last_err: Exception = Exception()
while True:
if not first:
try:
await asyncio.sleep(2.)
except asyncio.CancelledError:
raise
first = False
try:
sock = await self.event_loop.create_socket_connection(
(self.address, self.port), timeout=10
)
self.client.reconnect(sock)
except asyncio.CancelledError:
raise
except Exception as e:
if type(last_err) != type(e) or last_err.args != e.args:
logging.exception("MQTT Connection Error")
last_err = e
continue
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
break
self.connect_task = None
async def wait_connection(self, timeout: Optional[float] = None) -> bool:
try:
await asyncio.wait_for(self.connect_evt.wait(), timeout)
except asyncio.TimeoutError:
return False
return True
def is_connected(self) -> bool:
return self.connect_evt.is_set()
def subscribe_topic(self,
topic: str,
callback: FlexCallback,
qos: Optional[int] = None
) -> SubscriptionHandle:
if '#' in topic or '+' in topic:
raise self.server.error("Wildcards may not be used")
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
hdl = SubscriptionHandle(topic, callback)
sub_handles = [hdl]
need_sub = True
if topic in self.subscribed_topics:
prev_qos, sub_handles = self.subscribed_topics[topic]
qos = max(qos, prev_qos)
sub_handles.append(hdl)
need_sub = qos != prev_qos
self.subscribed_topics[topic] = (qos, sub_handles)
if self.is_connected() and need_sub:
res, msg_id = self.client.subscribe(topic, qos)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
sub_fut.add_done_callback(
BrokerAckLogger([topic], "subscribe"))
self.pending_acks[msg_id] = sub_fut
return hdl
def unsubscribe(self, hdl: SubscriptionHandle) -> None:
topic = hdl.topic
if topic in self.subscribed_topics:
sub_hdls = self.subscribed_topics[topic][1]
try:
sub_hdls.remove(hdl)
except Exception:
pass
if not sub_hdls:
del self.subscribed_topics[topic]
res, msg_id = self.client.unsubscribe(topic)
if msg_id is not None:
unsub_fut: asyncio.Future = asyncio.Future()
unsub_fut.add_done_callback(
BrokerAckLogger([topic], "unsubscribe"))
self.pending_acks[msg_id] = unsub_fut
def publish_topic(self,
topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False
) -> Awaitable[None]:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
pub_fut: asyncio.Future = asyncio.Future()
if isinstance(payload, (dict, list)):
try:
payload = json.dumps(payload)
except json.JSONDecodeError:
raise self.server.error(
"Dict or List is not json encodable") from None
elif isinstance(payload, bool):
payload = str(payload).lower()
try:
msg_info = self.client.publish(topic, payload, qos, retain)
if msg_info.is_published():
pub_fut.set_result(None)
else:
if qos == 0:
# There is no delivery guarantee for qos == 0, so
# it is possible that the on_publish event will
# not be called if paho mqtt encounters an error
# during publication. Return immediately as
# a workaround.
if msg_info.rc != paho_mqtt.MQTT_ERR_SUCCESS:
err_str = paho_mqtt.error_string(msg_info.rc)
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {err_str}", 503))
else:
pub_fut.set_result(None)
return pub_fut
self.pending_acks[msg_info.mid] = pub_fut
except ValueError:
pub_fut.set_exception(self.server.error(
"MQTT Message Queue Full", 529))
except Exception as e:
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {e}", 503))
return pub_fut
async def publish_topic_with_response(self,
topic: str,
response_topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False,
timeout: Optional[float] = None
) -> bytes:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
resp_fut: asyncio.Future = asyncio.Future()
resp_hdl = self.subscribe_topic(
response_topic, resp_fut.set_result, qos)
self.pending_responses.append(resp_fut)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
await asyncio.wait_for(resp_fut, timeout)
except asyncio.TimeoutError:
logging.info(f"Response to request {topic} timed out")
raise self.server.error("MQTT Request Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp_fut)
except Exception:
pass
self.unsubscribe(resp_hdl)
return resp_fut.result()
async def _handle_publish_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
payload: Any = web_request.get("payload", None)
qos: int = web_request.get_int("qos", self.qos)
retain: bool = web_request.get_boolean("retain", False)
timeout: Optional[float] = web_request.get_float('timeout', None)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
except asyncio.TimeoutError:
raise self.server.error("MQTT Publish Timed Out", 504)
return {
"topic": topic
}
async def _handle_subscription_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
qos: int = web_request.get_int("qos", self.qos)
timeout: Optional[float] = web_request.get_float('timeout', None)
resp: asyncio.Future = asyncio.Future()
hdl: Optional[SubscriptionHandle] = None
try:
hdl = self.subscribe_topic(topic, resp.set_result, qos)
self.pending_responses.append(resp)
await asyncio.wait_for(resp, timeout)
ret: bytes = resp.result()
except asyncio.TimeoutError:
raise self.server.error("MQTT Subscribe Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp)
except Exception:
pass
if hdl is not None:
self.unsubscribe(hdl)
try:
payload = json.loads(ret)
except json.JSONDecodeError:
payload = ret.decode()
return {
'topic': topic,
'payload': payload
}
async def _process_api_request(self, payload: bytes) -> None:
response = await self.json_rpc.dispatch(payload.decode())
if response is not None:
await self.publish_topic(self.api_resp_topic, response,
self.api_qos)
def register_api_handler(self, api_def: APIDefinition) -> None:
if api_def.callback is None:
# Remote API, uses RPC to reach out to Klippy
mqtt_method = api_def.jrpc_methods[0]
rpc_cb = self._generate_remote_callback(api_def.endpoint)
self.json_rpc.register_method(mqtt_method, rpc_cb)
else:
# Local API, uses local callback
for mqtt_method, req_method in \
zip(api_def.jrpc_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, api_def.callback)
self.json_rpc.register_method(mqtt_method, rpc_cb)
logging.info(
"Registering MQTT JSON-RPC methods: "
f"{', '.join(api_def.jrpc_methods)}")
def remove_api_handler(self, api_def: APIDefinition) -> None:
for jrpc_method in api_def.jrpc_methods:
self.json_rpc.remove_method(jrpc_method)
def _generate_local_callback(self,
endpoint: str,
request_method: str,
callback: Callable[[WebRequest], Coroutine]
) -> RPCCallback:
async def func(args: Dict[str, Any]) -> Any:
self._check_timestamp(args)
result = await callback(WebRequest(endpoint, args, request_method))
return result
return func
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
async def func(args: Dict[str, Any]) -> Any:
self._check_timestamp(args)
result = await self.klippy.request(WebRequest(endpoint, args))
return result
return func
def _check_timestamp(self, args: Dict[str, Any]) -> None:
ts = args.pop("mqtt_timestamp", None)
if ts is not None:
if ts in self.timestamp_deque:
logging.debug("Duplicate MQTT API request received")
raise self.server.error(
"Duplicate MQTT Request", DUP_API_REQ_CODE)
else:
self.timestamp_deque.append(ts)
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
if not status or not self.is_connected():
return
if self.publish_split_status:
for objkey in status:
objval = status[objkey]
for statekey in objval:
payload = {'eventtime': eventtime,
'value': objval[statekey]}
self.publish_topic(
f"{self.klipper_state_prefix}/{objkey}/{statekey}",
payload, retain=True)
else:
payload = {'eventtime': eventtime, 'status': status}
self.publish_topic(self.klipper_status_topic, payload)
def get_instance_name(self) -> str:
return self.instance_name
async def close(self) -> None:
if self.connect_task is not None:
self.connect_task.cancel()
self.connect_task = None
if not self.is_connected():
return
await self.publish_topic(self.moonraker_status_topic,
{'server': 'offline'},
retain=True)
self.disconnect_evt = asyncio.Event()
self.client.disconnect()
try:
await asyncio.wait_for(self.disconnect_evt.wait(), 2.)
except asyncio.TimeoutError:
logging.info("MQTT Disconnect Timeout")
futs = list(self.pending_acks.values())
futs.extend(self.pending_responses)
for fut in futs:
if fut.done():
continue
fut.set_exception(
self.server.error("Moonraker Shutdown", 503))
async def _publish_from_klipper(self,
topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False,
use_prefix: bool = False
) -> None:
if use_prefix:
topic = f"{self.instance_name}/{topic.lstrip('/')}"
await self.publish_topic(topic, payload, qos, retain)
def load_component(config: ConfigHelper) -> MQTTClient:
return MQTTClient(config)
+247
View File
@@ -0,0 +1,247 @@
# Notifier
#
# Copyright (C) 2022 Pataar <me@pataar.nl>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import apprise
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Dict,
Any,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .http_client import HttpClient
from .klippy_apis import KlippyAPI as APIComp
class Notifier:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.notifiers: Dict[str, NotifierInstance] = {}
self.events: Dict[str, NotifierEvent] = {}
prefix_sections = config.get_prefix_sections("notifier")
self.register_events(config)
self.register_remote_actions()
for section in prefix_sections:
cfg = config[section]
try:
notifier = NotifierInstance(cfg)
for event in self.events:
if event in notifier.events or "*" in notifier.events:
self.events[event].register_notifier(notifier)
logging.info(f"Registered notifier: '{notifier.get_name()}'")
except Exception as e:
msg = f"Failed to load notifier[{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
self.notifiers[notifier.get_name()] = notifier
self.register_endpoints(config)
def register_remote_actions(self):
self.server.register_remote_method("notify", self.notify_action)
async def notify_action(self, name: str, message: str = ""):
if name not in self.notifiers:
raise self.server.error(f"Notifier '{name}' not found", 404)
notifier = self.notifiers[name]
await notifier.notify("remote_action", [], message)
def register_events(self, config: ConfigHelper):
self.events["started"] = NotifierEvent(
"started",
"job_state:started",
config)
self.events["complete"] = NotifierEvent(
"complete",
"job_state:complete",
config)
self.events["error"] = NotifierEvent(
"error",
"job_state:error",
config)
self.events["cancelled"] = NotifierEvent(
"cancelled",
"job_state:cancelled",
config)
self.events["paused"] = NotifierEvent(
"paused",
"job_state:paused",
config)
self.events["resumed"] = NotifierEvent(
"resumed",
"job_state:resumed",
config)
def register_endpoints(self, config: ConfigHelper):
self.server.register_endpoint(
"/server/notifiers/list", ["GET"], self._handle_notifier_list
)
self.server.register_debug_endpoint(
"/debug/notifiers/test", ["POST"], self._handle_notifier_test
)
async def _handle_notifier_list(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"notifiers": self._list_notifiers()}
def _list_notifiers(self) -> List[Dict[str, Any]]:
return [notifier.as_dict() for notifier in self.notifiers.values()]
async def _handle_notifier_test(
self, web_request: WebRequest
) -> Dict[str, Any]:
name = web_request.get_str("name")
if name not in self.notifiers:
raise self.server.error(f"Notifier '{name}' not found", 404)
client: HttpClient = self.server.lookup_component("http_client")
notifier = self.notifiers[name]
kapis: APIComp = self.server.lookup_component('klippy_apis')
result: Dict[str, Any] = await kapis.query_objects(
{'print_stats': None}, default={})
print_stats = result.get('print_stats', {})
print_stats["filename"] = "notifier_test.gcode" # Mock the filename
await notifier.notify(notifier.events[0], [print_stats, print_stats])
return {
"status": "success",
"stats": print_stats
}
class NotifierEvent:
def __init__(self, identifier: str, event_name: str, config: ConfigHelper):
self.identifier = identifier
self.event_name = event_name
self.server = config.get_server()
self.notifiers: Dict[str, NotifierInstance] = {}
self.config = config
self.server.register_event_handler(self.event_name, self._handle)
def register_notifier(self, notifier: NotifierInstance):
self.notifiers[notifier.get_name()] = notifier
async def _handle(self, *args) -> None:
logging.info(f"'{self.identifier}' notifier event triggered'")
await self.invoke_notifiers(args)
async def invoke_notifiers(self, args):
for notifier_name in self.notifiers:
try:
notifier = self.notifiers[notifier_name]
await notifier.notify(self.identifier, args)
except Exception as e:
logging.info(f"Failed to notify [{notifier_name}]\n{e}")
continue
class NotifierInstance:
def __init__(self, config: ConfigHelper) -> None:
self.config = 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.apprise = apprise.Apprise()
self.warned = False
self.attach_requires_file_system_check = True
self.attach = config.get("attach", None)
if self.attach is None or \
(self.attach.startswith("http://") or
self.attach.startswith("https://")):
self.attach_requires_file_system_check = False
url_template = config.gettemplate('url')
self.url = url_template.render()
if len(self.url) < 2:
raise config.error(f"Invalid url for: {config.get_name()}")
self.title = config.gettemplate('title', None)
self.body = config.gettemplate("body", None)
self.events: List[str] = config.getlist("events", separator=",")
self.apprise.add(self.url)
def as_dict(self):
return {
"name": self.name,
"url": self.config.get("url"),
"title": self.config.get("title", None),
"body": self.config.get("body", None),
"events": self.events,
"attach": self.attach
}
async def notify(
self, event_name: str, event_args: List, message: str = ""
) -> None:
context = {
"event_name": event_name,
"event_args": event_args,
"event_message": message
}
rendered_title = (
'' if self.title is None else self.title.render(context)
)
rendered_body = (
event_name if self.body is None else self.body.render(context)
)
# Verify the attachment
if self.attach_requires_file_system_check and self.attach is not None:
fm = self.server.lookup_component("file_manager")
if not fm.can_access_path(self.attach):
if not self.warned:
self.server.add_warning(
f"Attachment of notifier '{self.name}' is not "
"valid. The location of the "
"attachment is not "
"accessible.")
self.warned = True
self.attach = None
await self.apprise.async_notify(
rendered_body.strip(),
rendered_title.strip(),
attach=self.attach
)
def get_name(self) -> str:
return self.name
def load_component(config: ConfigHelper) -> Notifier:
return Notifier(config)
+400
View File
@@ -0,0 +1,400 @@
# OctoPrint API compatibility
#
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI as APIComp
from .file_manager.file_manager import FileManager
from .job_queue import JobQueue
OCTO_VERSION = '1.5.0'
class OctoPrintCompat:
"""
Minimal implementation of the REST API as described here:
https://docs.octoprint.org/en/master/api/index.html
So that Cura OctoPrint plugin will function for:
* Handshake
* Upload gcode/ufp
* Webcam config
* Manual GCode submission
* Heater temperatures
"""
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.software_version = self.server.get_app_args().get(
'software_version')
self.enable_ufp: bool = config.getboolean('enable_ufp', True)
# Get webcam settings from config
self.webcam: Dict[str, Any] = {
'flipH': config.getboolean('flip_h', False),
'flipV': config.getboolean('flip_v', False),
'rotate90': config.getboolean('rotate_90', False),
'streamUrl': config.get('stream_url', '/webcam/?action=stream'),
'webcamEnabled': config.getboolean('webcam_enabled', True),
}
# Local variables
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
self.heaters: Dict[str, Dict[str, Any]] = {}
self.last_print_stats: Dict[str, Any] = {}
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
self.server.register_event_handler(
'server:status_update', self._handle_status_update)
# Version & Server information
self.server.register_endpoint(
'/api/version', ['GET'], self._get_version,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/server', ['GET'], self._get_server,
transports=['http'], wrap_result=False)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', ['POST'], self._post_login_user,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/currentuser', ['GET'], self._post_login_user,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/settings', ['GET'], self._get_settings,
transports=['http'], wrap_result=False)
# File operations
# Note that file upload is handled in file_manager.py
# TODO: List/info/select/delete files
# Job operations
self.server.register_endpoint(
'/api/job', ['GET'], self._get_job,
transports=['http'], wrap_result=False)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', ['GET'], self._get_printer,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', ['POST'], self._post_command,
transports=['http'], wrap_result=False)
# TODO: head/tool/bed/chamber specific read/issue
# Printer profiles
self.server.register_endpoint(
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
transports=['http'], wrap_result=False)
# Upload Handlers
self.server.register_upload_handler(
"/api/files/local", location_prefix="api/files/moonraker")
self.server.register_endpoint(
"/api/files/moonraker/(?P<relative_path>.+)", ['POST'],
self._select_file, transports=['http'], wrap_result=False)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self) -> None:
self.heaters = {}
# Fetch heaters
try:
result: Dict[str, Any]
sensors: List[str]
result = await self.klippy_apis.query_objects({'heaters': None})
sensors = result.get('heaters', {}).get('available_sensors', [])
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
sensors = []
# subscribe objects
sub: Dict[str, Any] = {s: None for s in sensors}
sub['print_stats'] = None
result = await self.klippy_apis.subscribe_objects(sub)
self.last_print_stats = result.get('print_stats', {})
if sensors:
self.heaters = {name: result.get(name, {}) for name in sensors}
def _handle_status_update(self, status: Dict[str, Any]) -> None:
if 'print_stats' in status:
self.last_print_stats.update(status['print_stats'])
for heater_name, data in self.heaters.items():
if heater_name in status:
data.update(status[heater_name])
def printer_state(self) -> str:
klippy_state = self.server.get_klippy_state()
if klippy_state in ["disconnected", "startup"]:
return 'Offline'
elif klippy_state != 'ready':
return 'Error'
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
def printer_temps(self) -> Dict[str, Any]:
temps: Dict[str, Any] = {}
for heater, data in self.heaters.items():
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
return temps
async def _get_version(self,
web_request: WebRequest
) -> Dict[str, str]:
"""
Version information
"""
return {
'server': OCTO_VERSION,
'api': '0.1',
'text': f'OctoPrint (Moonraker {self.software_version})',
}
async def _get_server(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Server status
"""
klippy_state = self.server.get_klippy_state()
return {
'server': OCTO_VERSION,
'safemode': (
None if klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Confirm session login.
Since we only support apikey auth, do nothing.
Report hardcoded user called _api
"""
return {
'_is_external_client': False,
'_login_mechanism': 'apikey',
'name': '_api',
'active': True,
'user': True,
'admin': True,
'apikey': None,
'permissions': [],
'groups': ['admins', 'users'],
}
async def _get_settings(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Used to parse OctoPrint capabilities
"""
settings = {
'plugins': {},
'feature': {
'sdSupport': False,
'temperatureGraph': False
},
'webcam': self.webcam,
}
if self.enable_ufp:
settings['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,
},
}
return settings
async def _get_job(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get current job status
"""
return {
'job': {
'file': {'name': None},
'estimatedPrintTime': None,
'filament': {'length': None},
'user': None,
},
'progress': {
'completion': None,
'filepos': None,
'printTime': None,
'printTimeLeft': None,
'printTimeOrigin': None,
},
'state': self.printer_state()
}
async def _get_printer(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer status
"""
state = self.printer_state()
return {
'temperature': self.printer_temps(),
'state': {
'text': state,
'flags': {
'operational': state not in ['Error', 'Offline'],
'paused': state == 'Paused',
'printing': state == 'Printing',
'cancelling': state == 'Cancelling',
'pausing': False,
'error': state == 'Error',
'ready': state == 'Operational',
'closedOrError': state in ['Error', 'Offline'],
},
},
}
async def _post_command(self,
web_request: WebRequest
) -> Dict:
"""
Request to run some gcode command
"""
commands: List[str] = web_request.get('commands', [])
for command in commands:
logging.info(f'Executing GCode: {command}')
try:
await self.klippy_apis.run_gcode(command)
except self.server.error:
msg = f"Error executing GCode {command}"
logging.exception(msg)
return {}
async def _get_printerprofiles(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer profiles
"""
return {
'profiles': {
'_default': {
'id': '_default',
'name': 'Default',
'color': 'default',
'model': 'Default',
'default': True,
'current': True,
'heatedBed': 'heater_bed' in self.heaters,
'heatedChamber': 'chamber' in self.heaters,
'axes': {
'x': {
'speed': 6000.,
'inverted': False
},
'y': {
'speed': 6000.,
'inverted': False
},
'z': {
'speed': 6000.,
'inverted': False
},
'e': {
'speed': 300.,
'inverted': False
}
}
}
}
}
async def _select_file(self,
web_request: WebRequest
) -> None:
command: str = web_request.get('command')
rel_path: str = web_request.get('relative_path')
root, filename = rel_path.strip("/").split("/", 1)
fmgr: FileManager = self.server.lookup_component('file_manager')
if command == "select":
start_print: bool = web_request.get('print', False)
if not start_print:
# No-op, selecting a file has no meaning in Moonraker
return
if root != "gcodes":
raise self.server.error(
"File must be located in the 'gcodes' root", 400)
if not fmgr.check_file_exists(root, filename):
raise self.server.error("File does not exist")
try:
ret = await self.klippy_apis.query_objects(
{'print_stats': None})
pstate: str = ret['print_stats']['state']
except self.server.error:
pstate = "not_avail"
started: bool = False
if pstate not in ["printing", "paused", "not_avail"]:
try:
await self.klippy_apis.start_print(filename)
except self.server.error:
started = False
else:
logging.debug(f"Job '{filename}' started via OctoPrint API")
started = True
if not started:
if fmgr.upload_queue_enabled():
job_queue: JobQueue = self.server.lookup_component(
'job_queue')
await job_queue.queue_job(filename, check_exists=False)
logging.debug(f"Job '{filename}' queued via OctoPrint API")
else:
raise self.server.error("Conflict", 409)
else:
raise self.server.error(f"Unsupported Command: {command}")
def load_component(config: ConfigHelper) -> OctoPrintCompat:
return OctoPrintCompat(config)
+839
View File
@@ -0,0 +1,839 @@
# PanelDue LCD display support
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import serial
import os
import time
import json
import errno
import logging
import asyncio
from collections import deque
from ..utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
List,
Callable,
Coroutine,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .klippy_apis import KlippyAPI as APIComp
from .file_manager.file_manager import FileManager as FMComp
FlexCallback = Callable[..., Optional[Coroutine]]
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
class PanelDueError(ServerError):
pass
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self,
config: ConfigHelper,
paneldue: PanelDue
) -> None:
self.event_loop = config.get_server().get_event_loop()
self.paneldue = paneldue
self.port: str = config.get('serial')
self.baud = config.getint('baud', 57600)
self.partial_input: bytes = b""
self.ser: Optional[serial.Serial] = None
self.fd: Optional[int] = None
self.connected: bool = False
self.send_busy: bool = False
self.send_buffer: bytes = b""
self.attempting_connect: bool = True
def disconnect(self, reconnect: bool = False) -> None:
if self.connected:
if self.fd is not None:
self.event_loop.remove_reader(self.fd)
self.fd = None
self.connected = False
if self.ser is not None:
self.ser.close()
self.ser = None
self.partial_input = b""
self.send_buffer = b""
self.paneldue.initialized = False
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.event_loop.delay_callback(1., self.connect)
async def connect(self) -> None:
self.attempting_connect = True
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info(f"Attempting to connect to: {self.port}")
try:
# XXX - sometimes the port cannot be exclusively locked, this
# would likely be due to a restart where the serial port was
# not correctly closed. Maybe don't use exclusive mode?
self.ser = serial.Serial(
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception(f"Unable to open port: {self.port}")
await asyncio.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
fd = self.fd = self.ser.fileno()
os.set_blocking(fd, False)
self.event_loop.add_reader(fd, self._handle_incoming)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self) -> None:
# Process incoming data using same method as gcode.py
if self.fd is None:
return
try:
data = os.read(self.fd, 4096)
except os.error:
return
if not data:
# possibly an error, disconnect
self.disconnect(reconnect=True)
logging.info("serial_display: No data received, disconnecting")
return
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
try:
decoded_line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(decoded_line)
except ServerError:
logging.exception(
f"GCode Processing Error: {decoded_line}")
self.paneldue.handle_gcode_response(
f"!! GCode Processing Error: {decoded_line}")
except Exception:
logging.exception("Error during gcode processing")
def send(self, data: bytes) -> None:
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.event_loop.register_callback(self._do_send)
async def _do_send(self) -> None:
assert self.fd is not None
while self.send_buffer:
if not self.connected:
break
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await asyncio.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect(reconnect=True)
return
self.send_busy = False
class PanelDue:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.event_loop = self.server.get_event_loop()
self.file_manager: FMComp = \
self.server.lookup_component('file_manager')
self.klippy_apis: APIComp = \
self.server.lookup_component('klippy_apis')
self.kinematics: str = "none"
self.machine_name = config.get('machine_name', "Klipper")
self.firmware_name: str = "Repetier | Klipper"
self.last_message: Optional[str] = None
self.last_gcode_response: Optional[str] = None
self.current_file: str = ""
self.file_metadata: Dict[str, Any] = {}
self.enable_checksum = config.getboolean('enable_checksum', True)
self.debug_queue: Deque[str] = deque(maxlen=100)
# Initialize tracked state.
self.printer_state: Dict[str, Dict[str, Any]] = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
self.extruder_count: int = 0
self.heaters: List[str] = []
self.is_ready: bool = False
self.is_shutdown: bool = False
self.initialized: bool = False
self.cq_busy: bool = False
self.gq_busy: bool = False
self.command_queue: List[Tuple[FlexCallback, Any, Any]] = []
self.gc_queue: List[str] = []
self.last_printer_state: str = 'O'
self.last_update_time: float = 0.
# Set up macros
self.confirmed_gcode: str = ""
self.mbox_sequence: int = 0
self.available_macros: Dict[str, str] = {}
self.confirmed_macros = {
"RESTART": "RESTART",
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
macros = config.getlist('macros', None)
if macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
self.available_macros = {m.split()[0]: m for m in macros}
conf_macros = config.getlist('confirmed_macros', None)
if conf_macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
self.available_macros.update(self.confirmed_macros)
self.non_trivial_keys = config.getlist('non_trivial_keys',
["Klipper state"])
self.ser_conn = SerialConnection(config, self)
logging.info("PanelDue Configured")
# Register server events
self.server.register_event_handler(
"server:klippy_ready", self._process_klippy_ready)
self.server.register_event_handler(
"server:klippy_shutdown", self._process_klippy_shutdown)
self.server.register_event_handler(
"server:klippy_disconnect", self._process_klippy_disconnect)
self.server.register_event_handler(
"server:status_update", self.handle_status_update)
self.server.register_event_handler(
"server:gcode_response", self.handle_gcode_response)
self.server.register_remote_method(
"paneldue_beep", self.paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes: Dict[str, FlexCallback] = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
'M408': self._run_paneldue_M408
}
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
'M25': lambda args: "PAUSE",
'M32': self._prepare_M32,
'M98': self._prepare_M98,
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
'M290': self._prepare_M290,
'M292': self._prepare_M292,
'M999': lambda args: "FIRMWARE_RESTART"
}
async def component_init(self) -> None:
await self.ser_conn.connect()
async def _process_klippy_ready(self) -> None:
# Request "info" and "configfile" status
retries = 10
printer_info: Dict[str, Any] = {}
cfg_status: Dict[str, Any] = {}
while retries:
try:
printer_info = await self.klippy_apis.get_klippy_info()
cfg_status = await self.klippy_apis.query_objects(
{'configfile': None})
except self.server.error:
logging.exception("PanelDue initialization request failed")
retries -= 1
if not retries:
raise
await asyncio.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + \
printer_info['software_version']
config: Dict[str, Any] = cfg_status.get(
'configfile', {}).get('config', {})
printer_cfg: Dict[str, Any] = config.get('printer', {})
self.kinematics = printer_cfg.get('kinematics', "none")
logging.info(
f"PanelDue Config Received:\n"
f"Firmware Name: {self.firmware_name}\n"
f"Kinematics: {self.kinematics}\n"
f"Printer Config: {config}\n")
# Initalize printer state and make subscription request
self.printer_state = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
sub_args = {k: None for k in self.printer_state.keys()}
self.extruder_count = 0
self.heaters = []
extruders = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
extruders.append(cfg)
sub_args[cfg] = None
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = None
extruders.sort()
self.heaters.extend(extruders)
try:
status: Dict[str, Any]
status = await self.klippy_apis.subscribe_objects(sub_args)
except self.server.error:
logging.exception("Unable to complete subscription request")
else:
self.printer_state.update(status)
self.is_shutdown = False
self.is_ready = True
def _process_klippy_shutdown(self) -> None:
self.is_shutdown = True
def _process_klippy_disconnect(self) -> None:
# Tell the PD that the printer is "off"
self.write_response({'status': 'O'})
self.last_printer_state = 'O'
self.is_shutdown = self.is_shutdown = False
def handle_status_update(self, status: Dict[str, Any]) -> None:
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
def paneldue_beep(self, frequency: int, duration: float) -> None:
duration = int(duration * 1000.)
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
def process_line(self, line: str) -> None:
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
self.event_loop.register_callback(self.klippy_apis.emergency_stop)
return
if self.enable_checksum:
# Get line number
line_index = line.find(' ')
try:
line_no: Optional[int] = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
script = line[line_index+1:cs_index]
else:
script = line
# Execute the gcode. Check for special RRF gcodes that
# require special handling
parts = script.split()
cmd = parts[0].strip()
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
arg = script[len(cmd):].strip()
parts = [cmd, arg]
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params: Dict[str, Any] = {}
for p in parts[1:]:
if p[0] not in "PSR":
params["arg_p"] = p.strip(" \"\t\n")
continue
arg = p[0].lower()
try:
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
except Exception:
msg = f"paneldue: Error parsing direct gcode {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params[f"arg_{arg}"] = val
func = self.direct_gcodes[cmd]
self.queue_command(func, **params)
return
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
sgc_func = self.special_gcodes[cmd]
script = sgc_func(parts[1:])
if not script:
return
self.queue_gcode(script)
def queue_gcode(self, script: str) -> None:
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.event_loop.register_callback(self._process_gcode_queue)
async def _process_gcode_queue(self) -> None:
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
if script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
else:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd: FlexCallback, *args, **kwargs) -> None:
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.event_loop.register_callback(self._process_command_queue)
async def _process_command_queue(self) -> None:
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if ret is not None:
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename: str) -> str:
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
# Remove initial "gcodes" folder. This is necessary
# due to the HACK in the paneldue_M20 gcode.
if filename.startswith("gcodes/"):
filename = filename[6:]
elif filename.startswith("/gcodes/"):
filename = filename[7:]
# Start with a "/" so the gcode parser can correctly
# handle files that begin with digits or special chars
if filename[0] != "/":
filename = "/" + filename
return filename
def _prepare_M23(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
def _prepare_M98(self, args: List[str]) -> str:
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
if cmd is None:
raise PanelDueError(f"Macro {macro} invalid")
if macro in self.confirmed_macros:
self._create_confirmation(macro, cmd)
cmd = ""
return cmd
def _prepare_M290(self, args: List[str]) -> str:
# args should in in the format Z0.02
offset = args[0][1:].strip()
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
def _prepare_M292(self, args: List[str]) -> str:
p_val = int(args[0][1])
if p_val == 0:
cmd = self.confirmed_gcode
self.confirmed_gcode = ""
return cmd
return ""
def _create_confirmation(self, name: str, gcode: str) -> None:
self.mbox_sequence += 1
self.confirmed_gcode = gcode
title = "Confirmation Dialog"
msg = f"Please confirm your intent to run {name}." \
" Press OK to continue, or CANCEL to abort."
mbox: Dict[str, Any] = {}
mbox['msgBox.mode'] = 3
mbox['msgBox.msg'] = msg
mbox['msgBox.seq'] = self.mbox_sequence
mbox['msgBox.title'] = title
mbox['msgBox.controls'] = 0
mbox['msgBox.timeout'] = 0
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response: str) -> None:
# Only queue up "non-trivial" gcode responses. At the
# moment we'll handle state changes and errors
if "Klipper state" in response \
or response.startswith('!!'):
self.last_gcode_response = response
else:
for key in self.non_trivial_keys:
if key in response:
self.last_gcode_response = response
return
def write_response(self, response: Dict[str, Any]) -> None:
byte_resp = json.dumps(response) + "\r\n"
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self) -> str:
# PanelDue States applicable to Klipper:
# I = idle, P = printing from SD, S = stopped (shutdown),
# C = starting up (not ready), A = paused, D = pausing,
# B = busy
if self.is_shutdown:
return 'S'
printer_state = self.printer_state
sd_state: str
sd_state = printer_state['print_stats'].get('state', "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
# Resuming
return 'R'
# Printing
return 'P'
elif sd_state == "paused":
p_active = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
if p_active and self.last_printer_state != 'A':
# Pausing
return 'D'
else:
# Paused
return 'A'
return 'I'
def _run_paneldue_M408(self,
arg_r: Optional[int] = None,
arg_s: int = 1
) -> None:
response: Dict[str, Any] = {}
sequence = arg_r
response_type = arg_s
curtime = self.event_loop.get_loop_time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
if not self.initialized:
response['dir'] = "/macros"
response['files'] = list(self.available_macros.keys())
self.initialized = True
if not self.is_ready:
self.last_printer_state = 'O'
response['status'] = self.last_printer_state
self.write_response(response)
return
if sequence is not None and self.last_gcode_response:
# Send gcode responses
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
response['firmwareName'] = self.firmware_name
response['numTools'] = self.extruder_count
response['geometry'] = self.kinematics
response['axes'] = 3
p_state = self.printer_state
self.last_printer_state = self._get_printer_status()
response['status'] = self.last_printer_state
response['babystep'] = round(p_state['gcode_move'].get(
'homing_origin', [0., 0., 0., 0.])[2], 3)
# Current position
pos: List[float]
homed_pos: str
sfactor: float
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
response['homed'] = [int(a in homed_pos) for a in "xyz"]
sfactor = round(p_state['gcode_move'].get('speed_factor', 1.) * 100, 2)
response['sfactor'] = sfactor
# Print Progress Tracking
sd_status = p_state['virtual_sdcard']
print_stats = p_state['print_stats']
fname: str = print_stats.get('filename', "")
sd_print_state: Optional[str] = print_stats.get('state')
if sd_print_state in ['printing', 'paused']:
# We know a file has been loaded, initialize metadata
if self.current_file != fname:
self.current_file = fname
self.file_metadata = self.file_manager.get_file_metadata(fname)
progress: float = sd_status.get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time: float = self.file_metadata.get('estimated_time', 0)
if est_time > MIN_EST_TIME:
# file read estimate
times_left = [int(est_time - est_time * progress)]
# filament estimate
est_total_fil: Optional[float]
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament: float = print_stats.get(
'filament_used', 0.)
fpct = min(1., cur_filament / est_total_fil)
times_left.append(int(est_time - est_time * fpct))
# object height estimate
obj_height: Optional[float]
obj_height = self.file_metadata.get('object_height')
if obj_height:
cur_height: float = p_state['gcode_move'].get(
'gcode_position', [0., 0., 0., 0.])[2]
hpct = min(1., cur_height / obj_height)
times_left.append(int(est_time - est_time * hpct))
else:
# The estimated time is not in the metadata, however we
# can still provide an estimate based on file progress
duration: float = print_stats.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
# clear filename and metadata
self.current_file = ""
self.file_metadata = {}
fan_speed: Optional[float] = p_state['fan'].get('speed')
if fan_speed is not None:
response['fanPercent'] = [round(fan_speed * 100, 1)]
extruder_name: str = ""
if self.extruder_count > 0:
extruder_name = p_state['toolhead'].get('extruder', "")
if extruder_name:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor: float = round(p_state['gcode_move'].get(
'extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp: float = round(p_state[name].get('temperature', 0.0), 1)
target: float = round(p_state[name].get('target', 0.0), 1)
response.setdefault('heaters', []).append(temp)
response.setdefault('active', []).append(target)
response.setdefault('standby', []).append(target)
if name.startswith('extruder'):
a_stat = 2 if name == extruder_name else 1
response.setdefault('hstat', []).append(a_stat if target else 0)
response.setdefault('efactor', []).append(efactor)
response.setdefault('extr', []).append(round(pos[3], 2))
else:
response.setdefault('hstat', []).append(2 if target else 0)
# Display message (via M117)
msg: str = p_state['display_status'].get('message', "")
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
self.write_response(response)
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
response_type = arg_s
if response_type != 2:
logging.info(
f"Cannot process response type {response_type} in M20")
return
path = arg_p
# Strip quotes if they exist
path = path.strip('\"')
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
# repetier compatibility enabled, the default folder is root,
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response: Dict[str, Any] = {'dir': path}
response['files'] = []
if path == "/macros":
response['files'] = list(self.available_macros.keys())
else:
# HACK: The PanelDue has a bug where it does not correctly detect
# subdirectories if we return the root as "/". Moonraker can
# support a "gcodes" directory, however we must choose between this
# support or disabling RRF specific gcodes (this is done by
# identifying as Repetier).
# The workaround below converts both "/" and "/gcodes" paths to
# "gcodes".
if path == "/":
response['dir'] = "/gcodes"
path = "gcodes"
elif path.startswith("/gcodes"):
path = path[1:]
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
self.write_response(response)
async def _run_paneldue_M30(self, arg_p: str = "") -> None:
# Delete a file. Clean up the file name and make sure
# it is relative to the "gcodes" root.
path = arg_p
path = path.strip('\"')
if path.startswith("0:/"):
path = path[3:]
elif path[0] == "/":
path = path[1:]
if not path.startswith("gcodes/"):
path = "gcodes/" + path
await self.file_manager.delete_file(path)
def _run_paneldue_M36(self, arg_p: Optional[str] = None) -> None:
response: Dict[str, Any] = {}
filename: Optional[str] = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
print_stats = self.printer_state.get('print_stats', {})
if filename is None:
# PanelDue is requesting file information on a
# currently printed file
active = False
if sd_status and print_stats:
filename = print_stats['filename']
active = sd_status['is_active']
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
# indicates Moonraker supports a "gcodes" directory.
if filename[0] == "/":
filename = filename[1:]
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata: Dict[str, Any] = \
self.file_manager.get_file_metadata(filename)
if metadata:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + time.ctime(metadata['modified'])
slicer: Optional[str] = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height: Optional[float] = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height: Optional[float] = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament: Optional[float] = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time: Optional[float] = metadata.get('estimated_time')
if est_time is not None:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
self.write_response(response)
def close(self) -> None:
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
msg += f"\nSequence {i}: {gc}"
logging.debug(msg)
def load_component(config: ConfigHelper) -> PanelDue:
return PanelDue(config)
File diff suppressed because it is too large. Load diff
+342
View File
@@ -0,0 +1,342 @@
# Moonraker Process Stat Tracking
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import time
import re
import os
import pathlib
import logging
from collections import deque
# Annotation imports
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Deque,
Any,
List,
Tuple,
Optional,
Dict,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest, WebsocketManager
from . import shell_command
STAT_CALLBACK = Callable[[int], Optional[Awaitable]]
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
NET_DEV_PATH = "/proc/net/dev"
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
CPU_STAT_PATH = "/proc/stat"
MEM_AVAIL_PATH = "/proc/meminfo"
STAT_UPDATE_TIME = 1.
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
WATCHDOG_REFRESH_TIME = 2.
REPORT_BLOCKED_TIME = 4.
THROTTLED_FLAGS = {
1: "Under-Voltage Detected",
1 << 1: "Frequency Capped",
1 << 2: "Currently Throttled",
1 << 3: "Temperature Limit Active",
1 << 16: "Previously Under-Volted",
1 << 17: "Previously Frequency Capped",
1 << 18: "Previously Throttled",
1 << 19: "Previously Temperature Limited"
}
class ProcStats:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.event_loop = self.server.get_event_loop()
self.watchdog = Watchdog(self)
self.stat_update_timer = self.event_loop.register_timer(
self._handle_stat_update)
self.vcgencmd: Optional[shell_command.ShellCommand] = None
if os.path.exists(VC_GEN_CMD_FILE):
logging.info("Detected 'vcgencmd', throttle checking enabled")
shell_cmd: shell_command.ShellCommandFactory
shell_cmd = self.server.load_component(config, "shell_command")
self.vcgencmd = shell_cmd.build_shell_command(
"vcgencmd get_throttled")
self.server.register_notification("proc_stats:cpu_throttled")
else:
logging.info("Unable to find 'vcgencmd', throttle checking "
"disabled")
self.temp_file = pathlib.Path(TEMPERATURE_PATH)
self.smaps = pathlib.Path(STATM_FILE_PATH)
self.netdev_file = pathlib.Path(NET_DEV_PATH)
self.cpu_stats_file = pathlib.Path(CPU_STAT_PATH)
self.meminfo_file = pathlib.Path(MEM_AVAIL_PATH)
self.server.register_endpoint(
"/machine/proc_stats", ["GET"], self._handle_stat_request)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_notification("proc_stats:proc_stat_update")
self.proc_stat_queue: Deque[Dict[str, Any]] = deque(maxlen=30)
self.last_update_time = time.time()
self.last_proc_time = time.process_time()
self.throttle_check_lock = asyncio.Lock()
self.total_throttled: int = 0
self.last_throttled: int = 0
self.update_sequence: int = 0
self.last_net_stats: Dict[str, Dict[str, Any]] = {}
self.last_cpu_stats: Dict[str, Tuple[int, int]] = {}
self.cpu_usage: Dict[str, float] = {}
self.memory_usage: Dict[str, int] = {}
self.stat_callbacks: List[STAT_CALLBACK] = []
async def component_init(self) -> None:
self.stat_update_timer.start()
self.watchdog.start()
def register_stat_callback(self, callback: STAT_CALLBACK) -> None:
self.stat_callbacks.append(callback)
async def _handle_stat_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
ts: Optional[Dict[str, Any]] = None
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cpu_temp = await self.event_loop.run_in_thread(
self._get_cpu_temperature)
wsm: WebsocketManager = self.server.lookup_component("websockets")
websocket_count = wsm.get_count()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts,
'cpu_temp': cpu_temp,
'network': self.last_net_stats,
'system_cpu_usage': self.cpu_usage,
'system_uptime': time.clock_gettime(time.CLOCK_BOOTTIME),
'system_memory': self.memory_usage,
'websocket_connections': websocket_count
}
async def _handle_shutdown(self) -> None:
msg = "\nMoonraker System Usage Statistics:"
for stats in self.proc_stat_queue:
msg += f"\n{self._format_stats(stats)}"
cpu_temp = await self.event_loop.run_in_thread(
self._get_cpu_temperature)
msg += f"\nCPU Temperature: {cpu_temp}"
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, eventtime: float) -> float:
update_time = eventtime
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)
cpu_temp, mem, mem_units, net = (
await self.event_loop.run_in_thread(self._read_system_files)
)
for dev in net:
bytes_sec = 0.
if dev in self.last_net_stats:
last_dev_stats = self.last_net_stats[dev]
cur_total: int = net[dev]['rx_bytes'] + net[dev]['tx_bytes']
last_total: int = last_dev_stats['rx_bytes'] + \
last_dev_stats['tx_bytes']
bytes_sec = round((cur_total - last_total) / time_diff, 2)
net[dev]['bandwidth'] = bytes_sec
self.last_net_stats = net
result = {
'time': time.time(),
'cpu_usage': usage,
'memory': mem,
'mem_units': mem_units
}
self.proc_stat_queue.append(result)
wsm: WebsocketManager = self.server.lookup_component("websockets")
websocket_count = wsm.get_count()
self.server.send_event("proc_stats:proc_stat_update", {
'moonraker_stats': result,
'cpu_temp': cpu_temp,
'network': net,
'system_cpu_usage': self.cpu_usage,
'system_memory': self.memory_usage,
'websocket_connections': websocket_count
})
if not self.update_sequence % THROTTLE_CHECK_INTERVAL:
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cur_throttled = ts['bits']
if cur_throttled & ~self.total_throttled:
self.server.add_log_rollover_item(
'throttled', f"CPU Throttled Flags: {ts['flags']}")
if cur_throttled != self.last_throttled:
self.server.send_event("proc_stats:cpu_throttled", ts)
self.last_throttled = cur_throttled
self.total_throttled |= cur_throttled
for cb in self.stat_callbacks:
ret = cb(self.update_sequence)
if ret is not None:
await ret
self.last_update_time = update_time
self.last_proc_time = proc_time
self.update_sequence += 1
return eventtime + STAT_UPDATE_TIME
async def _check_throttled_state(self) -> Dict[str, Any]:
async with self.throttle_check_lock:
assert self.vcgencmd is not None
try:
resp = await self.vcgencmd.run_with_response(
timeout=.5, log_complete=False)
ts = int(resp.strip().split("=")[-1], 16)
except Exception:
return {'bits': 0, 'flags': ["?"]}
flags = []
for flag, desc in THROTTLED_FLAGS.items():
if flag & ts:
flags.append(desc)
return {'bits': ts, 'flags': flags}
def _read_system_files(self) -> Tuple:
mem, units = self._get_memory_usage()
temp = self._get_cpu_temperature()
net_stats = self._get_net_stats()
self._update_cpu_stats()
self._update_system_memory()
return temp, mem, units, net_stats
def _get_memory_usage(self) -> Tuple[Optional[int], Optional[str]]:
try:
mem_data = self.smaps.read_text()
rss_match = re.search(r"Rss:\s+(\d+)\s+(\w+)", mem_data)
if rss_match is None:
return None, None
mem = int(rss_match.group(1))
units = rss_match.group(2)
except Exception:
return None, None
return mem, units
def _get_cpu_temperature(self) -> Optional[float]:
try:
res = int(self.temp_file.read_text().strip())
temp = res / 1000.
except Exception:
return None
return temp
def _get_net_stats(self) -> Dict[str, Any]:
net_stats: Dict[str, Any] = {}
try:
ret = self.netdev_file.read_text()
dev_info = re.findall(r"([\w]+):(.+)", ret)
for (dev_name, stats) in dev_info:
parsed_stats = stats.strip().split()
net_stats[dev_name] = {
'rx_bytes': int(parsed_stats[0]),
'tx_bytes': int(parsed_stats[8]),
'rx_packets': int(parsed_stats[1]),
'tx_packets': int(parsed_stats[9]),
'rx_errs': int(parsed_stats[2]),
'tx_errs': int(parsed_stats[10]),
'rx_drop': int(parsed_stats[3]),
'tx_drop': int(parsed_stats[11])
}
return net_stats
except Exception:
return {}
def _update_system_memory(self) -> None:
mem_stats: Dict[str, Any] = {}
try:
ret = self.meminfo_file.read_text()
total_match = re.search(r"MemTotal:\s+(\d+)", ret)
avail_match = re.search(r"MemAvailable:\s+(\d+)", ret)
if total_match is not None and avail_match is not None:
mem_stats["total"] = int(total_match.group(1))
mem_stats["available"] = int(avail_match.group(1))
mem_stats["used"] = mem_stats["total"] - mem_stats["available"]
self.memory_usage.update(mem_stats)
except Exception:
pass
def _update_cpu_stats(self) -> None:
try:
cpu_usage: Dict[str, Any] = {}
ret = self.cpu_stats_file.read_text()
usage_info: List[str] = re.findall(r"cpu[^\n]+", ret)
for cpu in usage_info:
parts = cpu.split()
name = parts[0]
cpu_sum = sum([int(t) for t in parts[1:]])
cpu_idle = int(parts[4])
if name in self.last_cpu_stats:
last_sum, last_idle = self.last_cpu_stats[name]
cpu_delta = cpu_sum - last_sum
idle_delta = cpu_idle - last_idle
cpu_used = cpu_delta - idle_delta
cpu_usage[name] = round(
100 * (cpu_used / cpu_delta), 2)
self.cpu_usage = cpu_usage
self.last_cpu_stats[name] = (cpu_sum, cpu_idle)
except Exception:
pass
def _format_stats(self, stats: Dict[str, Any]) -> str:
return f"System Time: {stats['time']:2f}, " \
f"Usage: {stats['cpu_usage']}%, " \
f"Memory: {stats['memory']} {stats['mem_units']}"
def log_last_stats(self, count: int = 1):
count = min(len(self.proc_stat_queue), count)
msg = ""
for stats in list(self.proc_stat_queue)[-count:]:
msg += f"\n{self._format_stats(stats)}"
logging.info(msg)
def close(self) -> None:
self.stat_update_timer.stop()
self.watchdog.stop()
class Watchdog:
def __init__(self, proc_stats: ProcStats) -> None:
self.proc_stats = proc_stats
self.event_loop = proc_stats.event_loop
self.blocked_count: int = 0
self.last_watch_time: float = 0.
self.watchdog_timer = self.event_loop.register_timer(
self._watchdog_callback
)
def _watchdog_callback(self, eventtime: float) -> float:
time_diff = eventtime - self.last_watch_time
if time_diff > REPORT_BLOCKED_TIME:
self.blocked_count += 1
logging.info(
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds"
f", total blocked count: {self.blocked_count}")
# delay the stat logging so we capture the CPU percentage after
# the next cycle
self.event_loop.delay_callback(
.2, self.proc_stats.log_last_stats, 5)
self.last_watch_time = eventtime
return eventtime + WATCHDOG_REFRESH_TIME
def start(self):
if not self.watchdog_timer.is_running():
self.last_watch_time = self.event_loop.get_loop_time()
self.watchdog_timer.start()
def stop(self):
self.watchdog_timer.stop()
def load_component(config: ConfigHelper) -> ProcStats:
return ProcStats(config)
+91
View File
@@ -0,0 +1,91 @@
# Support for password/token secrets
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import pathlib
import logging
import configparser
import json
from typing import (
TYPE_CHECKING,
Dict,
Optional,
Any
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .file_manager.file_manager import FileManager
class Secrets:
def __init__(self, config: ConfigHelper) -> None:
server = config.get_server()
self.secrets_file: Optional[pathlib.Path] = None
path: Optional[str] = config.get("secrets_path", None, deprecate=True)
app_args = server.get_app_args()
data_path = app_args["data_path"]
fpath = pathlib.Path(data_path).joinpath("moonraker.secrets")
if not fpath.is_file() and path is not None:
fpath = pathlib.Path(path).expanduser().resolve()
self.type = "invalid"
self.values: Dict[str, Any] = {}
fm: FileManager = server.lookup_component("file_manager")
fm.add_reserved_path("secrets", fpath, False)
if fpath.is_file():
self.secrets_file = fpath
data = self.secrets_file.read_text()
vals = self._parse_json(data)
if vals is not None:
if not isinstance(vals, dict):
server.add_warning(
f"[secrets]: option 'secrets_path', top level item in"
f" json file '{self.secrets_file}' must be an Object.")
return
self.values = vals
self.type = "json"
else:
vals = self._parse_ini(data)
if vals is None:
server.add_warning(
"[secrets]: option 'secrets_path', invalid file "
f"format, must be json or ini: '{self.secrets_file}'")
return
self.values = vals
self.type = "ini"
logging.debug(f"[secrets]: Loaded {self.type} file: "
f"{self.secrets_file}")
elif path is not None:
server.add_warning(
"[secrets]: option 'secrets_path', file does not exist: "
f"'{self.secrets_file}'")
else:
logging.debug(
"[secrets]: Option `secrets_path` not supplied")
def _parse_ini(self, data: str) -> Optional[Dict[str, Any]]:
try:
cfg = configparser.ConfigParser(interpolation=None)
cfg.read_string(data)
return {sec: dict(cfg.items(sec)) for sec in cfg.sections()}
except Exception:
return None
def _parse_json(self, data: str) -> Optional[Dict[str, Any]]:
try:
return json.loads(data)
except json.JSONDecodeError:
return None
def get_type(self) -> str:
return self.type
def __getitem__(self, key: str) -> Any:
return self.values[key]
def get(self, key: str, default: Any = None) -> Any:
return self.values.get(key, default)
def load_component(config: ConfigHelper) -> Secrets:
return Secrets(config)
+304
View File
@@ -0,0 +1,304 @@
# Generic sensor support
#
# Copyright (C) 2022 Morton Jonuschat <mjonuschat+moonraker@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Component to read additional generic sensor data and make it
# available to clients
from __future__ import annotations
import logging
from collections import defaultdict, deque
from dataclasses import dataclass, replace
from functools import partial
# Annotation imports
from typing import (
Any,
DefaultDict,
Deque,
Dict,
List,
Optional,
Type,
TYPE_CHECKING,
Union,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .mqtt import MQTTClient
SENSOR_UPDATE_TIME = 1.0
SENSOR_EVENT_NAME = "sensors:sensor_update"
@dataclass(frozen=True)
class SensorConfiguration:
id: str
name: str
type: str
source: str = ""
def _set_result(
name: str, value: Union[int, float], store: Dict[str, Union[int, float]]
) -> None:
if not isinstance(value, (int, float)):
store[name] = float(value)
else:
store[name] = value
@dataclass(frozen=True)
class Sensor:
config: SensorConfiguration
values: Dict[str, Deque[Union[int, float]]]
class BaseSensor:
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200) -> None:
self.server = cfg.get_server()
self.error_state: Optional[str] = None
self.config = SensorConfiguration(
id=name,
type=cfg.get("type"),
name=cfg.get("name", name),
)
self.last_measurements: Dict[str, Union[int, float]] = {}
self.last_value: Dict[str, Union[int, float]] = {}
self.values: DefaultDict[str, Deque[Union[int, float]]] = defaultdict(
lambda: deque(maxlen=store_size)
)
def _update_sensor_value(self, eventtime: float) -> None:
"""
Append the last updated value to the store.
"""
for key, value in self.last_measurements.items():
self.values[key].append(value)
# Copy the last measurements data
self.last_value = {**self.last_measurements}
async def initialize(self) -> bool:
"""
Sensor initialization executed on Moonraker startup.
"""
logging.info("Registered sensor '%s'", self.config.name)
return True
def get_sensor_info(self) -> Dict[str, Any]:
return {
"id": self.config.id,
"friendly_name": self.config.name,
"type": self.config.type,
"values": self.last_measurements,
}
def get_sensor_measurements(self) -> Dict[str, List[Union[int, float]]]:
return {key: list(values) for key, values in self.values.items()}
def get_name(self) -> str:
return self.config.name
def close(self) -> None:
pass
class MQTTSensor(BaseSensor):
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200):
super().__init__(name=name, cfg=cfg)
self.mqtt: MQTTClient = self.server.load_component(cfg, "mqtt")
self.state_topic: str = cfg.get("state_topic")
self.state_response = cfg.load_template("state_response_template", "{payload}")
self.config = replace(self.config, source=self.state_topic)
self.qos: Optional[int] = cfg.getint("qos", None, minval=0, maxval=2)
self.server.register_event_handler(
"mqtt:disconnected", self._on_mqtt_disconnected
)
def _on_state_update(self, payload: bytes) -> None:
measurements: Dict[str, Union[int, float]] = {}
context = {
"payload": payload.decode(),
"set_result": partial(_set_result, store=measurements),
}
try:
self.state_response.render(context)
except Exception as e:
logging.error("Error updating sensor results: %s", e)
self.error_state = str(e)
else:
self.error_state = None
self.last_measurements = measurements
logging.debug(
"Received updated sensor value for %s: %s",
self.config.name,
self.last_measurements,
)
async def _on_mqtt_disconnected(self):
self.error_state = "MQTT Disconnected"
self.last_measurements = {}
async def initialize(self) -> bool:
await super().initialize()
try:
self.mqtt.subscribe_topic(
self.state_topic,
self._on_state_update,
self.qos,
)
self.error_state = None
return True
except Exception as e:
self.error_state = str(e)
return False
class Sensors:
__sensor_types: Dict[str, Type[BaseSensor]] = {"MQTT": MQTTSensor}
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.store_size = config.getint("sensor_store_size", 1200)
prefix_sections = config.get_prefix_sections("sensor")
self.sensors: Dict[str, BaseSensor] = {}
# Register timer to update sensor values in store
self.sensors_update_timer = self.server.get_event_loop().register_timer(
self._update_sensor_values
)
# Register endpoints
self.server.register_endpoint(
"/server/sensors/list",
["GET"],
self._handle_sensor_list_request,
)
self.server.register_endpoint(
"/server/sensors/info",
["GET"],
self._handle_sensor_info_request,
)
self.server.register_endpoint(
"/server/sensors/measurements",
["GET"],
self._handle_sensor_measurements_request,
)
# Register notifications
self.server.register_notification(SENSOR_EVENT_NAME)
for section in prefix_sections:
cfg = config[section]
try:
try:
_, name = cfg.get_name().split(maxsplit=1)
except ValueError:
raise cfg.error(f"Invalid section name: {cfg.get_name()}")
logging.info(f"Configuring sensor: {name}")
sensor_type: str = cfg.get("type")
sensor_class: Optional[Type[BaseSensor]] = self.__sensor_types.get(
sensor_type.upper(), None
)
if sensor_class is None:
raise config.error(f"Unsupported sensor type: {sensor_type}")
self.sensors[name] = sensor_class(
name=name,
cfg=cfg,
store_size=self.store_size,
)
except Exception as e:
# Ensures that configuration errors are shown to the user
self.server.add_warning(
f"Failed to configure sensor [{cfg.get_name()}]\n{e}"
)
continue
def _update_sensor_values(self, eventtime: float) -> float:
"""
Iterate through the sensors and store the last updated value.
"""
changed_data: Dict[str, Dict[str, Union[int, float]]] = {}
for sensor_name, sensor in self.sensors.items():
base_value = sensor.last_value
sensor._update_sensor_value(eventtime=eventtime)
# Notify if a change in sensor values was detected
if base_value != sensor.last_value:
changed_data[sensor_name] = sensor.last_value
if changed_data:
self.server.send_event(SENSOR_EVENT_NAME, changed_data)
return eventtime + SENSOR_UPDATE_TIME
async def component_init(self) -> None:
try:
logging.debug("Initializing sensor component")
for sensor in self.sensors.values():
if not await sensor.initialize():
self.server.add_warning(
f"Sensor '{sensor.get_name()}' failed to initialize"
)
self.sensors_update_timer.start()
except Exception as e:
logging.exception(e)
async def _handle_sensor_list_request(
self, web_request: WebRequest
) -> Dict[str, Dict[str, Any]]:
output = {
"sensors": {
key: sensor.get_sensor_info() for key, sensor in self.sensors.items()
}
}
return output
async def _handle_sensor_info_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
sensor_name: str = web_request.get_str("sensor")
if sensor_name not in self.sensors:
raise self.server.error(f"No valid sensor named {sensor_name}")
sensor = self.sensors[sensor_name]
return sensor.get_sensor_info()
async def _handle_sensor_measurements_request(
self, web_request: WebRequest
) -> Dict[str, Dict[str, Any]]:
sensor_name: str = web_request.get_str("sensor", "")
if sensor_name and sensor_name not in self.sensors:
raise self.server.error(f"No valid sensor named {sensor_name}")
output = {
key: sensor.get_sensor_measurements()
for key, sensor in self.sensors.items()
if sensor_name is "" or key == sensor_name
}
return output
def close(self) -> None:
self.sensors_update_timer.stop()
for sensor in self.sensors.values():
sensor.close()
def load_component(config: ConfigHelper) -> Sensors:
return Sensors(config)
+397
View File
@@ -0,0 +1,397 @@
# linux shell command execution utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import shlex
import logging
import signal
import asyncio
from ..utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Awaitable,
List,
Optional,
Callable,
Coroutine,
Dict,
Set,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
OutputCallback = Optional[Callable[[bytes], None]]
class ShellCommandError(ServerError):
def __init__(
self,
message: str,
return_code: Optional[int],
stdout: Optional[bytes] = b"",
stderr: Optional[bytes] = b"",
status_code: int = 500
) -> None:
super().__init__(message, status_code=status_code)
self.stdout = stdout or b""
self.stderr = stderr or b""
self.return_code = return_code
class ShellCommandProtocol(asyncio.subprocess.SubprocessStreamProtocol):
def __init__(
self,
limit: int,
loop: asyncio.events.AbstractEventLoop,
program_name: str = "",
std_out_cb: OutputCallback = None,
std_err_cb: OutputCallback = None,
log_stderr: bool = False
) -> None:
self._loop = loop
self._pipe_fds: List[int] = []
super().__init__(limit, loop)
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.pending_data: List[bytes] = [b"", b""]
def connection_made(
self, transport: asyncio.transports.BaseTransport
) -> None:
self._transport = transport
assert isinstance(transport, asyncio.SubprocessTransport)
stdout_transport = transport.get_pipe_transport(1)
if stdout_transport is not None:
self._pipe_fds.append(1)
stderr_transport = transport.get_pipe_transport(2)
if stderr_transport is not None:
self._pipe_fds.append(2)
stdin_transport = transport.get_pipe_transport(0)
if stdin_transport is not None:
self.stdin = asyncio.streams.StreamWriter(
stdin_transport, # type: ignore
protocol=self,
reader=None,
loop=self._loop
)
def pipe_data_received(self, fd: int, data: bytes | str) -> None:
cb = None
data_idx = fd - 1
if fd == 1:
cb = self.std_out_cb
elif fd == 2:
cb = self.std_err_cb
if self.log_stderr:
if isinstance(data, bytes):
msg = data.decode(errors='ignore')
else:
msg = data
logging.info(f"{self.program_name}: {msg}")
if cb is not None:
if isinstance(data, str):
data = data.encode()
lines = data.split(b'\n')
lines[0] = self.pending_data[data_idx] + lines[0]
self.pending_data[data_idx] = lines.pop()
for line in lines:
if not line:
continue
cb(line)
def pipe_connection_lost(
self, fd: int, exc: Exception | None
) -> None:
cb = None
pending = b""
if fd == 1:
cb = self.std_out_cb
pending = self.pending_data[0]
elif fd == 2:
cb = self.std_err_cb
pending = self.pending_data[1]
if pending and cb is not None:
cb(pending)
super().pipe_connection_lost(fd, exc)
class ShellCommand:
IDX_SIGINT = 0
IDX_SIGTERM = 1
IDX_SIGKILL = 2
def __init__(
self,
factory: ShellCommandFactory,
cmd: str,
std_out_callback: OutputCallback,
std_err_callback: OutputCallback,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> None:
self.factory = factory
self.name = cmd
self.std_out_cb = std_out_callback
self.std_err_cb = std_err_callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.log_stderr = log_stderr
self.env = env
self.cwd = cwd
self.proc: Optional[asyncio.subprocess.Process] = None
self.cancelled = False
self.return_code: Optional[int] = None
self.run_lock = asyncio.Lock()
async def cancel(self, sig_idx: int = 1) -> None:
if self.cancelled:
return
self.cancelled = True
if self.proc is not None:
exit_success = False
sig_idx = min(2, max(0, sig_idx))
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
for sig in sigs:
try:
self.proc.send_signal(sig)
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=2.)
except asyncio.TimeoutError:
continue
except ProcessLookupError:
pass
logging.debug(f"Command '{self.name}' exited with "
f"signal: {sig.name}")
exit_success = True
break
if not exit_success:
logging.info(f"WARNING: {self.name} did not cleanly exit")
def get_return_code(self) -> Optional[int]:
return self.return_code
def _reset_command_data(self) -> None:
self.return_code = self.proc = None
self.cancelled = False
async def run(
self,
timeout: float = 2.,
verbose: bool = True,
log_complete: bool = True,
sig_idx: int = 1,
proc_input: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> bool:
async with self.run_lock:
self.factory.add_running_command(self)
self._reset_command_data()
if not timeout:
# Never timeout
timeout = 9999999999999999.
if (
self.std_out_cb is None
and self.std_err_cb is None and
not self.log_stderr
):
# No callbacks set so output cannot be verbose
verbose = False
created = await self._create_subprocess(
verbose, proc_input is not None)
if not created:
self.factory.remove_running_command(self)
return False
assert self.proc is not None
try:
if proc_input is not None:
ret: Coroutine = self.proc.communicate(
input=proc_input.encode())
else:
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.cancel(sig_idx)
else:
complete = not self.cancelled
self.factory.remove_running_command(self)
return self._check_proc_success(
complete, log_complete, success_codes
)
async def run_with_response(
self,
timeout: float = 2.,
retries: int = 1,
log_complete: bool = True,
sig_idx: int = 1,
proc_input: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> str:
async with self.run_lock:
self.factory.add_running_command(self)
retries = max(1, retries)
stdin: Optional[bytes] = None
if proc_input is not None:
stdin = proc_input.encode()
while retries > 0:
self._reset_command_data()
timed_out = False
stdout = stderr = b""
if await self._create_subprocess(has_input=stdin is not None):
assert self.proc is not None
try:
ret = self.proc.communicate(input=stdin)
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
timed_out = True
await self.cancel(sig_idx)
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(
f"{self.command[0]}: "
f"{stderr.decode(errors='ignore')}")
if self._check_proc_success(
complete, log_complete, success_codes
):
self.factory.remove_running_command(self)
return stdout.decode(errors='ignore').rstrip("\n")
if stdout:
logging.debug(
f"Shell command '{self.name}' output:"
f"\n{stdout.decode(errors='ignore')}")
if self.cancelled and not timed_out:
break
retries -= 1
await asyncio.sleep(.5)
self.factory.remove_running_command(self)
raise ShellCommandError(
f"Error running shell command: '{self.name}'",
self.return_code, stdout, stderr)
async def _create_subprocess(
self,
use_callbacks: bool = False,
has_input: bool = False
) -> bool:
loop = asyncio.get_running_loop()
def protocol_factory():
return ShellCommandProtocol(
limit=2**20, loop=loop, program_name=self.command[0],
std_out_cb=self.std_out_cb, std_err_cb=self.std_err_cb,
log_stderr=self.log_stderr)
try:
stdpipe: Optional[int] = None
if has_input:
stdpipe = asyncio.subprocess.PIPE
if self.std_err_cb is not None or self.log_stderr:
errpipe = asyncio.subprocess.PIPE
else:
errpipe = asyncio.subprocess.STDOUT
if use_callbacks:
transport, protocol = await loop.subprocess_exec(
protocol_factory, *self.command, stdin=stdpipe,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
self.proc = asyncio.subprocess.Process(
transport, protocol, loop)
else:
self.proc = await asyncio.create_subprocess_exec(
*self.command, stdin=stdpipe,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
except Exception:
logging.exception(
f"shell_command: Command ({self.name}) failed")
return False
return True
def _check_proc_success(
self,
complete: bool,
log_complete: bool,
success_codes: Optional[List[int]] = None
) -> bool:
assert self.proc is not None
if success_codes is None:
success_codes = [0]
self.return_code = self.proc.returncode
success = self.return_code in success_codes and complete
if success:
msg = f"Command ({self.name}) successfully finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
elif not complete:
msg = f"Command ({self.name}) timed out"
else:
msg = f"Command ({self.name}) exited with return code" \
f" {self.return_code}"
if log_complete:
logging.info(msg)
return success
class ShellCommandFactory:
error = ShellCommandError
def __init__(self, config: ConfigHelper) -> None:
self.running_commands: Set[ShellCommand] = set()
def add_running_command(self, cmd: ShellCommand) -> None:
self.running_commands.add(cmd)
def remove_running_command(self, cmd: ShellCommand) -> None:
try:
self.running_commands.remove(cmd)
except KeyError:
pass
def build_shell_command(
self,
cmd: str,
callback: OutputCallback = None,
std_err_callback: OutputCallback = None,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> ShellCommand:
return ShellCommand(
self, cmd, callback, std_err_callback, env, log_stderr, cwd
)
def exec_cmd(
self,
cmd: str,
timeout: float = 2.,
retries: int = 1,
sig_idx: int = 1,
proc_input: Optional[str] = None,
log_complete: bool = True,
log_stderr: bool = False,
env: Optional[Dict[str, str]] = None,
cwd: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> Awaitable:
scmd = ShellCommand(self, cmd, None, None, env,
log_stderr, cwd)
coro = scmd.run_with_response(
timeout, retries, log_complete, sig_idx,
proc_input, success_codes
)
return asyncio.create_task(coro)
async def close(self) -> None:
for cmd in self.running_commands:
await cmd.cancel()
def load_component(config: ConfigHelper) -> ShellCommandFactory:
return ShellCommandFactory(config)
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
# Template Factory helper
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import asyncio
import jinja2
import json
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from .secrets import Secrets
class TemplateFactory:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
secrets: Secrets = self.server.load_component(config, 'secrets')
self.jenv = jinja2.Environment('{%', '%}', '{', '}')
self.async_env = jinja2.Environment(
'{%', '%}', '{', '}', enable_async=True
)
self.ui_env = jinja2.Environment(enable_async=True)
self.jenv.add_extension("jinja2.ext.do")
self.jenv.filters['fromjson'] = json.loads
self.async_env.add_extension("jinja2.ext.do")
self.async_env.filters['fromjson'] = json.loads
self.ui_env.add_extension("jinja2.ext.do")
self.ui_env.filters['fromjson'] = json.loads
self.add_environment_global('raise_error', self._raise_error)
self.add_environment_global('secrets', secrets)
def add_environment_global(self, name: str, value: Any):
if name in self.jenv.globals:
raise self.server.error(
f"Jinja 2 environment already contains global {name}")
self.jenv.globals[name] = value
self.async_env.globals[name] = value
def _raise_error(self, err_msg: str, err_code: int = 400) -> None:
raise self.server.error(err_msg, err_code)
def create_template(self,
source: str,
is_async: bool = False
) -> JinjaTemplate:
env = self.async_env if is_async else self.jenv
try:
template = env.from_string(source)
except Exception:
logging.exception(f"Error creating template from source:\n{source}")
raise
return JinjaTemplate(source, self.server, template, is_async)
def create_ui_template(self, source: str) -> JinjaTemplate:
try:
template = self.ui_env.from_string(source)
except Exception:
logging.exception(f"Error creating template from source:\n{source}")
raise
return JinjaTemplate(source, self.server, template, True)
class JinjaTemplate:
def __init__(self,
source: str,
server: Server,
template: jinja2.Template,
is_async: bool
) -> None:
self.server = server
self.orig_source = source
self.template = template
self.is_async = is_async
def __str__(self) -> str:
return self.orig_source
def render(self, context: Dict[str, Any] = {}) -> str:
if self.is_async:
raise self.server.error(
"Cannot render async templates with the render() method"
", use render_async()")
try:
return self.template.render(context).strip()
except Exception as e:
msg = "Error rending Jinja2 Template"
if self.server.is_configured():
raise self.server.error(msg, 500) from e
raise self.server.config_error(msg) from e
async def render_async(self, context: Dict[str, Any] = {}) -> str:
try:
ret = await self.template.render_async(context)
except asyncio.CancelledError:
raise
except Exception as e:
raise self.server.error("Error rending Jinja2 Template", 500) from e
return ret.strip()
def load_component(config: ConfigHelper) -> TemplateFactory:
return TemplateFactory(config)
@@ -0,0 +1,15 @@
# Package definition for the update_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import update_manager as um
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> um.UpdateManager:
return um.load_component(config)
@@ -0,0 +1,391 @@
# Deploy updates for applications managed by Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import shutil
import hashlib
import logging
import re
from .base_deploy import BaseDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
Dict,
List,
Tuple
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from .update_manager import CommandHelper
from ..machine import Machine
from ..file_manager.file_manager import FileManager
MIN_PIP_VERSION = (23, 0)
SUPPORTED_CHANNELS = {
"zip": ["stable", "beta"],
"git_repo": ["dev", "beta"]
}
TYPE_TO_CHANNEL = {
"zip": "stable",
"zip_beta": "beta",
"git_repo": "dev"
}
class AppDeploy(BaseDeploy):
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
super().__init__(config, cmd_helper, prefix="Application")
self.config = config
type_choices = list(TYPE_TO_CHANNEL.keys())
self.type = config.get('type').lower()
if self.type not in type_choices:
raise config.error(
f"Config Error: Section [{config.get_name()}], Option "
f"'type: {self.type}': value must be one "
f"of the following choices: {type_choices}"
)
self.channel = config.get(
"channel", TYPE_TO_CHANNEL[self.type]
)
if self.type == "zip_beta":
self.server.add_warning(
f"Config Section [{config.get_name()}], Option 'type: "
"zip_beta', value 'zip_beta' is deprecated. Set 'type' "
"to zip and 'channel' to 'beta'")
self.type = "zip"
self.path = pathlib.Path(
config.get('path')).expanduser().resolve()
if (
self.name not in ["moonraker", "klipper"]
and not self.path.joinpath(".writeable").is_file()
):
fm: FileManager = self.server.lookup_component("file_manager")
fm.add_reserved_path(f"update_manager {self.name}", self.path)
executable = config.get('env', None)
if self.channel not in SUPPORTED_CHANNELS[self.type]:
raise config.error(
f"Invalid Channel '{self.channel}' for config "
f"section [{config.get_name()}], type: {self.type}")
self._verify_path(config, 'path', self.path, check_file=False)
self.executable: Optional[pathlib.Path] = None
self.pip_cmd: Optional[str] = None
self.pip_version: Tuple[int, ...] = tuple()
self.venv_args: Optional[str] = None
if executable is not None:
self.executable = pathlib.Path(executable).expanduser()
self._verify_path(config, 'env', self.executable, check_exe=True)
# Detect if executable is actually located in a virtualenv
# by checking the parent for the activation script
act_path = self.executable.parent.joinpath("activate")
while not act_path.is_file():
if self.executable.is_symlink():
self.executable = pathlib.Path(os.readlink(self.executable))
act_path = self.executable.parent.joinpath("activate")
else:
break
if act_path.is_file():
venv_dir = self.executable.parent.parent
self.log_info(f"Detected virtualenv: {venv_dir}")
pip_exe = self.executable.parent.joinpath("pip")
if pip_exe.is_file():
self.pip_cmd = f"{self.executable} -m pip"
else:
self.log_info("Unable to locate pip executable")
else:
self.log_info(
f"Unable to detect virtualenv at: {executable}"
)
self.executable = pathlib.Path(executable).expanduser()
self.venv_args = config.get('venv_args', None)
self.info_tags: List[str] = config.getlist("info_tags", [])
self.managed_services: List[str] = []
svc_default = []
if config.getboolean("is_system_service", True):
svc_default.append(self.name)
svc_choices = [self.name, "klipper", "moonraker"]
services: List[str] = config.getlist(
"managed_services", svc_default, separator=None
)
for svc in services:
if svc not in svc_choices:
raw = " ".join(services)
self.server.add_warning(
f"[{config.get_name()}]: Option 'managed_services: {raw}' "
f"contains an invalid value '{svc}'. All values must be "
f"one of the following choices: {svc_choices}"
)
break
for svc in svc_choices:
if svc in services and svc not in self.managed_services:
self.managed_services.append(svc)
logging.debug(
f"Extension {self.name} managed services: {self.managed_services}"
)
# We need to fetch all potential options for an Application. Not
# all options apply to each subtype, however we can't limit the
# options in children if we want to switch between channels and
# satisfy the confighelper's requirements.
self.moved_origin: Optional[str] = config.get('moved_origin', None)
self.origin: str = config.get('origin')
self.primary_branch = config.get("primary_branch", "master")
self.npm_pkg_json: Optional[pathlib.Path] = None
if config.getboolean("enable_node_updates", False):
self.npm_pkg_json = self.path.joinpath("package-lock.json")
self._verify_path(config, 'enable_node_updates', self.npm_pkg_json)
self.python_reqs: Optional[pathlib.Path] = None
if self.executable is not None:
self.python_reqs = self.path.joinpath(config.get("requirements"))
self._verify_path(config, 'requirements', self.python_reqs)
self.install_script: Optional[pathlib.Path] = None
install_script = config.get('install_script', None)
if install_script is not None:
self.install_script = self.path.joinpath(install_script).resolve()
self._verify_path(config, 'install_script', self.install_script)
@staticmethod
def _is_git_repo(app_path: Union[str, pathlib.Path]) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path).expanduser()
return app_path.joinpath('.git').exists()
async def initialize(self) -> Dict[str, Any]:
storage = await super().initialize()
self.need_channel_update = storage.get("need_channel_update", False)
self._is_valid = storage.get("is_valid", False)
self.pip_version = tuple(storage.get("pip_version", []))
if self.pip_version:
ver_str = ".".join([str(part) for part in self.pip_version])
self.log_info(f"Stored pip version: {ver_str}")
return storage
def _verify_path(
self,
config: ConfigHelper,
option: str,
path: pathlib.Path,
check_file: bool = True,
check_exe: bool = False
) -> None:
base_msg = (
f"Invalid path for option `{option}` in section "
f"[{config.get_name()}]: Path `{path}`"
)
if not path.exists():
raise config.error(f"{base_msg} does not exist")
if check_file and not path.is_file():
raise config.error(f"{base_msg} is not a file")
if check_exe and not os.access(path, os.X_OK):
raise config.error(f"{base_msg} is not executable")
def check_need_channel_swap(self) -> bool:
return self.need_channel_update
def get_configured_type(self) -> str:
return self.type
def check_same_paths(self,
app_path: Union[str, pathlib.Path],
executable: Union[str, pathlib.Path]
) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path)
if isinstance(executable, str):
executable = pathlib.Path(executable)
app_path = app_path.expanduser()
executable = executable.expanduser()
if self.executable is None:
return False
try:
return self.path.samefile(app_path) and \
self.executable.samefile(executable)
except Exception:
return False
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
raise NotImplementedError
async def reinstall(self):
raise NotImplementedError
async def restart_service(self):
if not self.managed_services:
return
is_full = self.cmd_helper.is_full_update()
for svc in self.managed_services:
if is_full and svc != self.name:
self.notify_status(f"Service {svc} restart postponed...")
self.cmd_helper.add_pending_restart(svc)
continue
self.cmd_helper.remove_pending_restart(svc)
self.notify_status(f"Restarting service {svc}...")
if svc == "moonraker":
# Launch restart async so the request can return
# before the server restarts
event_loop = self.server.get_event_loop()
event_loop.delay_callback(.1, self._do_restart, svc)
else:
await self._do_restart(svc)
async def _do_restart(self, svc_name: str) -> None:
machine: Machine = self.server.lookup_component("machine")
try:
await machine.do_service_action("restart", svc_name)
except Exception:
if svc_name == "moonraker":
# We will always get an error when restarting moonraker
# from within the child process, so ignore it
return
raise self.log_exc("Error restarting service")
def get_update_status(self) -> Dict[str, Any]:
return {
'channel': self.channel,
'debug_enabled': self.server.is_debug_enabled(),
'need_channel_update': self.need_channel_update,
'is_valid': self._is_valid,
'configured_type': self.type,
'info_tags': self.info_tags
}
def get_persistent_data(self) -> Dict[str, Any]:
storage = super().get_persistent_data()
storage['is_valid'] = self._is_valid
storage['need_channel_update'] = self.need_channel_update
storage['pip_version'] = list(self.pip_version)
return storage
async def _get_file_hash(self,
filename: Optional[pathlib.Path]
) -> Optional[str]:
if filename is None or not filename.is_file():
return None
def hash_func(f: pathlib.Path) -> str:
return hashlib.sha256(f.read_bytes()).hexdigest()
try:
event_loop = self.server.get_event_loop()
return await event_loop.run_in_thread(hash_func, filename)
except Exception:
return None
async def _check_need_update(self,
prev_hash: Optional[str],
filename: Optional[pathlib.Path]
) -> bool:
cur_hash = await self._get_file_hash(filename)
if prev_hash is None or cur_hash is None:
return False
return prev_hash != cur_hash
async def _install_packages(self, package_list: List[str]) -> None:
self.notify_status("Installing system dependencies...")
# Install packages with apt-get
try:
await self.cmd_helper.install_packages(
package_list, timeout=3600., notify=True)
except Exception:
self.log_exc("Error updating packages")
return
async def _update_python_requirements(
self, requirements: Union[pathlib.Path, List[str]]
) -> None:
if self.pip_cmd is None:
return
await self._update_pip()
# Update python dependencies
if isinstance(requirements, pathlib.Path):
if not requirements.is_file():
self.log_info(
f"Invalid path to requirements_file '{requirements}'")
return
args = f"-r {requirements}"
else:
args = " ".join(requirements)
self.notify_status("Updating python packages...")
try:
await self.cmd_helper.run_cmd(
f"{self.pip_cmd} install {args}", timeout=1200., notify=True,
retries=3
)
except Exception:
self.log_exc("Error updating python requirements")
async def _update_pip(self) -> None:
if self.pip_cmd is None:
return
update_ver = await self._check_pip_version()
if update_ver is None:
return
cur_vstr = ".".join([str(part) for part in self.pip_version])
self.notify_status(
f"Updating pip from version {cur_vstr} to {update_ver}..."
)
try:
await self.cmd_helper.run_cmd(
f"{self.pip_cmd} install pip=={update_ver}",
timeout=1200., notify=True, retries=3
)
except Exception:
self.log_exc("Error updating python pip")
async def _check_pip_version(self) -> Optional[str]:
if self.pip_cmd is None:
return None
self.notify_status("Checking pip version...")
try:
data: str = await self.cmd_helper.run_cmd_with_response(
f"{self.pip_cmd} --version", timeout=30., retries=3
)
match = re.match(
r"^pip ([0-9.]+) from .+? \(python ([0-9.]+)\)$", data.strip()
)
if match is None:
return None
pipver_str: str = match.group(1)
pyver_str: str = match.group(2)
pipver = tuple([int(part) for part in pipver_str.split(".")])
pyver = tuple([int(part) for part in pyver_str.split(".")])
except Exception:
self.log_exc("Error Getting Pip Version")
return None
self.pip_version = pipver
if not self.pip_version:
return None
self.log_info(
f"Dectected pip version: {pipver_str}, Python {pyver_str}"
)
if pyver < (3, 7):
return None
if self.pip_version < MIN_PIP_VERSION:
return ".".join([str(ver) for ver in MIN_PIP_VERSION])
return None
async def _build_virtualenv(self) -> None:
if self.executable is None or self.venv_args is None:
return
bin_dir = self.executable.parent
env_path = bin_dir.parent.resolve()
self.notify_status(f"Creating virtualenv at: {env_path}...")
if env_path.exists():
shutil.rmtree(env_path)
try:
await self.cmd_helper.run_cmd(
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
except Exception:
self.log_exc(f"Error creating virtualenv")
return
if not self.executable.exists():
raise self.log_exc("Failed to create new virtualenv", False)
@@ -0,0 +1,61 @@
# Moonraker/Klipper update configuration
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import sys
import copy
from ...utils import source_info
from typing import (
TYPE_CHECKING,
Dict
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ..database import MoonrakerDatabase
KLIPPER_DEFAULT_PATH = os.path.expanduser("~/klipper")
KLIPPER_DEFAULT_EXEC = os.path.expanduser("~/klippy-env/bin/python")
BASE_CONFIG: Dict[str, Dict[str, str]] = {
"moonraker": {
"origin": "https://github.com/arksine/moonraker.git",
"requirements": "scripts/moonraker-requirements.txt",
"venv_args": "-p python3",
"install_script": "scripts/install-moonraker.sh",
"host_repo": "arksine/moonraker",
"env": sys.executable,
"path": str(source_info.source_path()),
"managed_services": "moonraker"
},
"klipper": {
"moved_origin": "https://github.com/kevinoconnor/klipper.git",
"origin": "https://github.com/Klipper3d/klipper.git",
"requirements": "scripts/klippy-requirements.txt",
"venv_args": "-p python2",
"install_script": "scripts/install-octopi.sh",
"host_repo": "arksine/moonraker",
"managed_services": "klipper"
}
}
def get_base_configuration(config: ConfigHelper, channel: str) -> ConfigHelper:
server = config.get_server()
base_cfg = copy.deepcopy(BASE_CONFIG)
app_type = "zip" if channel == "stable" else "git_repo"
base_cfg["moonraker"]["channel"] = channel
base_cfg["moonraker"]["type"] = app_type
base_cfg["klipper"]["channel"] = channel
base_cfg["klipper"]["type"] = app_type
db: MoonrakerDatabase = server.lookup_component('database')
base_cfg["klipper"]["path"] = db.get_item(
"moonraker", "update_manager.klipper_path", KLIPPER_DEFAULT_PATH
).result()
base_cfg["klipper"]["env"] = db.get_item(
"moonraker", "update_manager.klipper_exec", KLIPPER_DEFAULT_EXEC
).result()
return config.read_supplemental_dict(base_cfg)
@@ -0,0 +1,97 @@
# Base Deployment Interface
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING, Dict, Any, Optional
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ...utils import ServerError
from .update_manager import CommandHelper
class BaseDeploy:
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
name: Optional[str] = None,
prefix: str = "",
cfg_hash: Optional[str] = None
) -> None:
if name is None:
name = config.get_name().split(maxsplit=1)[-1]
if name.startswith("client "):
# allow deprecated [update_manager client app] style names
name = name[7:]
self.name = name
if prefix:
prefix = f"{prefix} {self.name}: "
self.prefix = prefix
self.server = config.get_server()
self.cmd_helper = cmd_helper
self.refresh_interval = cmd_helper.get_refresh_interval()
refresh_interval = config.getint('refresh_interval', None)
if refresh_interval is not None:
self.refresh_interval = refresh_interval * 60 * 60
if cfg_hash is None:
cfg_hash = config.get_hash().hexdigest()
self.cfg_hash = cfg_hash
async def initialize(self) -> Dict[str, Any]:
umdb = self.cmd_helper.get_umdb()
storage: Dict[str, Any] = await umdb.get(self.name, {})
self.last_refresh_time: float = storage.get('last_refresh_time', 0.0)
self.last_cfg_hash: str = storage.get('last_config_hash', "")
return storage
def needs_refresh(self) -> bool:
next_refresh_time = self.last_refresh_time + self.refresh_interval
return (
self.cfg_hash != self.last_cfg_hash or
time.time() > next_refresh_time
)
def get_last_refresh_time(self) -> float:
return self.last_refresh_time
async def refresh(self) -> None:
pass
async def update(self) -> bool:
return False
def get_update_status(self) -> Dict[str, Any]:
return {}
def get_persistent_data(self) -> Dict[str, Any]:
return {
'last_config_hash': self.cfg_hash,
'last_refresh_time': self.last_refresh_time
}
def _save_state(self) -> None:
umdb = self.cmd_helper.get_umdb()
self.last_refresh_time = time.time()
self.last_cfg_hash = self.cfg_hash
umdb[self.name] = self.get_persistent_data()
def log_exc(self, msg: str, traceback: bool = True) -> ServerError:
log_msg = f"{self.prefix}{msg}"
if traceback:
logging.exception(log_msg)
else:
logging.info(log_msg)
return self.server.error(msg)
def log_info(self, msg: str) -> None:
log_msg = f"{self.prefix}{msg}"
logging.info(log_msg)
def notify_status(self, msg: str, is_complete: bool = False) -> None:
log_msg = f"{self.prefix}{msg}"
logging.debug(log_msg)
self.cmd_helper.notify_update_response(log_msg, is_complete)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,431 @@
# Zip Application Deployment implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import json
import shutil
import re
import time
import zipfile
from .app_deploy import AppDeploy
from ...utils import verify_source
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from .update_manager import CommandHelper
RINFO_KEYS = [
"git_version", "long_version", "commit_hash", "source_checksum",
"ignored_exts", "ignored_dirs", "build_date", "channel",
"owner_repo", "host_repo", "release_tag"
]
class ZipDeploy(AppDeploy):
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
super().__init__(config, cmd_helper)
self.need_channel_update = self.type != "zip"
self.official_repo: str = "?"
self.owner: str = "?"
# Extract repo from origin for validation
match = re.match(r"https?://(?:www\.)?github.com/([^/]+/[^.]+)",
self.origin)
if match is not None:
self.official_repo = match.group(1)
self.owner = self.official_repo.split('/')[0]
else:
raise config.error(
"Invalid url set for 'origin' option in section "
f"[{config.get_name()}]. Unable to extract owner/repo.")
self.host_repo: str = config.get('host_repo', self.official_repo)
self.package_list: List[str] = []
self.python_pkg_list: List[str] = []
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
@staticmethod
async def from_application(app: AppDeploy) -> ZipDeploy:
new_app = ZipDeploy(app.config, app.cmd_helper)
await new_app.reinstall()
return new_app
async def initialize(self) -> Dict[str, Any]:
storage = await super().initialize()
self.source_checksum: str = storage.get("source_checksum", "?")
self.pristine = storage.get('pristine', False)
self.verified = storage.get('verified', False)
self.build_date: int = storage.get('build_date', 0)
self.full_version: str = storage.get('full_version', "?")
self.short_version: str = storage.get('short_version', "?")
self.commit_hash: str = storage.get('commit_hash', "?")
self.lastest_hash: str = storage.get('latest_hash', "?")
self.latest_version: str = storage.get('latest_version', "?")
self.latest_checksum: str = storage.get('latest_checksum', "?")
self.latest_build_date: int = storage.get('latest_build_date', 0)
self.errors: List[str] = storage.get('errors', [])
self.commit_log: List[Dict[str, Any]] = storage.get('commit_log', [])
return storage
def get_persistent_data(self) -> Dict[str, Any]:
storage = super().get_persistent_data()
storage.update({
'source_checksum': self.source_checksum,
'pristine': self.pristine,
'verified': self.verified,
'build_date': self.build_date,
'full_version': self.full_version,
'short_version': self.short_version,
'commit_hash': self.commit_hash,
'latest_hash': self.lastest_hash,
'latest_version': self.latest_version,
'latest_checksum': self.latest_checksum,
'latest_build_date': self.latest_build_date,
'commit_log': self.commit_log,
'errors': self.errors
})
return storage
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
info_file = self.path.joinpath(file_name)
if not info_file.exists():
self.log_info(f"Unable to locate file '{info_file}'")
return {}
try:
event_loop = self.server.get_event_loop()
info_bytes = await event_loop.run_in_thread(info_file.read_text)
info: Dict[str, Any] = json.loads(info_bytes)
except Exception:
self.log_exc(f"Unable to parse info file {file_name}")
info = {}
return info
def _get_tag_version(self, version_string: str) -> str:
tag_version: str = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", version_string)
if ver_match:
tag_version = ver_match.group()
return tag_version
async def refresh(self) -> None:
try:
await self._update_repo_state()
except Exception:
self.verified = False
self.log_exc("Error refreshing application state")
async def _update_repo_state(self) -> None:
self.errors = []
self._is_valid = False
self.verified = False
release_info = await self._parse_info_file(".release_info")
dep_info = await self._parse_info_file(".dependencies")
for key in RINFO_KEYS:
if key not in release_info:
self._add_error(f"Missing release info item: {key}")
if 'channel' in release_info:
local_channel = release_info['channel']
if self.channel == "stable" and local_channel == "beta":
self.need_channel_update = True
self.full_version = release_info.get('long_version', "?")
self.short_version = self._get_tag_version(
release_info.get('git_version', ""))
self.commit_hash = release_info.get('commit_hash', "?")
self.build_date = release_info.get('build_date', 0)
owner_repo = release_info.get('owner_repo', "?")
if self.official_repo != owner_repo:
self._add_error(
f"Owner repo mismatch. Received {owner_repo}, "
f"official: {self.official_repo}")
# validate the local source code
event_loop = self.server.get_event_loop()
res = await event_loop.run_in_thread(verify_source, self.path)
if res is not None:
self.source_checksum, self.pristine = res
if self.name in ["moonraker", "klipper"]:
self.server.add_log_rollover_item(
f"{self.name}_validation",
f"{self.name} checksum: {self.source_checksum}, "
f"pristine: {self.pristine}")
else:
self._add_error("Unable to validate source checksum")
self.source_checksum = ""
self.pristine = False
self.package_list = sorted(dep_info.get(
'debian', {}).get('packages', []))
self.python_pkg_list = sorted(dep_info.get('python', []))
# Retrieve version info from github to check for updates and
# validate local release info
host_repo = release_info.get('host_repo', "?")
release_tag = release_info.get('release_tag', "?")
if host_repo != self.host_repo:
self._add_error(
f"Host repo mismatch, received: {host_repo}, "
f"expected: {self.host_repo}. This could result in "
" a failed update.")
resource = f"repos/{self.host_repo}/releases"
current_release, latest_release = await self._fetch_github_releases(
resource, release_tag)
await self._validate_current_release(release_info, current_release)
if not self.errors:
self.verified = True
await self._process_latest_release(latest_release)
self._save_state()
self._log_zipapp_info()
async def _fetch_github_releases(self,
resource: str,
current_tag: Optional[str] = None
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
try:
client = self.cmd_helper.get_http_client()
resp = await client.github_api_request(resource, attempts=3)
resp.raise_for_status()
releases = resp.json()
assert isinstance(releases, list)
except Exception:
self.log_exc("Error fetching releases from GitHub")
return {}, {}
release: Dict[str, Any]
latest_release: Dict[str, Any] = {}
current_release: Dict[str, Any] = {}
for release in releases:
if not latest_release:
if self.channel != "stable":
# Allow the beta channel to update regardless
latest_release = release
elif not release['prerelease']:
# This is a stable release on the stable channle
latest_release = release
if current_tag is not None:
if not current_release and release['tag_name'] == current_tag:
current_release = release
if latest_release and current_release:
break
elif latest_release:
break
return current_release, latest_release
async def _validate_current_release(self,
release_info: Dict[str, Any],
release: Dict[str, Any]
) -> None:
if not release:
self._add_error("Unable to find current release on GitHub")
return
asset_info = self._get_asset_urls(release, ["RELEASE_INFO"])
if "RELEASE_INFO" not in asset_info:
self._add_error(
"RELEASE_INFO not found in current release assets")
info_url, content_type, size = asset_info['RELEASE_INFO']
client = self.cmd_helper.get_http_client()
rinfo_bytes = await client.get_file(info_url, content_type)
github_rinfo: Dict[str, Any] = json.loads(rinfo_bytes)
if github_rinfo.get(self.name, {}) != release_info:
self._add_error(
"Local release info does not match the remote")
else:
self.log_info("Current Release Info Validated")
async def _process_latest_release(self, release: Dict[str, Any]):
if not release:
self._add_error("Unable to find latest release on GitHub")
return
zip_file_name = f"{self.name}.zip"
asset_names = ["RELEASE_INFO", "COMMIT_LOG", zip_file_name]
asset_info = self._get_asset_urls(release, asset_names)
if "RELEASE_INFO" in asset_info:
asset_url, content_type, size = asset_info['RELEASE_INFO']
client = self.cmd_helper.get_http_client()
rinfo_bytes = await client.get_file(asset_url, content_type)
update_release_info: Dict[str, Any] = json.loads(rinfo_bytes)
update_info = update_release_info.get(self.name, {})
self.lastest_hash = update_info.get('commit_hash', "?")
self.latest_checksum = update_info.get('source_checksum', "?")
self.latest_version = self._get_tag_version(
update_info.get('git_version', "?"))
self.latest_build_date = update_info.get('build_date', 0)
else:
self._add_error(
"RELEASE_INFO not found in latest release assets")
self.commit_log = []
if self.short_version != self.latest_version:
# Only report commit log if versions change
if "COMMIT_LOG" in asset_info:
asset_url, content_type, size = asset_info['COMMIT_LOG']
client = self.cmd_helper.get_http_client()
commit_bytes = await client.get_file(asset_url, content_type)
commit_info: Dict[str, Any] = json.loads(commit_bytes)
self.commit_log = commit_info.get(self.name, [])
if zip_file_name in asset_info:
self.release_download_info = asset_info[zip_file_name]
self._is_valid = True
else:
self.release_download_info = ("?", "?", 0)
self._add_error(f"Release asset {zip_file_name} not found")
def _get_asset_urls(self,
release: Dict[str, Any],
filenames: List[str]
) -> Dict[str, Tuple[str, str, int]]:
asset_info: Dict[str, Tuple[str, str, int]] = {}
asset: Dict[str, Any]
for asset in release.get('assets', []):
name = asset['name']
if name in filenames:
rinfo_url = asset['browser_download_url']
content_type = asset['content_type']
size = asset['size']
asset_info[name] = (rinfo_url, content_type, size)
filenames.remove(name)
if not filenames:
break
return asset_info
def _add_error(self, warning: str):
self.log_info(warning)
self.errors.append(warning)
def _log_zipapp_info(self):
self.log_info(
"\nZip Application Distribution Detected\n"
f" Valid: {self._is_valid}\n"
f" Verified: {self.verified}\n"
f" Channel: {self.channel}\n"
f" Repo: {self.official_repo}\n"
f" Path: {self.path}\n"
f" Pristine: {self.pristine}\n"
f" Need Channel Update: {self.need_channel_update}\n"
f" Commits Behind: {len(self.commit_log)}\n"
f"Current Release Info:\n"
f" Source Checksum: {self.source_checksum}\n"
f" Commit SHA: {self.commit_hash}\n"
f" Long Version: {self.full_version}\n"
f" Short Version: {self.short_version}\n"
f" Build Date: {time.ctime(self.build_date)}\n"
f"Latest Available Release Info:\n"
f" Source Checksum: {self.latest_checksum}\n"
f" Commit SHA: {self.lastest_hash}\n"
f" Version: {self.latest_version}\n"
f" Build Date: {time.ctime(self.latest_build_date)}\n"
f" Download URL: {self.release_download_info[0]}\n"
f" Content Type: {self.release_download_info[1]}\n"
f" Download Size: {self.release_download_info[2]}"
)
async def _update_dependencies(self,
npm_hash,
force: bool = False
) -> None:
new_deps = await self._parse_info_file('.dependencies')
system_pkgs = sorted(
new_deps.get('debian', {}).get('packages', []))
python_pkgs = sorted(new_deps.get('python', []))
if system_pkgs:
if force or system_pkgs != self.package_list:
await self._install_packages(system_pkgs)
if python_pkgs:
if force or python_pkgs != self.python_pkg_list:
await self._update_python_requirements(python_pkgs)
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
if force or ret:
if self.npm_pkg_json is not None:
self.notify_status("Updating Node Packages...")
try:
await self.cmd_helper.run_cmd(
"npm ci --only=prod", notify=True, timeout=600.,
cwd=str(self.path))
except Exception:
self.notify_status("Node Package Update failed")
def _extract_release(self, release_zip: pathlib.Path) -> None:
if self.path.is_dir():
shutil.rmtree(self.path)
os.mkdir(self.path)
with zipfile.ZipFile(release_zip) as zf:
zf.extractall(self.path)
async def update(self, force_dep_update: bool = False) -> bool:
if not self._is_valid:
raise self.log_exc("Update aborted, repo not valid", False)
if self.short_version == self.latest_version:
# already up to date
return False
self.cmd_helper.notify_update_response(
f"Updating Application {self.name}...")
npm_hash = await self._get_file_hash(self.npm_pkg_json)
dl_url, content_type, size = self.release_download_info
self.notify_status("Starting Download...")
td = await self.cmd_helper.create_tempdir(self.name, "app")
try:
tempdir = pathlib.Path(td.name)
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
client = self.cmd_helper.get_http_client()
await client.download_file(
dl_url, content_type, temp_download_file, size,
self.cmd_helper.on_download_progress)
self.notify_status(
f"Download Complete, extracting release to '{self.path}'")
event_loop = self.server.get_event_loop()
await event_loop.run_in_thread(
self._extract_release, temp_download_file)
finally:
await event_loop.run_in_thread(td.cleanup)
await self._update_dependencies(npm_hash, force=force_dep_update)
await self._update_repo_state()
await self.restart_service()
self.notify_status("Update Finished...", is_complete=True)
return True
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
res = f"repos/{self.host_repo}/releases"
releases = await self._fetch_github_releases(res)
await self._process_latest_release(releases[1])
await self.update(force_dep_update=force_dep_update)
async def reinstall(self) -> None:
# Clear the persistent storage prior to a channel swap.
# After the next update is complete new data will be
# restored.
umdb = self.cmd_helper.get_umdb()
await umdb.pop(self.name, None)
await self.initialize()
await self.recover(force_dep_update=True)
def get_update_status(self) -> Dict[str, Any]:
status = super().get_update_status()
# XXX - Currently this reports status matching
# that of the git repo so as to not break existing
# client functionality. In the future it would be
# good to report values that are specifc
status.update({
'detected_type': "zip",
'remote_alias': "origin",
'branch': "master",
'owner': self.owner,
'version': self.short_version,
'remote_version': self.latest_version,
'current_hash': self.commit_hash,
'remote_hash': self.lastest_hash,
'is_dirty': False,
'detached': not self.verified,
'commits_behind': self.commit_log,
'git_messages': self.errors,
'full_version_string': self.full_version,
'pristine': self.pristine,
})
return status
+373
View File
@@ -0,0 +1,373 @@
# Centralized webcam configuration
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import re
import ipaddress
import socket
import uuid
import logging
from typing import (
TYPE_CHECKING,
Optional,
Dict,
List,
Any,
Tuple
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .database import MoonrakerDatabase
from .machine import Machine
from .shell_command import ShellCommandFactory
from .http_client import HttpClient
# This provides a mapping of fields defined by Moonraker to fields
# defined by the database.
CAM_FIELDS = {
"name": "name", "service": "service", "target_fps": "targetFps",
"stream_url": "urlStream", "snapshot_url": "urlSnapshot",
"flip_horizontal": "flipX", "flip_vertical": "flipY"
}
class WebcamManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.webcams: Dict[str, WebCam] = {}
# parse user configured webcams
prefix_sections = config.get_prefix_sections("webcam ")
for section in prefix_sections:
cam_cfg = config[section]
webcam = WebCam.from_config(cam_cfg)
self.webcams[webcam.name] = webcam
self.server.register_endpoint(
"/server/webcams/list", ["GET"], self._handle_webcam_list
)
self.server.register_endpoint(
"/server/webcams/item", ["GET", "POST", "DELETE"],
self._handle_webcam_request
)
self.server.register_endpoint(
"/server/webcams/test", ["POST"], self._handle_webcam_test
)
self.server.register_notification("webcam:webcams_changed")
self.server.register_event_handler(
"machine:public_ip_changed", self._set_default_host_ip
)
async def component_init(self) -> None:
machine: Machine = self.server.lookup_component("machine")
if machine.public_ip:
self._set_default_host_ip(machine.public_ip)
db: MoonrakerDatabase = self.server.lookup_component("database")
saved_cams: Dict[str, Any] = await db.get_item("webcams", default={})
for cam_data in saved_cams.values():
try:
webcam = WebCam.from_database(self.server, cam_data)
if webcam.name in self.webcams:
continue
self.webcams[webcam.name] = webcam
except Exception:
logging.exception("Failed to process webcam from db")
continue
def _set_default_host_ip(self, ip: str) -> None:
default_host = "http://127.0.0.1"
if ip:
try:
addr = ipaddress.ip_address(ip)
except Exception:
logging.debug(f"Invalid IP Recd: {ip}")
else:
if addr.version == 6:
default_host = f"http://[{addr}]"
else:
default_host = f"http://{addr}"
WebCam.set_default_host(default_host)
logging.info(f"Default public webcam address set: {default_host}")
def get_webcams(self) -> Dict[str, WebCam]:
return self.webcams
def _list_webcams(self) -> List[Dict[str, Any]]:
return [wc.as_dict() for wc in self.webcams.values()]
async def _find_dbcam_by_uuid(
self, name: str
) -> Tuple[str, Dict[str, Any]]:
db: MoonrakerDatabase = self.server.lookup_component("database")
saved_cams: Dict[str, Dict[str, Any]]
saved_cams = await db.get_item("webcams", default={})
for uid, cam_data in saved_cams.items():
if name == cam_data["name"]:
return uid, cam_data
return "", {}
async def _save_cam(self, webcam: WebCam) -> None:
uid, cam_data = await self._find_dbcam_by_uuid(webcam.name)
if not uid:
uid = str(uuid.uuid4())
for mfield, dbfield in CAM_FIELDS.items():
cam_data[dbfield] = getattr(webcam, mfield)
cam_data["location"] = webcam.location
cam_data["rotation"] = webcam.rotation
if "icon" not in cam_data:
cam_data["icon"] = "mdi-webcam"
db: MoonrakerDatabase = self.server.lookup_component("database")
db.insert_item("webcams", uid, cam_data)
async def _delete_cam(self, webcam: WebCam) -> None:
uid, cam = await self._find_dbcam_by_uuid(webcam.name)
if not uid:
return
db: MoonrakerDatabase = self.server.lookup_component("database")
db.delete_item("webcams", uid)
async def _handle_webcam_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
name = web_request.get_str("name")
webcam_data: Dict[str, Any] = {}
if action == "GET":
if name not in self.webcams:
raise self.server.error(f"Webcam {name} not found", 404)
webcam_data = self.webcams[name].as_dict()
elif action == "POST":
if (
name in self.webcams and
self.webcams[name].source == "config"
):
raise self.server.error(
f"Cannot overwrite webcam '{name}' sourced from "
"Moonraker configuration"
)
webcam = WebCam.from_web_request(self.server, web_request)
self.webcams[name] = webcam
webcam_data = webcam.as_dict()
await self._save_cam(webcam)
elif action == "DELETE":
if name not in self.webcams:
raise self.server.error(f"Webcam {name} not found", 404)
elif self.webcams[name].source == "config":
raise self.server.error(
f"Cannot delete webcam '{name}' sourced from "
"Moonraker configuration"
)
webcam = self.webcams.pop(name)
webcam_data = webcam.as_dict()
await self._delete_cam(webcam)
if action != "GET":
self.server.send_event(
"webcam:webcams_changed", {"webcams": self._list_webcams()}
)
return {"webcam": webcam_data}
async def _handle_webcam_list(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"webcams": self._list_webcams()}
async def _handle_webcam_test(
self, web_request: WebRequest
) -> Dict[str, Any]:
name = web_request.get_str("name")
if name not in self.webcams:
raise self.server.error(f"Webcam '{name}' not found", 404)
client: HttpClient = self.server.lookup_component("http_client")
cam = self.webcams[name]
result: Dict[str, Any] = {
"name": name,
"snapshot_reachable": False
}
for img_type in ["snapshot", "stream"]:
try:
func = getattr(cam, f"get_{img_type}_url")
result[f"{img_type}_url"] = await func(True)
except Exception:
logging.exception(f"Error Processing {img_type} url")
result[f"{img_type}_url"] = ""
url: str = result["snapshot_url"]
if result.get("snapshot_url", "").startswith("http"):
ret = await client.get(url, connect_timeout=1., request_timeout=1.)
result["snapshot_reachable"] = not ret.has_error()
return result
class WebCam:
_default_host: str = "http://127.0.0.1"
def __init__(self, server: Server, **kwargs) -> None:
self._server = server
self.name: str = kwargs["name"]
self.location: str = kwargs["location"]
self.service: str = kwargs["service"]
self.target_fps: int = kwargs["target_fps"]
self.stream_url: str = kwargs["stream_url"]
self.snapshot_url: str = kwargs["snapshot_url"]
self.flip_horizontal: bool = kwargs["flip_horizontal"]
self.flip_vertical: bool = kwargs["flip_vertical"]
self.rotation: int = kwargs["rotation"]
self.source: str = kwargs["source"]
def as_dict(self):
return {k: v for k, v in self.__dict__.items() if k[0] != "_"}
async def get_stream_url(self, convert_local: bool = False) -> str:
return await self._get_url(self.stream_url, convert_local)
async def get_snapshot_url(self, convert_local: bool = False) -> str:
return await self._get_url(self.snapshot_url, convert_local)
async def _get_url(self, url: str, convert_local: bool) -> str:
if not url:
raise self._server.error("Empty URL Provided")
match = re.match(r"\w+://[^/]+", url)
if match is None:
# assume a partial URL on the default host
url = f"{self._default_host}/{url.lstrip('/')}"
if not convert_local:
return url
return await self.convert_local(url)
def _get_local_ips(self) -> List[str]:
all_ips: List[str] = []
machine: Machine = self._server.lookup_component("machine")
sys_info = machine.get_system_info()
network = sys_info.get("network", {})
iface: Dict[str, Any]
for iface in network.values():
addresses: List[Dict[str, Any]] = iface["ip_addresses"]
for addr_info in addresses:
all_ips.append(addr_info["address"])
return all_ips
async def convert_local(self, url: str) -> str:
match = re.match(r"(\w+)://([^/]+)(/.*)?", url)
if match is None:
return url
scheme = match.group(1)
addr = match.group(2)
fragment = match.group(3)
if fragment is None:
fragment = ""
if addr[0] == "[":
# ipv6 address
addr_match = re.match(r"\[(.+)\](:\d+)?", addr)
else:
# ipv4 address or hostname
addr_match = re.match(r"([^:]+)(:\d+)?", addr)
if addr_match is None:
return url
addr = addr_match.group(1)
port: Optional[str] = addr_match.group(2)
default_ports = {"http": "80", "https": "443", "rtsp": "554"}
if port is None:
if scheme not in default_ports:
return url
port = default_ports[scheme]
else:
port = port.lstrip(":")
# attempt to convert hostname to IP
try:
eventloop = self._server.get_event_loop()
addr_info = await eventloop.run_in_thread(
socket.getaddrinfo, addr, int(port)
)
if addr_info:
addr = addr_info[0][4][0]
except Exception:
pass
try:
ip = ipaddress.ip_address(addr)
except Exception:
# Invalid IP, can't convert.
return url
else:
if ip.is_loopback:
return url
# Check to see if this ip address is on the local machine
if addr not in self._get_local_ips():
return url
scmd: ShellCommandFactory
scmd = self._server.lookup_component("shell_command")
try:
# Use the ss command to list all tcp ports
resp: str = await scmd.exec_cmd("ss -ltn")
lines = resp.split("\n")[1:]
for line in lines:
parts = line.strip().split()
if len(parts) < 5:
continue
laddr, lport = parts[3].split(":")
if lport == port:
if laddr == "[::]":
return f"{scheme}://[::1]:{port}{fragment}"
elif laddr == "0.0.0.0":
return f"{scheme}://127.0.0.1:{port}{fragment}"
except scmd.error:
pass
return url
@staticmethod
def set_default_host(host: str) -> None:
WebCam._default_host = host
@classmethod
def from_config(cls, config: ConfigHelper) -> WebCam:
webcam: Dict[str, Any] = {}
webcam["name"] = config.get_name().split(maxsplit=1)[-1]
webcam["location"] = config.get("location", "printer")
webcam["service"] = config.get("service", "mjpegstreamer")
webcam["target_fps"] = config.getint("target_fps", 15)
webcam["stream_url"] = config.get("stream_url")
webcam["snapshot_url"] = config.get("snapshot_url")
webcam["flip_horizontal"] = config.getboolean("flip_horizontal", False)
webcam["flip_vertical"] = config.getboolean("flip_vertical", False)
webcam["rotation"] = config.getint("rotation", 0)
if webcam["rotation"] not in [0, 90, 180, 270]:
raise config.error("Invalid value for option 'rotation'")
webcam["source"] = "config"
return cls(config.get_server(), **webcam)
@classmethod
def from_web_request(
cls, server: Server, web_request: WebRequest
) -> WebCam:
webcam: Dict[str, Any] = {}
webcam["name"] = web_request.get_str("name")
webcam["location"] = web_request.get_str("location", "printer")
webcam["service"] = web_request.get_str("service", "mjpegstreamer")
webcam["target_fps"] = web_request.get_int("target_fps", 15)
webcam["stream_url"] = web_request.get_str("stream_url")
webcam["snapshot_url"] = web_request.get_str("snapshot_url")
webcam["flip_horizontal"] = web_request.get_boolean(
"flip_horizontal", False
)
webcam["flip_vertical"] = web_request.get_boolean(
"flip_vertical", False
)
webcam["rotation"] = web_request.get_int("rotation", 0)
if webcam["rotation"] not in [0, 90, 180, 270]:
raise server.error("Invalid value for parameter 'rotation'")
webcam["source"] = "database"
return cls(server, **webcam)
@classmethod
def from_database(cls, server: Server, cam_data: Dict[str, Any]) -> WebCam:
webcam: Dict[str, Any] = {}
for mfield, dbfield in CAM_FIELDS.items():
webcam[mfield] = cam_data[dbfield]
webcam["location"] = webcam.get("location", "printer")
webcam["rotation"] = webcam.get("rotation", 0)
webcam["source"] = "database"
return cls(server, **webcam)
def load_component(config: ConfigHelper) -> WebcamManager:
return WebcamManager(config)
+594
View File
@@ -0,0 +1,594 @@
# WLED neopixel support
#
# Copyright (C) 2021-2022 Richard Mitchell <richardjm+moonraker@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Component to control the wled neopixel home system from AirCookie
# Github at https://github.com/Aircoookie/WLED
# Wiki at https://kno.wled.ge/
from __future__ import annotations
from enum import Enum
import logging
import json
import asyncio
import serial_asyncio
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
# Annotation imports
from typing import (
TYPE_CHECKING,
Type,
List,
Any,
Optional,
Dict,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
class OnOff(str, Enum):
on: str = "on"
off: str = "off"
class Strip():
_COLORSIZE: int = 4
def __init__(self: Strip,
name: str,
cfg: ConfigHelper):
self.server = cfg.get_server()
self.request_mutex = asyncio.Lock()
self.name = name
self.initial_preset: int = cfg.getint("initial_preset", -1)
self.initial_red: float = cfg.getfloat("initial_red", 0.5)
self.initial_green: float = cfg.getfloat("initial_green", 0.5)
self.initial_blue: float = cfg.getfloat("initial_blue", 0.5)
self.initial_white: float = cfg.getfloat("initial_white", 0.5)
self.chain_count: int = cfg.getint("chain_count", 1)
# Supports rgbw always
self._chain_data = bytearray(
self.chain_count * self._COLORSIZE)
self.onoff = OnOff.off
self.preset = self.initial_preset
def get_strip_info(self: Strip) -> Dict[str, Any]:
return {
"strip": self.name,
"status": self.onoff.value,
"chain_count": self.chain_count,
"preset": self.preset,
"brightness": self.brightness,
"intensity": self.intensity,
"speed": self.speed,
"error": self.error_state
}
async def initialize(self: Strip) -> None:
self.send_full_chain_data = True
self.onoff = OnOff.on
self.preset = self.initial_preset
self.brightness = 255
self.intensity = -1
self.speed = -1
if self.initial_preset >= 0:
self._update_color_data(self.initial_red,
self.initial_green,
self.initial_blue,
self.initial_white,
None)
await self.wled_on(self.initial_preset)
else:
await self.set_wled(self.initial_red,
self.initial_green,
self.initial_blue,
self.initial_white,
None,
True)
def _update_color_data(self: Strip,
red: float, green: float, blue: float, white: float,
index: Optional[int]) -> None:
red = int(red * 255. + .5)
blue = int(blue * 255. + .5)
green = int(green * 255. + .5)
white = int(white * 255. + .5)
led_data = [red, green, blue, white]
if index is None:
self._chain_data[:] = led_data * self.chain_count
else:
elem_size = len(led_data)
self._chain_data[(index-1)*elem_size:index*elem_size] = led_data
async def send_wled_command_impl(self: Strip,
state: Dict[str, Any]) -> None:
pass
def close(self: Strip):
pass
async def _send_wled_command(self: Strip,
state: Dict[str, Any]) -> None:
try:
await self.send_wled_command_impl(state)
self.error_state = None
except Exception as e:
msg = f"WLED: Error {e}"
self.error_state = msg
logging.exception(msg)
raise self.server.error(msg)
async def wled_on(self: Strip, preset: int) -> None:
self.onoff = OnOff.on
logging.debug(f"WLED: {self.name} on PRESET={preset}")
if preset < 0:
# WLED_ON STRIP=strip (no args) - reset to default
await self.initialize()
else:
self.send_full_chain_data = True
self.preset = preset
# Without reading the data back from wled we don't know the values
self.brightness = -1
self.intensity = -1
self.speed = -1
await self._send_wled_command({"on": True, "ps": preset})
async def wled_off(self: Strip) -> None:
logging.debug(f"WLED: {self.name} off")
self.onoff = OnOff.off
# Without this calling SET_WLED for a single pixel after WLED_OFF
# would send just that pixel
self.send_full_chain_data = True
await self._send_wled_command({"on": False})
async def wled_control(self: Strip, brightness: int, intensity: int,
speed: int) -> None:
logging.debug(
f"WLED: {self.name} control {self.onoff} BRIGHTNESS={brightness} "
f"INTENSITY={intensity} SPEED={speed} CURRENTPRESET={self.preset}")
if self.onoff == OnOff.off:
logging.info("wled control only permitted when strip is on")
return
# Even if a preset is not activated sending seg {} information will
# turn it back on
control: Dict[str, Any]
if self.preset != -1:
control = {"tt": 0, "seg": {}}
else:
control = {"tt": 0}
shouldSend: bool = False
# Using 0 is not recommended in wled docs
if brightness > 0:
if brightness > 255:
logging.info("BRIGHTNESS should be between 1 and 255")
else:
shouldSend = True
self.brightness = brightness
control["bri"] = self.brightness
# Brightness in seg {} - only if a preset is on
if self.preset != -1:
control["seg"]["bri"] = self.brightness
# Intensity - only if a preset is on
if intensity > -1 and self.preset != -1:
if intensity > 255:
logging.info("INTENSITY should be between 0 and 255")
else:
shouldSend = True
self.intensity = intensity
control["seg"]["ix"] = self.intensity
# Speed - only if a preset is on
if speed > -1 and self.preset != -1:
if speed > 255:
logging.info("SPEED should be between 0 and 255")
else:
shouldSend = True
self.speed = speed
control["seg"]["sx"] = self.speed
# Control brightness, intensity, and speed for segment
# This will allow full control for effects such as "Percent"
if shouldSend:
await self._send_wled_command(control)
def _wled_pixel(self: Strip, index: int) -> List[int]:
led_color_data: List[int] = []
for p in self._chain_data[(index-1)*self._COLORSIZE:
(index)*self._COLORSIZE]:
led_color_data.append(p)
return led_color_data
async def set_wled(self: Strip,
red: float, green: float, blue: float, white: float,
index: Optional[int], transmit: bool) -> None:
logging.debug(
f"WLED: {self.name} R={red} G={green} B={blue} W={white} "
f"INDEX={index} TRANSMIT={transmit}")
self._update_color_data(red, green, blue, white, index)
if transmit:
# Clear preset (issues with sending seg{} will revert to preset)
self.preset = -1
# If we are coming from a preset without a wled_control
# we don't know a brightness, this will also ensure
# behaviour is consistent prior to introduction of wled_control
if self.brightness == -1:
self.brightness = 255
# Base command for setting an led (for all active segments)
# See https://kno.wled.ge/interfaces/json-api/
state: Dict[str, Any] = {"on": True,
"tt": 0,
"bri": self.brightness,
"seg": {"bri": self.brightness, "i": []}}
if index is None:
# All pixels same color only send range command of first color
self.send_full_chain_data = False
state["seg"]["i"] = [0, self.chain_count, self._wled_pixel(1)]
elif self.send_full_chain_data:
# Send a full set of color data (e.g. previous preset)
self.send_full_chain_data = False
cdata = []
for i in range(self.chain_count):
cdata.append(self._wled_pixel(i+1))
state["seg"]["i"] = cdata
else:
# Only one pixel has changed since last full data sent
# so send just that one
state["seg"]["i"] = [index-1, self._wled_pixel(index)]
# Send wled control command
await self._send_wled_command(state)
if self.onoff == OnOff.off:
# Without a repeated call individual led control doesn't
# turn the led strip back on or doesn't set brightness
# correctly from off
# Confirmed as a bug:
# https://discord.com/channels/473448917040758787/757254961640898622/934135556370202645
self.onoff = OnOff.on
await self._send_wled_command(state)
else:
# If not transmitting this time easiest just to send all data when
# next transmitting
self.send_full_chain_data = True
class StripHttp(Strip):
def __init__(self: StripHttp,
name: str,
cfg: ConfigHelper):
super().__init__(name, cfg)
# Read the uri information
addr: str = cfg.get("address")
port: int = cfg.getint("port", 80)
protocol: str = cfg.get("protocol", "http")
self.url = f"{protocol}://{addr}:{port}/json"
self.timeout: float = cfg.getfloat("timeout", 2.)
self.client = AsyncHTTPClient()
async def send_wled_command_impl(self: StripHttp,
state: Dict[str, Any],
retries: int = 3
) -> None:
async with self.request_mutex:
logging.debug(f"WLED: url:{self.url} json:{state}")
headers = {"Content-Type": "application/json"}
request = HTTPRequest(url=self.url,
method="POST",
headers=headers,
body=json.dumps(state),
connect_timeout=self.timeout,
request_timeout=self.timeout)
for i in range(retries):
try:
response = await self.client.fetch(request)
except Exception:
if i == retries - 1:
raise
await asyncio.sleep(1.0)
else:
break
logging.debug(
f"WLED: url:{self.url} status:{response.code} "
f"response:{response.body.decode()}")
class StripSerial(Strip):
def __init__(self: StripSerial,
name: str,
cfg: ConfigHelper):
super().__init__(name, cfg)
# Read the serial information (requires wled 0.13 2108250 or greater)
self.serialport: str = cfg.get("serial")
self.baud: int = cfg.getint("baud", 115200, above=49)
async def send_wled_command_impl(self: StripSerial,
state: Dict[str, Any]) -> None:
async with self.request_mutex:
if not hasattr(self, 'ser'):
_, self.ser = await serial_asyncio.open_serial_connection(
url=self.serialport, baudrate=self.baud)
logging.debug(f"WLED: serial:{self.serialport} json:{state}")
self.ser.write(json.dumps(state).encode())
def close(self: StripSerial):
if hasattr(self, 'ser'):
self.ser.close()
logging.info(f"WLED: Closing serial {self.serialport}")
class WLED:
def __init__(self: WLED, config: ConfigHelper) -> None:
# root_logger = logging.getLogger()
# root_logger.setLevel(logging.DEBUG)
self.server = config.get_server()
prefix_sections = config.get_prefix_sections("wled")
logging.info(f"WLED component loading strips: {prefix_sections}")
strip_types = {
"HTTP": StripHttp,
"SERIAL": StripSerial
}
self.strips = {}
for section in prefix_sections:
cfg = config[section]
try:
name_parts = cfg.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise cfg.error(
f"Invalid Section Name: {cfg.get_name()}")
name: str = name_parts[1]
logging.info(f"WLED strip: {name}")
# Discard old color_order setting, always support 4 color strips
_ = cfg.get("color_order", "", deprecate=True)
strip_type: str = cfg.get("type", "http")
strip_class: Optional[Type[Strip]]
strip_class = strip_types.get(strip_type.upper())
if strip_class is None:
raise config.error(f"Unsupported Strip Type: {strip_type}")
self.strips[name] = strip_class(name, cfg)
except Exception as e:
# Ensures errors such as "Color not supported" are visible
msg = f"Failed to initialise strip [{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
# Register two remote methods for GCODE
self.server.register_remote_method(
"set_wled_state", self.set_wled_state)
self.server.register_remote_method(
"set_wled", self.set_wled)
# As moonraker is about making things a web api, let's try it
# Yes, this is largely a cut-n-paste from power.py
self.server.register_endpoint(
"/machine/wled/strips", ["GET"],
self._handle_list_strips)
self.server.register_endpoint(
"/machine/wled/status", ["GET"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/on", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/off", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/toggle", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/strip", ["GET", "POST"],
self._handle_single_wled_request)
async def component_init(self) -> None:
try:
logging.debug("Initializing wled")
event_loop = self.server.get_event_loop()
cur_time = event_loop.get_loop_time()
endtime = cur_time + 120.
query_strips = list(self.strips.values())
failed_strips: List[Strip] = []
while cur_time < endtime:
for strip in query_strips:
ret = strip.initialize()
if ret is not None:
await ret
if strip.error_state is not None:
failed_strips.append(strip)
if not failed_strips:
logging.debug("All wled strips initialized")
return
query_strips = failed_strips
failed_strips = []
await asyncio.sleep(2.)
cur_time = event_loop.get_loop_time()
if failed_strips:
failed_names = [s.name for s in failed_strips]
self.server.add_warning(
"The following wled strips failed init:"
f" {failed_names}")
except Exception as e:
logging.exception(e)
async def wled_on(self: WLED, strip: str, preset: int) -> None:
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
await self.strips[strip].wled_on(preset)
# Full control of wled
# state: True, False, "on", "off"
# preset: wled preset (int) to use (ignored if state False or "Off")
async def set_wled_state(
self: WLED,
strip: str,
state: Optional[str] = None,
preset: int = -1,
brightness: int = -1,
intensity: int = -1,
speed: int = -1
) -> None:
status = None
if isinstance(state, bool):
status = OnOff.on if state else OnOff.off
elif isinstance(state, str):
status = state.lower()
if status in ["true", "false"]:
status = OnOff.on if status == "true" else OnOff.off
if status is None and preset == -1 and brightness == -1 and \
intensity == -1 and speed == -1:
logging.info(
f"Invalid state received but no control or preset data passed")
return
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
# All other arguments are ignored
if status == OnOff.off:
await self.strips[strip].wled_off()
# Turn on if on or a preset is specified
if status == OnOff.on or preset != -1:
await self.strips[strip].wled_on(preset)
# Control
if brightness != -1 or intensity != -1 or speed != -1:
await self.strips[strip].wled_control(brightness, intensity, speed)
# Individual pixel control, for compatibility with SET_LED
async def set_wled(self: WLED,
strip: str,
red: float = 0.,
green: float = 0.,
blue: float = 0.,
white: float = 0.,
index: Optional[int] = None,
transmit: int = 1) -> None:
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
if isinstance(index, int) and index < 0:
index = None
await self.strips[strip].set_wled(red, green, blue, white,
index,
True if transmit == 1 else False)
async def _handle_list_strips(self,
web_request: WebRequest
) -> Dict[str, Any]:
strips = {name: strip.get_strip_info()
for name, strip in self.strips.items()}
output = {"strips": strips}
return output
async def _handle_single_wled_request(self: WLED,
web_request: WebRequest
) -> Dict[str, Any]:
strip_name: str = web_request.get_str('strip')
preset: int = web_request.get_int('preset', -1)
brightness: int = web_request.get_int('brightness', -1)
intensity: int = web_request.get_int('intensity', -1)
speed: int = web_request.get_int('speed', -1)
req_action = web_request.get_action()
if strip_name not in self.strips:
raise self.server.error(f"No valid strip named {strip_name}")
strip = self.strips[strip_name]
if req_action == 'GET':
return {strip_name: strip.get_strip_info()}
elif req_action == "POST":
action = web_request.get_str('action').lower()
if action not in ["on", "off", "toggle", "control"]:
raise self.server.error(
f"Invalid requested action '{action}'")
result = await self._process_request(strip, action, preset,
brightness, intensity, speed)
return {strip_name: result}
async def _handle_batch_wled_request(self: WLED,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
ep = web_request.get_endpoint()
if not args:
raise self.server.error("No arguments provided")
requested_strips = {k: self.strips.get(k, None) for k in args}
result = {}
req = ep.split("/")[-1]
for name, strip in requested_strips.items():
if strip is not None:
result[name] = await self._process_request(strip, req, -1,
-1, -1, -1)
else:
result[name] = {"error": "strip_not_found"}
return result
async def _process_request(self: WLED,
strip: Strip,
req: str,
preset: int,
brightness: int,
intensity: int,
speed: int
) -> Dict[str, Any]:
strip_onoff = strip.onoff
if req == "status":
return strip.get_strip_info()
if req == "toggle":
req = "on" if strip_onoff == OnOff.off else "off"
if req in ["on", "off", "control"]:
# Always do something, could be turning off colors, or changing
# preset, easier not to have to worry
if req == "on" or req == "control":
if req == "on":
strip_onoff = OnOff.on
await strip.wled_on(preset)
if brightness != -1 or intensity != -1 or speed != -1:
await strip.wled_control(brightness, intensity, speed)
else:
strip_onoff = OnOff.off
await strip.wled_off()
return strip.get_strip_info()
raise self.server.error(f"Unsupported wled request: {req}")
def close(self) -> None:
for strip in self.strips.values():
strip.close()
def load_component(config: ConfigHelper) -> WLED:
return WLED(config)
+108
View File
@@ -0,0 +1,108 @@
# Zeroconf registration implementation for Moonraker
#
# Copyright (C) 2021 Clifford Roche <clifford.roche@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import socket
import asyncio
import logging
import ipaddress
from zeroconf import IPVersion
from zeroconf.asyncio import AsyncServiceInfo, AsyncZeroconf
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .machine import Machine
class AsyncRunner:
def __init__(self, ip_version: IPVersion) -> None:
self.ip_version = ip_version
self.aiozc: Optional[AsyncZeroconf] = None
async def register_services(self, infos: List[AsyncServiceInfo]) -> None:
self.aiozc = AsyncZeroconf(ip_version=self.ip_version)
tasks = [
self.aiozc.async_register_service(info, allow_name_change=True)
for info in infos
]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
async def unregister_services(self, infos: List[AsyncServiceInfo]) -> None:
assert self.aiozc is not None
tasks = [self.aiozc.async_unregister_service(info) for info in infos]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
await self.aiozc.async_close()
async def update_services(self, infos: List[AsyncServiceInfo]) -> None:
assert self.aiozc is not None
tasks = [self.aiozc.async_update_service(info) for info in infos]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
class ZeroconfRegistrar:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.runner = AsyncRunner(IPVersion.All)
hi = self.server.get_host_info()
addr: str = hi["address"]
if addr.lower() == "all":
addr = "::"
host_ip = ipaddress.ip_address(addr)
fam = socket.AF_INET6 if host_ip.version == 6 else socket.AF_INET
addresses: List[bytes] = [(socket.inet_pton(fam, addr))]
self.bound_all = addr in ["0.0.0.0", "::"]
self.service_info = self._build_service_info(addresses)
if self.bound_all:
self.server.register_event_handler(
"machine:net_state_changed", self._update_service)
async def component_init(self) -> None:
logging.info("Starting Zeroconf services")
if self.bound_all:
machine: Machine = self.server.lookup_component("machine")
network = machine.get_system_info()["network"]
addresses = [x for x in self._extract_ip_addresses(network)]
self.service_info = self._build_service_info(addresses)
await self.runner.register_services([self.service_info])
async def close(self) -> None:
await self.runner.unregister_services([self.service_info])
async def _update_service(self, network: Dict[str, Any]) -> None:
if self.bound_all:
addresses = [x for x in self._extract_ip_addresses(network)]
self.service_info = self._build_service_info(addresses)
await self.runner.update_services([self.service_info])
def _build_service_info(self,
addresses: Optional[List[bytes]] = None
) -> AsyncServiceInfo:
hi = self.server.get_host_info()
return AsyncServiceInfo(
"_moonraker._tcp.local.",
f"Moonraker Instance on {hi['hostname']}._moonraker._tcp.local.",
addresses=addresses,
port=hi["port"],
properties={"path": "/"},
server=f"{hi['hostname']}.local.",
)
def _extract_ip_addresses(self, network: Dict[str, Any]) -> Iterator[bytes]:
for ifname, ifinfo in network.items():
for addr_info in ifinfo["ip_addresses"]:
if addr_info["is_link_local"]:
continue
is_ipv6 = addr_info['family'] == "ipv6"
family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
yield socket.inet_pton(family, addr_info["address"])
def load_component(config: ConfigHelper) -> ZeroconfRegistrar:
return ZeroconfRegistrar(config)
File diff suppressed because it is too large. Load diff
+188
View File
@@ -0,0 +1,188 @@
# Wrapper around the asyncio eventloop
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import inspect
import functools
import socket
import time
import logging
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Optional,
Tuple,
TypeVar,
Union
)
if TYPE_CHECKING:
_T = TypeVar("_T")
FlexCallback = Callable[..., Optional[Awaitable]]
TimerCallback = Callable[[float], Union[float, Awaitable[float]]]
class EventLoop:
TimeoutError = asyncio.TimeoutError
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self.aioloop = self._create_new_loop()
self.add_signal_handler = self.aioloop.add_signal_handler
self.remove_signal_handler = self.aioloop.remove_signal_handler
self.add_reader = self.aioloop.add_reader
self.add_writer = self.aioloop.add_writer
self.remove_reader = self.aioloop.remove_reader
self.remove_writer = self.aioloop.remove_writer
self.get_loop_time = self.aioloop.time
self.create_future = self.aioloop.create_future
self.create_task = self.aioloop.create_task
self.call_at = self.aioloop.call_at
self.set_debug = self.aioloop.set_debug
self.is_running = self.aioloop.is_running
def _create_new_loop(self) -> asyncio.AbstractEventLoop:
for _ in range(5):
# Sometimes the new loop does not properly instantiate.
# Give 5 attempts before raising an exception
new_loop = asyncio.new_event_loop()
if not new_loop.is_closed():
break
logging.info("Failed to create open eventloop, "
"retyring in .5 seconds...")
time.sleep(.5)
else:
raise RuntimeError("Unable to create new open eventloop")
asyncio.set_event_loop(new_loop)
return new_loop
def register_callback(self,
callback: FlexCallback,
*args,
**kwargs
) -> None:
async def _wrapper():
try:
ret = callback(*args, **kwargs)
if inspect.isawaitable(ret):
await ret
except asyncio.CancelledError:
raise
except Exception:
logging.exception("Error Running Callback")
self.aioloop.create_task(_wrapper())
def delay_callback(self,
delay: float,
callback: FlexCallback,
*args,
**kwargs
) -> asyncio.TimerHandle:
return self.aioloop.call_later(
delay, self.register_callback,
functools.partial(callback, *args, **kwargs)
)
def register_timer(self, callback: TimerCallback):
return FlexTimer(self, callback)
def run_in_thread(self,
callback: Callable[..., _T],
*args
) -> Awaitable[_T]:
return self.aioloop.run_in_executor(None, callback, *args)
async def create_socket_connection(
self, address: Tuple[str, int], timeout: Optional[float] = None
) -> socket.socket:
host, port = address
"""
async port of socket.create_connection()
"""
loop = self.aioloop
err = None
ainfo = await loop.getaddrinfo(
host, port, family=0, type=socket.SOCK_STREAM
)
for res in ainfo:
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
sock.settimeout(0)
sock.setblocking(False)
await asyncio.wait_for(
loop.sock_connect(sock, (host, port)), timeout
)
# Break explicitly a reference cycle
err = None
return sock
except (socket.error, asyncio.TimeoutError) as _:
err = _
if sock is not None:
loop.remove_writer(sock.fileno())
sock.close()
if err is not None:
try:
raise err
finally:
# Break explicitly a reference cycle
err = None
else:
raise socket.error("getaddrinfo returns an empty list")
def start(self):
self.aioloop.run_forever()
def stop(self):
self.aioloop.stop()
def close(self):
self.aioloop.close()
class FlexTimer:
def __init__(self,
eventloop: EventLoop,
callback: TimerCallback
) -> None:
self.eventloop = eventloop
self.callback = callback
self.timer_handle: Optional[asyncio.TimerHandle] = None
self.running: bool = False
def start(self, delay: float = 0.):
if self.running:
return
self.running = True
call_time = self.eventloop.get_loop_time() + delay
self.timer_handle = self.eventloop.call_at(
call_time, self._schedule_task)
def stop(self):
if not self.running:
return
self.running = False
if self.timer_handle is not None:
self.timer_handle.cancel()
self.timer_handle = None
def _schedule_task(self):
self.timer_handle = None
self.eventloop.create_task(self._call_wrapper())
def is_running(self) -> bool:
return self.running
async def _call_wrapper(self):
if not self.running:
return
ret = self.callback(self.eventloop.get_loop_time())
if isinstance(ret, Awaitable):
ret = await ret
if self.running:
self.timer_handle = self.eventloop.call_at(ret, self._schedule_task)
+692
View File
@@ -0,0 +1,692 @@
# KlippyConnection - manage unix socket connection to Klipper
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import os
import time
import logging
import json
import getpass
import asyncio
import pathlib
from .utils import ServerError, get_unix_peer_credentials
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Optional,
Callable,
Coroutine,
Dict,
List,
Set,
Tuple
)
if TYPE_CHECKING:
from .server import Server
from .app import MoonrakerApp
from .websockets import WebRequest, Subscribable
from .confighelper import ConfigHelper
from .components.klippy_apis import KlippyAPI
from .components.file_manager.file_manager import FileManager
from .components.machine import Machine
from .components.job_state import JobState
FlexCallback = Callable[..., Optional[Coroutine]]
# These endpoints are reserved for klippy/moonraker communication only and are
# not exposed via http or the websocket
RESERVED_ENDPOINTS = [
"list_endpoints",
"gcode/subscribe_output",
"register_remote_method",
]
INIT_TIME = .25
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
class KlippyConnection:
def __init__(self, server: Server) -> None:
self.server = server
self.uds_address = pathlib.Path("/tmp/klippy_uds")
self.writer: Optional[asyncio.StreamWriter] = None
self.connection_mutex: asyncio.Lock = asyncio.Lock()
self.event_loop = self.server.get_event_loop()
self.log_no_access = True
# Connection State
self.connection_task: Optional[asyncio.Task] = None
self.closing: bool = False
self._klippy_info: Dict[str, Any] = {}
self._klippy_identified: bool = False
self._klippy_initializing: bool = False
self._klippy_started: bool = False
self._klipper_version: str = ""
self._missing_reqs: Set[str] = set()
self._peer_cred: Dict[str, int] = {}
self._service_info: Dict[str, Any] = {}
self.init_attempts: int = 0
self._state: str = "disconnected"
self._state_message: str = "Klippy Disconnected"
self.subscriptions: Dict[Subscribable, Dict[str, Any]] = {}
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
self.pending_requests: Dict[int, KlippyRequest] = {}
self.remote_methods: Dict[str, FlexCallback] = {}
self.klippy_reg_methods: List[str] = []
self.register_remote_method(
'process_gcode_response', self._process_gcode_response,
need_klippy_reg=False)
self.register_remote_method(
'process_status_update', self._process_status_update,
need_klippy_reg=False)
self.server.register_component("klippy_connection", self)
def configure(self, config: ConfigHelper):
self.uds_address = config.getpath(
"klippy_uds_address", self.uds_address
)
@property
def klippy_apis(self) -> KlippyAPI:
return self.server.lookup_component("klippy_apis")
@property
def state(self) -> str:
if self.is_connected() and not self._klippy_started:
return "startup"
return self._state
@property
def state_message(self) -> str:
return self._state_message
@property
def klippy_info(self) -> Dict[str, Any]:
return self._klippy_info
@property
def missing_requirements(self) -> List[str]:
return list(self._missing_reqs)
@property
def peer_credentials(self) -> Dict[str, int]:
return dict(self._peer_cred)
@property
def service_info(self) -> Dict[str, Any]:
return self._service_info
@property
def unit_name(self) -> str:
svc_info = self._service_info
unit_name = svc_info.get("unit_name", "klipper.service")
return unit_name.split(".", 1)[0]
async def wait_connected(self) -> bool:
if (
self.connection_task is None or
self.connection_task.done()
):
return self.is_connected()
try:
await self.connection_task
except Exception:
pass
return self.is_connected()
async def wait_started(self, timeout: float = 20.) -> bool:
if self.connection_task is None or not self.is_connected():
return False
if not self.connection_task.done():
await asyncio.wait_for(
asyncio.shield(self.connection_task), timeout=timeout)
return self.is_connected()
async def _read_stream(self, reader: asyncio.StreamReader) -> None:
errors_remaining: int = 10
while not reader.at_eof():
try:
data = await reader.readuntil(b'\x03')
except (ConnectionError, asyncio.IncompleteReadError):
break
except asyncio.CancelledError:
logging.exception("Klippy Stream Read Cancelled")
raise
except Exception:
logging.exception("Klippy Stream Read Error")
errors_remaining -= 1
if not errors_remaining or not self.is_connected():
break
continue
errors_remaining = 10
try:
decoded_cmd = json.loads(data[:-1])
self._process_command(decoded_cmd)
except Exception:
logging.exception(
f"Error processing Klippy Host Response: {data.decode()}")
if not self.closing:
logging.debug("Klippy Disconnection From _read_stream()")
await self.close()
async def _write_request(self, request: KlippyRequest) -> None:
if self.writer is None or self.closing:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Host not connected", 503))
return
data = json.dumps(request.to_dict()).encode() + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Write Request Cancelled", 503))
raise
except Exception:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Write Request Error", 503))
if not self.closing:
logging.debug("Klippy Disconnection From _write_request()")
await self.close()
def register_remote_method(self,
method_name: str,
cb: FlexCallback,
need_klippy_reg: bool = True
) -> None:
if method_name in self.remote_methods:
raise self.server.error(
f"Remote method ({method_name}) already registered")
if self.server.is_running():
raise self.server.error(
f"Failed to register remote method {method_name}, "
"methods must be registered during initialization")
self.remote_methods[method_name] = cb
if need_klippy_reg:
# These methods need to be registered with Klippy
self.klippy_reg_methods.append(method_name)
def connect(self) -> Awaitable[bool]:
if (
self.is_connected() or
not self.server.is_running() or
(self.connection_task is not None and
not self.connection_task.done())
):
# already connecting
fut = self.event_loop.create_future()
fut.set_result(self.is_connected())
return fut
self.connection_task = self.event_loop.create_task(self._do_connect())
return self.connection_task
async def _do_connect(self) -> bool:
async with self.connection_mutex:
while self.writer is None:
await asyncio.sleep(INIT_TIME)
if self.closing or not self.server.is_running():
return False
if not self.uds_address.exists():
continue
if not os.access(str(self.uds_address), os.R_OK | os.W_OK):
if self.log_no_access:
user = getpass.getuser()
logging.info(
f"Cannot connect to Klippy, Linux user '{user}' "
"lacks permission to open Unix Domain Socket: "
f"{self.uds_address}")
self.log_no_access = False
continue
self.log_no_access = True
try:
reader, writer = await self.open_klippy_connection(True)
except asyncio.CancelledError:
raise
except Exception:
continue
logging.info("Klippy Connection Established")
self.writer = writer
if self._get_peer_credentials(writer):
machine: Machine = self.server.lookup_component("machine")
provider = machine.get_system_provider()
svc_info = await provider.extract_service_info(
"klipper", self._peer_cred["process_id"]
)
if svc_info != self._service_info:
self._service_info = svc_info
machine.log_service_info(svc_info)
self.event_loop.create_task(self._read_stream(reader))
return await self._init_klippy_connection()
async def open_klippy_connection(
self, primary: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
if not primary and not self.is_connected():
raise ServerError("Klippy Unix Connection Not Available", 503)
return await asyncio.open_unix_connection(
str(self.uds_address), limit=UNIX_BUFFER_LIMIT)
def _get_peer_credentials(self, writer: asyncio.StreamWriter) -> bool:
self._peer_cred = get_unix_peer_credentials(writer, "Klippy")
if not self._peer_cred:
return False
logging.debug(
f"Klippy Connection: Received Peer Credentials: {self._peer_cred}"
)
return True
async def _init_klippy_connection(self) -> bool:
self._klippy_identified = False
self._klippy_started = False
self._klippy_initializing = True
self._missing_reqs.clear()
self.init_attempts = 0
self._state = "startup"
while self.server.is_running():
await asyncio.sleep(INIT_TIME)
await self._check_ready()
if not self._klippy_initializing:
logging.debug("Klippy Connection Initialized")
return True
if not self.is_connected():
self._klippy_initializing = False
break
else:
self.init_attempts += 1
logging.debug("Klippy Connection Failed to Init")
return False
async def _request_endpoints(self) -> None:
result = await self.klippy_apis.list_endpoints(default=None)
if result is None:
return
endpoints = result.get('endpoints', [])
app: MoonrakerApp = self.server.lookup_component("application")
for ep in endpoints:
if ep not in RESERVED_ENDPOINTS:
app.register_remote_handler(ep)
async def _request_initial_subscriptions(self) -> None:
try:
await self.klippy_apis.subscribe_objects({'webhooks': None})
except ServerError as e:
logging.exception("Unable to subscribe to webhooks object")
else:
logging.info("Webhooks Subscribed")
try:
await self.klippy_apis.subscribe_gcode_output()
except ServerError as e:
logging.exception(
"Unable to register gcode output subscription"
)
else:
logging.info("GCode Output Subscribed")
async def _check_ready(self) -> None:
send_id = not self._klippy_identified
result: Dict[str, Any]
try:
result = await self.klippy_apis.get_klippy_info(send_id)
except ServerError as e:
if self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
self.init_attempts <= MAX_LOG_ATTEMPTS:
logging.info(
f"{e}\nKlippy info request error. This indicates that\n"
f"Klippy may have experienced an error during startup.\n"
f"Please check klippy.log for more information")
return
version = result.get("software_version", "")
if version != self._klipper_version:
self._klipper_version = version
msg = f"Klipper Version: {version}"
self.server.add_log_rollover_item("klipper_version", msg)
self._klippy_info = dict(result)
if "state_message" in self._klippy_info:
self._state_message = self._klippy_info["state_message"]
if "state" not in result:
return
if send_id:
self._klippy_identified = True
await self.server.send_event("server:klippy_identified")
# Request initial endpoints to register info, emergency stop APIs
await self._request_endpoints()
self._state = result["state"]
if self._state != "startup":
await self._request_initial_subscriptions()
# Register remaining endpoints available
await self._request_endpoints()
startup_state = self._state
await self.server.send_event(
"server:klippy_started", startup_state
)
self._klippy_started = True
if self._state != "ready":
logging.info("\n" + self._state_message)
if self._state == "shutdown" and startup_state != "shutdown":
# Klippy shutdown during startup event
self.server.send_event("server:klippy_shutdown")
else:
await self._verify_klippy_requirements()
# register methods with klippy
for method in self.klippy_reg_methods:
try:
await self.klippy_apis.register_method(method)
except ServerError:
logging.exception(
f"Unable to register method '{method}'")
if self._state == "ready":
logging.info("Klippy ready")
await self.server.send_event("server:klippy_ready")
if self._state == "shutdown":
# Klippy shutdown during ready event
self.server.send_event("server:klippy_shutdown")
else:
logging.info(
"Klippy state transition from ready during init, "
f"new state: {self._state}"
)
self._klippy_initializing = False
async def _verify_klippy_requirements(self) -> None:
result = await self.klippy_apis.get_object_list(default=None)
if result is None:
logging.info(
f"Unable to retrieve Klipper Object List")
return
req_objs = set(["virtual_sdcard", "display_status", "pause_resume"])
self._missing_reqs = req_objs - set(result)
if self._missing_reqs:
err_str = ", ".join([f"[{o}]" for o in self._missing_reqs])
logging.info(
f"\nWarning, unable to detect the following printer "
f"objects:\n{err_str}\nPlease add the the above sections "
f"to printer.cfg for full Moonraker functionality.")
if "virtual_sdcard" not in self._missing_reqs:
# Update the gcode path
query_res = await self.klippy_apis.query_objects(
{'configfile': None}, default=None)
if query_res is None:
logging.info(f"Unable to set SD Card path")
else:
config = query_res.get('configfile', {}).get('config', {})
vsd_config = config.get('virtual_sdcard', {})
vsd_path = vsd_config.get('path', None)
if vsd_path is not None:
file_manager: FileManager = self.server.lookup_component(
'file_manager')
file_manager.validate_gcode_path(vsd_path)
else:
logging.info(
"Configuration for [virtual_sdcard] not found,"
" unable to set SD Card path")
def _process_command(self, cmd: Dict[str, Any]) -> None:
method = cmd.get('method', None)
if method is not None:
# This is a remote method called from klippy
if method in self.remote_methods:
params = cmd.get('params', {})
self.event_loop.register_callback(
self._execute_method, method, **params)
else:
logging.info(f"Unknown method received: {method}")
return
# This is a response to a request, process
req_id = cmd.get('id', None)
request: Optional[KlippyRequest]
request = self.pending_requests.pop(req_id, None)
if request is None:
logging.info(
f"No request matching request ID: {req_id}, "
f"response: {cmd}")
return
if 'result' in cmd:
result = cmd['result']
if not result:
result = "ok"
else:
err = cmd.get('error', "Malformed Klippy Response")
result = ServerError(err, 400)
request.notify(result)
async def _execute_method(self, method_name: str, **kwargs) -> None:
try:
ret = self.remote_methods[method_name](**kwargs)
if ret is not None:
await ret
except Exception:
logging.exception(f"Error running remote method: {method_name}")
def _process_gcode_response(self, response: str) -> None:
self.server.send_event("server:gcode_response", response)
def _process_status_update(self,
eventtime: float,
status: Dict[str, Any]
) -> None:
if 'webhooks' in status:
wh: Dict[str, str] = status['webhooks']
if "state_message" in wh:
self._state_message = wh["state_message"]
# XXX - process other states (startup, ready, error, etc)?
if "state" in wh:
state = wh["state"]
if state == "shutdown" and not self._klippy_initializing:
# If the shutdown state is received during initialization
# defer the event, the init routine will handle it.
logging.info("Klippy has shutdown")
self.server.send_event("server:klippy_shutdown")
self._state = state
for conn, sub in self.subscriptions.items():
conn_status: Dict[str, Any] = {}
for name, fields in sub.items():
if name in status:
val: Dict[str, Any] = dict(status[name])
if fields is not None:
val = {k: v for k, v in val.items() if k in fields}
if val:
conn_status[name] = val
conn.send_status(conn_status, eventtime)
async def request(self, web_request: WebRequest) -> Any:
if not self.is_connected():
raise ServerError("Klippy Host not connected", 503)
rpc_method = web_request.get_endpoint()
if rpc_method == "objects/subscribe":
return await self._request_subscripton(web_request)
else:
if rpc_method == "gcode/script":
script = web_request.get_str('script', "")
if script:
self.server.send_event(
"klippy_connection:gcode_received", script)
return await self._request_standard(web_request)
async def _request_subscripton(self,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
conn = web_request.get_subscribable()
# Build the subscription request from a superset of all client
# subscriptions
sub = args.get('objects', {})
if conn is None:
raise self.server.error(
"No connection associated with subscription request")
self.subscriptions[conn] = sub
all_subs: Dict[str, Any] = {}
# request superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
if obj in all_subs:
pi = all_subs[obj]
if items is None or pi is None:
all_subs[obj] = None
else:
uitems = list(set(pi) | set(items))
all_subs[obj] = uitems
else:
all_subs[obj] = items
args['objects'] = all_subs
args['response_template'] = {'method': "process_status_update"}
result = await self._request_standard(web_request)
# prune the status response
pruned_status = {}
all_status = result['status']
sub = self.subscriptions.get(conn, {})
for obj, fields in all_status.items():
if obj in sub:
valid_fields = sub[obj]
if valid_fields is None:
pruned_status[obj] = fields
else:
pruned_status[obj] = {k: v for k, v in fields.items()
if k in valid_fields}
result['status'] = pruned_status
return result
async def _request_standard(self, web_request: WebRequest) -> Any:
rpc_method = web_request.get_endpoint()
args = web_request.get_args()
# Create a base klippy request
base_request = KlippyRequest(rpc_method, args)
self.pending_requests[base_request.id] = base_request
self.event_loop.register_callback(self._write_request, base_request)
return await base_request.wait()
def remove_subscription(self, conn: Subscribable) -> None:
self.subscriptions.pop(conn, None)
def is_connected(self) -> bool:
return self.writer is not None and not self.closing
def is_ready(self) -> bool:
return self._state == "ready"
def is_printing(self) -> bool:
if not self.is_ready():
return False
job_state: JobState = self.server.lookup_component("job_state")
stats = job_state.get_last_stats()
return stats.get("state", "") == "printing"
async def rollover_log(self) -> None:
if "unit_name" not in self._service_info:
raise self.server.error(
"Unable to detect Klipper Service, cannot perform "
"manual rollover"
)
logfile: Optional[str] = self._klippy_info.get("log_file", None)
if logfile is None:
raise self.server.error(
"Unable to detect path to Klipper log file"
)
if self.is_printing():
raise self.server.error("Cannot rollover log while printing")
logpath = pathlib.Path(logfile).expanduser().resolve()
if not logpath.is_file():
raise self.server.error(
f"No file at {logpath} exists, cannot perform rollover"
)
machine: Machine = self.server.lookup_component("machine")
await machine.do_service_action("stop", self.unit_name)
suffix = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
new_path = pathlib.Path(f"{logpath}.{suffix}")
def _do_file_op() -> None:
if new_path.exists():
new_path.unlink()
logpath.rename(new_path)
await self.event_loop.run_in_thread(_do_file_op)
await machine.do_service_action("start", self.unit_name)
async def _on_connection_closed(self) -> None:
self._klippy_identified = False
self._klippy_initializing = False
self._klippy_started = False
self._state = "disconnected"
self._state_message = "Klippy Disconnected"
for request in self.pending_requests.values():
request.notify(ServerError("Klippy Disconnected", 503))
self.pending_requests = {}
self.subscriptions = {}
self._peer_cred = {}
self._missing_reqs.clear()
logging.info("Klippy Connection Removed")
await self.server.send_event("server:klippy_disconnect")
if self.server.is_running():
# Reconnect if server is running
loop = self.event_loop
self.connection_task = loop.create_task(self._do_connect())
async def close(self, wait_closed: bool = False) -> None:
if self.closing:
if wait_closed:
await self.connection_mutex.acquire()
self.connection_mutex.release()
return
self.closing = True
if (
self.connection_task is not None and
not self.connection_task.done()
):
self.connection_task.cancel()
async with self.connection_mutex:
if self.writer is not None:
try:
self.writer.close()
await self.writer.wait_closed()
except Exception:
logging.exception("Error closing Klippy Unix Socket")
self.writer = None
await self._on_connection_closed()
self.closing = False
# Basic KlippyRequest class, easily converted to dict for json encoding
class KlippyRequest:
def __init__(self, rpc_method: str, params: Dict[str, Any]) -> None:
self.id = id(self)
self.rpc_method = rpc_method
self.params = params
self._event = asyncio.Event()
self.response: Any = None
async def wait(self) -> Any:
# Log pending requests every 60 seconds
start_time = time.time()
while True:
try:
await asyncio.wait_for(self._event.wait(), 60.)
except asyncio.TimeoutError:
pending_time = time.time() - start_time
logging.info(
f"Request '{self.rpc_method}' pending: "
f"{pending_time:.2f} seconds")
self._event.clear()
continue
break
if isinstance(self.response, ServerError):
raise self.response
return self.response
def notify(self, response: Any) -> None:
if self._event.is_set():
return
self.response = response
self._event.set()
def to_dict(self) -> Dict[str, Any]:
return {'id': self.id, 'method': self.rpc_method,
'params': self.params}
+153
View File
@@ -0,0 +1,153 @@
# Log Management
#
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import logging.handlers
import os
import sys
import asyncio
from queue import SimpleQueue as Queue
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional,
Awaitable,
Dict,
List,
Any,
)
if TYPE_CHECKING:
from .server import Server
from .websockets import WebRequest
from .klippy_connection import KlippyConnection
# 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, app_args: Dict[str, Any], **kwargs) -> None:
super().__init__(app_args['log_file'], **kwargs)
self.rollover_info: Dict[str, str] = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
}
self.rollover_info['application_args'] = "\n".join(
[f"{k}: {v}" for k, v in app_args.items()])
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
def set_rollover_info(self, name: str, item: str) -> None:
self.rollover_info[name] = item
def doRollover(self) -> None:
super().doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
class LogManager:
def __init__(
self, app_args: Dict[str, Any], startup_warnings: List[str]
) -> None:
root_logger = logging.getLogger()
queue: Queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
for name, val in app_args.items():
logging.info(f"{name}: {val}")
self.file_hdlr: Optional[MoonrakerLoggingHandler] = None
self.listener: Optional[logging.handlers.QueueListener] = None
log_file: str = app_args.get('log_file', "")
if log_file:
try:
self.file_hdlr = MoonrakerLoggingHandler(
app_args, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
self.file_hdlr.setFormatter(formatter)
self.listener = logging.handlers.QueueListener(
queue, self.file_hdlr, stdout_hdlr)
except Exception:
log_file = os.path.normpath(log_file)
dir_name = os.path.dirname(log_file)
startup_warnings.append(
f"Unable to create log file at '{log_file}'. "
f"Make sure that the folder '{dir_name}' exists "
"and Moonraker has Read/Write access to the folder. "
)
if self.listener is None:
self.listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
self.listener.start()
def set_server(self, server: Server) -> None:
self.server = server
self.server.register_endpoint(
"/server/logs/rollover", ['POST'], self._handle_log_rollover
)
def set_rollover_info(self, name: str, item: str) -> None:
if self.file_hdlr is not None:
self.file_hdlr.set_rollover_info(name, item)
def rollover_log(self) -> Awaitable[None]:
if self.file_hdlr is None:
raise self.server.error("File Logging Disabled")
eventloop = self.server.get_event_loop()
return eventloop.run_in_thread(self.file_hdlr.doRollover)
def stop_logging(self):
self.listener.stop()
async def _handle_log_rollover(
self, web_request: WebRequest
) -> Dict[str, Any]:
log_apps = ["moonraker", "klipper"]
app = web_request.get_str("application", None)
result: Dict[str, Any] = {"rolled_over": [], "failed": {}}
if app is not None:
if app not in log_apps:
raise self.server.error(f"Unknown application {app}")
log_apps = [app]
if "moonraker" in log_apps:
try:
ret = self.rollover_log()
if ret is not None:
await ret
except asyncio.CancelledError:
raise
except Exception as e:
result["failed"]["moonraker"] = str(e)
else:
result["rolled_over"].append("moonraker")
if "klipper" in log_apps:
kconn: KlippyConnection
kconn = self.server.lookup_component("klippy_connection")
try:
await kconn.rollover_log()
except self.server.error as e:
result["failed"]["klipper"] = str(e)
else:
result["rolled_over"].append("klipper")
return result
Regular → Executable
+12 -476
View File
@@ -1,481 +1,17 @@
# Moonraker - HTTP/Websocket API Server for Klipper
#!/usr/bin/env python3
# Legacy entry point for Moonraker
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import argparse
import sys
import importlib
import os
import time
import socket
import logging
import json
import errno
import tornado
import tornado.netutil
from tornado import gen
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.util import TimeoutError
from tornado.locks import Event
from app import MoonrakerApp
from utils import ServerError, MoonrakerLoggingHandler
INIT_MS = 1000
CORE_PLUGINS = [
'file_manager', 'gcode_apis', 'machine',
'temperature_store', 'shell_command']
class Sentinel:
pass
class Server:
error = ServerError
def __init__(self, args):
self.host = args.address
self.port = args.port
# Options configurable by Klippy
self.request_timeout = 5.
self.long_running_gcodes = {}
self.long_running_requests = {}
# Event initialization
self.events = {}
# Klippy Connection Handling
socketfile = os.path.normpath(os.path.expanduser(args.socketfile))
self.klippy_server_sock = tornado.netutil.bind_unix_socket(
socketfile, backlog=1)
self.remove_server_sock = tornado.netutil.add_accept_handler(
self.klippy_server_sock, self._handle_klippy_connection)
self.klippy_sock = None
self.is_klippy_connected = False
self.is_klippy_ready = False
self.server_configured = False
self.partial_data = b""
# Server/IOLoop
self.server_running = False
self.moonraker_app = app = MoonrakerApp(self, args)
self.io_loop = IOLoop.current()
self.init_cb = PeriodicCallback(self._initialize, INIT_MS)
# Plugin initialization
self.plugins = {}
self.register_endpoint = app.register_local_handler
self.register_static_file_handler = app.register_static_file_handler
self.register_upload_handler = app.register_upload_handler
for plugin in CORE_PLUGINS:
self.load_plugin(plugin)
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
self.pending_requests = {}
self.remote_methods = {}
self.register_remote_method(
'set_klippy_shutdown', self._set_klippy_shutdown)
self.register_remote_method(
'response', self._handle_klippy_response)
self.register_remote_method(
'process_gcode_response', self._process_gcode_response)
self.register_remote_method(
'process_status_update', self._process_status_update)
def start(self):
logging.info(
"Starting Moonraker on (%s, %d)" %
(self.host, self.port))
self.moonraker_app.listen(self.host, self.port)
self.server_running = True
# ***** Plugin Management *****
def load_plugin(self, plugin_name, default=Sentinel):
if plugin_name in self.plugins:
return self.plugins[plugin_name]
# Make sure plugin exists
mod_path = os.path.join(
os.path.dirname(__file__), 'plugins', plugin_name + '.py')
if not os.path.exists(mod_path):
msg = "Plugin (%s) does not exist" % (plugin_name)
logging.info(msg)
if default == Sentinel:
raise ServerError(msg)
return default
module = importlib.import_module("plugins." + plugin_name)
try:
load_func = getattr(module, "load_plugin")
plugin = load_func(self)
except Exception:
msg = "Unable to load plugin (%s)" % (plugin_name)
logging.info(msg)
if default == Sentinel:
raise ServerError(msg)
return default
self.plugins[plugin_name] = plugin
logging.info("Plugin (%s) loaded" % (plugin_name))
return plugin
def lookup_plugin(self, plugin_name, default=Sentinel):
plugin = self.plugins.get(plugin_name, default)
if plugin == Sentinel:
raise ServerError("Plugin (%s) not found" % (plugin_name))
return plugin
def register_event_handler(self, event, callback):
self.events.setdefault(event, []).append(callback)
def send_event(self, event, *args):
events = self.events.get(event, [])
for evt in events:
self.io_loop.spawn_callback(evt, *args)
def register_remote_method(self, method_name, cb):
if method_name in self.remote_methods:
# XXX - may want to raise an exception here
logging.info("Remote method (%s) already registered"
% (method_name))
return
self.remote_methods[method_name] = cb
# ***** Klippy Connection *****
def _handle_klippy_connection(self, conn, addr):
if self.is_klippy_connected:
logging.info("New Connection received while Klippy Connected")
self.close_client_sock()
logging.info("Klippy Connection Established")
self.is_klippy_connected = True
conn.setblocking(0)
self.klippy_sock = conn
self.io_loop.add_handler(
self.klippy_sock.fileno(), self._handle_klippy_data,
IOLoop.READ | IOLoop.ERROR)
# begin server iniialization
self.init_cb.start()
def _handle_klippy_data(self, fd, events):
if events & IOLoop.ERROR:
self.close_client_sock()
return
try:
data = self.klippy_sock.recv(4096)
except socket.error as e:
# If bad file descriptor allow connection to be
# closed by the data check
if e.errno == errno.EBADF:
data = b''
else:
return
if data == b'':
# Socket Closed
self.close_client_sock()
return
commands = data.split(b'\x03')
commands[0] = self.partial_data + commands[0]
self.partial_data = commands.pop()
for cmd in commands:
try:
decoded_cmd = json.loads(cmd)
method = decoded_cmd.get('method')
params = decoded_cmd.get('params', {})
cb = self.remote_methods.get(method)
if cb is not None:
cb(**params)
else:
logging.info("Unknown command received %s" % cmd.decode())
except Exception:
logging.exception(
"Error processing Klippy Host Response: %s"
% (cmd.decode()))
def klippy_send(self, data):
# TODO: need a mutex or lock to make sure that multiple co-routines
# do not attempt to send
if not self.is_klippy_connected:
return False
retries = 10
data = json.dumps(data).encode() + b"\x03"
while data:
try:
sent = self.klippy_sock.send(data)
except socket.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE \
or not retries:
sent = 0
else:
# XXX - Should pause for 1ms here
retries -= 1
continue
retries = 10
if sent > 0:
data = data[sent:]
else:
logging.info("Error sending client data, closing socket")
self.close_client_sock()
return False
return True
async def _initialize(self):
await self._request_endpoints()
if not self.server_configured:
await self._request_config()
if not self.is_klippy_ready:
await self._request_ready()
if self.is_klippy_ready and self.server_configured:
# Make sure we have all registered endpoints
await self._request_endpoints()
self.init_cb.stop()
async def _request_endpoints(self):
request = self.make_request("list_endpoints", "GET", {})
result = await request.wait()
if not isinstance(result, ServerError):
endpoints = result.get('hooks', {})
static_paths = result.get('static_paths', {})
for ep in endpoints:
self.moonraker_app.register_remote_handler(ep)
for sp in static_paths:
self.moonraker_app.register_static_file_handler(
sp['resource_id'], sp['file_path'])
async def _request_config(self):
request = self.make_request(
"moonraker/get_configuration", "GET", {})
result = await request.wait()
if not isinstance(result, ServerError):
self._load_config(result)
self.server_configured = True
else:
logging.info(
"Error receiving configuration. This indicates a "
"potential configuration issue in printer.cfg. Please check "
"klippy.log for more information")
async def _request_ready(self):
request = self.make_request("info", "GET", {})
result = await request.wait()
if not isinstance(result, ServerError):
is_ready = result.get("is_ready", False)
if is_ready:
self._set_klippy_ready()
else:
msg = result.get("message", "Klippy Not Ready")
logging.info(msg)
else:
logging.info(
"Klippy Info request error. This indicates a that Klippy "
"may have experienced an error during startup. Please check "
"klippy.log for more information")
def _load_config(self, config):
self.request_timeout = config.get(
'request_timeout', self.request_timeout)
self.long_running_gcodes = config.get(
'long_running_gcodes', self.long_running_gcodes)
self.long_running_requests = config.get(
'long_running_requests', self.long_running_requests)
self.moonraker_app.load_config(config)
# load config for core plugins
for plugin_name in CORE_PLUGINS:
plugin = self.plugins[plugin_name]
if hasattr(plugin, "load_config"):
plugin.load_config(config)
# Load and apply optional plugin Configuration
plugin_cfgs = {name[7:]: cfg for name, cfg in config.items()
if name.startswith("plugin_")}
for name, cfg in plugin_cfgs.items():
plugin = self.plugins.get(name)
if plugin is None:
plugin = self.load_plugin(name, None)
if hasattr(plugin, "load_config"):
plugin.load_config(cfg)
# Remove plugins that are loaded but no longer configured
valid_plugins = CORE_PLUGINS + list(plugin_cfgs.keys())
self.io_loop.spawn_callback(self._prune_plugins, valid_plugins)
async def _prune_plugins(self, valid_plugins):
for name, plugin in self.plugins.items():
if name not in valid_plugins:
if hasattr(plugin, "close"):
await plugin.close()
self.plugins.pop(name, None)
def _handle_klippy_response(self, request_id, response):
req = self.pending_requests.pop(request_id, None)
if req is not None:
if isinstance(response, dict) and 'error' in response:
response = ServerError(response['message'], 400)
req.notify(response)
else:
logging.info("No request matching response: " + str(response))
def _set_klippy_ready(self):
logging.info("Klippy ready")
self.is_klippy_ready = True
self.send_event("server:klippy_state_changed", "ready")
def _set_klippy_shutdown(self):
logging.info("Klippy has shutdown")
self.is_klippy_ready = False
self.send_event("server:klippy_state_changed", "shutdown")
def _process_gcode_response(self, response):
self.send_event("server:gcode_response", response)
def _process_status_update(self, status):
self.send_event("server:status_update", status)
def make_request(self, path, method, args):
timeout = self.long_running_requests.get(path, self.request_timeout)
if path == "gcode/script":
script = args.get('script', "")
base_gc = script.strip().split()[0].upper()
timeout = self.long_running_gcodes.get(base_gc, timeout)
base_request = BaseRequest(path, method, args, timeout)
self.pending_requests[base_request.id] = base_request
ret = self.klippy_send(base_request.to_dict())
if not ret:
self.pending_requests.pop(base_request.id, None)
base_request.notify(
ServerError("Klippy Host not connected", 503))
return base_request
async def _kill_server(self):
# XXX - Currently this function is not used.
# Should I expose functionality to shutdown
# or restart the server, or simply remove this?
logging.info(
"Shutting Down Webserver")
for plugin in self.plugins:
if hasattr(plugin, "close"):
await plugin.close()
self.close_client_sock()
self.close_server_sock()
if self.server_running:
self.server_running = False
await self.moonraker_app.close()
self.io_loop.stop()
def close_client_sock(self):
self.is_klippy_ready = False
self.server_configured = False
self.init_cb.stop()
if self.is_klippy_connected:
self.is_klippy_connected = False
logging.info("Klippy Connection Removed")
try:
self.io_loop.remove_handler(self.klippy_sock.fileno())
self.klippy_sock.close()
except socket.error:
logging.exception("Error Closing Client Socket")
self.send_event("server:klippy_state_changed", "disconnect")
def close_server_sock(self):
try:
self.remove_server_sock()
self.klippy_server_sock.close()
# XXX - remove server sock file (or use abstract?)
except Exception:
logging.exception("Error Closing Server Socket")
# Basic WebRequest class, easily converted to dict for json encoding
class BaseRequest:
def __init__(self, path, method, args, timeout=None):
self.id = id(self)
self.path = path
self.method = method
self.args = args
self._timeout = timeout
self._event = Event()
self.response = None
if timeout is not None:
self._timeout = time.time() + timeout
async def wait(self):
# Wait for klippy to process the request or until the timeout
# has been reached.
try:
await self._event.wait(timeout=self._timeout)
except TimeoutError:
logging.info("Request '%s' Timed Out" %
(self.method + " " + self.path))
return ServerError("Klippy Request Timed Out", 500)
return self.response
def notify(self, response):
self.response = response
self._event.set()
def to_dict(self):
return {'id': self.id, 'path': self.path,
'method': self.method, 'args': self.args}
def main():
# Parse start arguments
parser = argparse.ArgumentParser(
description="Moonraker - Klipper API Server")
parser.add_argument(
"-a", "--address", default='0.0.0.0', metavar='<address>',
help="host name or ip to bind to the Web Server")
parser.add_argument(
"-p", "--port", type=int, default=7125, metavar='<port>',
help="port the Web Server will listen on")
parser.add_argument(
"-s", "--socketfile", default="/tmp/moonraker", metavar='<socketfile>',
help="file name and location for the Unix Domain Socket")
parser.add_argument(
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
help="log file name and location")
parser.add_argument(
"-k", "--apikey", default="~/.moonraker_api_key",
metavar='<apikeyfile>', help="API Key file location")
parser.add_argument(
"-d", "--debug", action='store_true',
help="Enable Debug Logging")
cmd_line_args = parser.parse_args()
# Setup Logging
log_file = os.path.normpath(os.path.expanduser(cmd_line_args.logfile))
cmd_line_args.logfile = log_file
root_logger = logging.getLogger()
file_hdlr = MoonrakerLoggingHandler(
log_file, when='midnight', backupCount=2)
root_logger.addHandler(file_hdlr)
if cmd_line_args.debug:
root_logger.setLevel(logging.DEBUG)
else:
root_logger.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
if sys.version_info < (3, 7):
msg = "Moonraker requires Python 3.7 or above. Detected Version: %s" \
% (sys.version)
logging.info(msg)
print(msg)
exit(1)
# Start IOLoop and Server
io_loop = IOLoop.current()
try:
server = Server(cmd_line_args)
except Exception:
logging.exception("Moonraker Error")
return
try:
server.start()
io_loop.start()
except Exception:
logging.exception("Server Running Error")
io_loop.close(True)
logging.info("Server Shutdown")
if __name__ == '__main__':
main()
if __name__ == "__main__":
import sys
import importlib
import pathlib
pkg_parent = pathlib.Path(__file__).parent.parent
sys.path.pop(0)
sys.path.insert(0, str(pkg_parent))
svr = importlib.import_module(".server", "moonraker")
svr.main(False) # type: ignore
-490
View File
@@ -1,490 +0,0 @@
# Enhanced gcode file management and analysis
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import sys
import shutil
import time
import logging
import json
from tornado.ioloop import IOLoop
from tornado.locks import Lock
VALID_GCODE_EXTS = ['gcode', 'g', 'gco']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py")
class FileManager:
def __init__(self, server):
self.server = server
self.file_paths = {}
self.file_lists = {}
self.gcode_metadata = {}
self.metadata_lock = Lock()
self.server.register_endpoint(
"/server/files/list", "file_list", ['GET'],
self._handle_filelist_request)
self.server.register_endpoint(
"/server/files/metadata", "file_metadata", ['GET'],
self._handle_metadata_request)
self.server.register_endpoint(
"/server/files/directory", "directory", ['GET', 'POST', 'DELETE'],
self._handle_directory_request)
self.server.register_endpoint(
"/server/files/move", "file_move", ['POST'],
self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/copy", "file_copy", ['POST'],
self._handle_file_move_copy)
# Register APIs to handle file uploads
self.server.register_upload_handler("/server/files/upload")
self.server.register_upload_handler("/api/files/local")
def load_config(self, config):
# Gcode Files
sd = config.get('sd_path', None)
if sd is not None:
sd = os.path.normpath(os.path.expanduser(sd))
if sd != self.file_paths.get('gcodes', ""):
self.file_paths['gcodes'] = sd
self.server.register_static_file_handler(
'/server/files/gcodes/', sd, can_delete=True,
op_check_cb=self._handle_operation_check)
try:
self._update_file_list()
except Exception:
logging.exception("Unable to initialize gcode file list")
# Configuration files in the optional config path
cfg_path = config.get('printer_config_path', None)
if cfg_path is not None:
cfg_path = os.path.normpath(os.path.expanduser(cfg_path))
if cfg_path != self.file_paths.get('config', ""):
self.file_paths['config'] = cfg_path
self.server.register_static_file_handler(
"/server/files/config/", cfg_path,
can_delete=True)
try:
self._update_file_list(base='config')
except Exception:
logging.exception("Unable to initialize config file list")
# Register path for example configs
klipper_path = config.get('klipper_path', None)
if klipper_path is not None:
example_cfg_path = os.path.join(klipper_path, "config")
if example_cfg_path != self.file_paths.get("config_examples", ""):
self.file_paths['config_examples'] = example_cfg_path
self.server.register_static_file_handler(
"/server/files/config_examples/", example_cfg_path)
try:
self._update_file_list(base='config_examples')
except Exception:
logging.exception(
"Unable to initialize config_examples file list")
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
async def _handle_filelist_request(self, path, method, args):
root = args.get('root', "gcodes")
return self.get_file_list(format_list=True, base=root)
async def _handle_metadata_request(self, path, method, args):
requested_file = args.get('filename')
metadata = self.gcode_metadata.get(requested_file)
if metadata is None:
raise self.server.error(
"Metadata not available for <%s>" % (requested_file), 404)
metadata['filename'] = requested_file
return metadata
async def _handle_directory_request(self, path, method, args):
directory = args.get('path', "gcodes")
base, url_path, dir_path = self._convert_path(directory)
method = method.upper()
if method == 'GET':
# Get list of files and subdirectories for this target
return self._list_directory(dir_path)
elif method == 'POST' and base in FULL_ACCESS_ROOTS:
# Create a new directory
try:
os.mkdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed(url_path, "add_directory", base)
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == base:
raise self.server.error(
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
"Directory does not exist (%s)" % (directory))
force = args.get('force', False)
if isinstance(force, str):
force = force.lower() == "true"
if force:
# Make sure that the directory does not contain a file
# loaded by the virtual_sdcard
await self._handle_operation_check(dir_path)
shutil.rmtree(dir_path)
else:
try:
os.rmdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed(url_path, "delete_directory", base)
else:
raise self.server.error("Operation Not Supported", 405)
return "ok"
async def _handle_operation_check(self, requested_path):
# Get virtual_sdcard status
request = self.server.make_request(
"objects/status", 'GET', {'virtual_sdcard': []})
result = await request.wait()
if isinstance(result, self.server.error):
raise result
vsd = result.get('virtual_sdcard', {})
loaded_file = vsd.get('filename', "")
gc_path = self.file_paths.get('gcodes', "")
full_path = os.path.join(gc_path, loaded_file)
if os.path.isdir(requested_path):
# Check to see of the loaded file is in the reques
if full_path.startswith(requested_path):
raise self.server.error("File currently in use", 403)
elif full_path == requested_path:
raise self.server.error("File currently in use", 403)
ongoing = vsd.get('total_duration', 0.) > 0.
return ongoing
def _convert_path(self, url_path):
parts = url_path.strip("/").split("/")
if not parts:
raise self.server.error("Invalid path: " % (url_path))
base = parts[0]
if base not in self.file_paths:
raise self.server.error("Invalid base path (%s)" % (base))
root_path = local_path = self.file_paths[base]
url_path = ""
if len(parts) > 1:
url_path = "/".join(parts[1:])
local_path = os.path.join(root_path, url_path)
return base, url_path, local_path
async def _handle_file_move_copy(self, path, method, args):
source = args.get("source")
destination = args.get("dest")
if source is None:
raise self.server.error("File move/copy request issing source")
if destination is None:
raise self.server.error(
"File move/copy request missing destination")
source_base, src_url_path, source_path = self._convert_path(source)
dest_base, dst_url_path, dest_path = self._convert_path(destination)
if dest_base not in FULL_ACCESS_ROOTS:
raise self.server.error(
"Destination path is read-only: %s" % (dest_base))
if not os.path.exists(source_path):
raise self.server.error("File %s does not exist" % (source_path))
# make sure the destination is not in use
if os.path.exists(dest_path):
await self._handle_operation_check(dest_path)
action = ""
if path == "/server/files/move":
if source_base not in FULL_ACCESS_ROOTS:
raise self.server.error(
"Source path is read-only, cannot move: %s"
% (source_base))
# if moving the file, make sure the source is not in use
await self._handle_operation_check(source_path)
try:
shutil.move(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "file_move"
elif path == "/server/files/copy":
try:
if os.path.isdir(source_path):
shutil.copytree(source_path, dest_path)
else:
shutil.copy2(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "file_copy"
self.notify_filelist_changed(
dst_url_path, action, dest_base,
{'prev_file': src_url_path, 'prev_root': source_base})
return "ok"
def _list_directory(self, path):
if not os.path.isdir(path):
raise self.server.error(
"Directory does not exist (%s)" % (path))
flist = {'dirs': [], 'files': []}
for fname in os.listdir(path):
full_path = os.path.join(path, fname)
modified = time.ctime(os.path.getmtime(full_path))
if os.path.isdir(full_path):
flist['dirs'].append({
'dirname': fname,
'modified': modified
})
elif os.path.isfile(full_path):
size = os.path.getsize(full_path)
flist['files'].append(
{'filename': fname,
'modified': modified,
'size': size})
return flist
def _shell_proc_callback(self, result):
try:
proc_resp = json.loads(result.strip())
except Exception:
logging.exception("file_manager: unable to load metadata")
logging.debug(result)
return
proc_log = proc_resp.get('log', [])
for log_msg in proc_log:
logging.info(log_msg)
file_path = proc_resp.pop('file', None)
if file_path is not None:
self.gcode_metadata[file_path] = proc_resp.get('metadata')
async def _update_metadata(self):
async with self.metadata_lock:
exisiting_data = {}
update_list = []
gc_files = dict(self.file_lists.get('gcodes', {}))
gc_path = self.file_paths.get('gcodes', "")
for fname, fdata in gc_files.items():
mdata = self.gcode_metadata.get(fname, {})
if mdata.get('size', "") == fdata.get('size') \
and mdata.get('modified', "") == fdata.get('modified'):
# file metadata has already been extracted
exisiting_data[fname] = mdata
else:
update_list.append(fname)
self.gcode_metadata = exisiting_data
for fname in update_list:
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
gc_path, "-f", "'" + fname + "'"])
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(
cmd, self._shell_proc_callback)
try:
await scmd.run(timeout=4.)
except Exception:
logging.exception("Error running extract_metadata.py")
def _update_file_list(self, base='gcodes'):
# Use os.walk find files in sd path and subdirs
path = self.file_paths.get(base, None)
if path is None:
msg = "No known path for root: %s" % (base)
logging.info(msg)
raise self.server.error(msg)
elif not os.path.isdir(path):
msg = "Cannot generate file list for root: %s" % (base)
logging.info(msg)
raise self.server.error(msg)
logging.info("Updating File List <%s>..." % (base))
new_list = {}
for root, dirs, files in os.walk(path, followlinks=True):
for name in files:
ext = name[name.rfind('.')+1:]
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(root, name)
r_path = full_path[len(path) + 1:]
size = os.path.getsize(full_path)
modified = time.ctime(os.path.getmtime(full_path))
new_list[r_path] = {'size': size, 'modified': modified}
self.file_lists[base] = new_list
if base == 'gcodes':
ioloop = IOLoop.current()
ioloop.spawn_callback(self._update_metadata)
return dict(new_list)
async def process_file_upload(self, request):
# lookup root file path
root = self._get_argument(request, 'root', "gcodes")
if root == "gcodes":
result = await self._do_gcode_upload(request)
elif root in FULL_ACCESS_ROOTS:
result = self._do_standard_upload(request, root)
else:
raise self.server.error("Invalid root request: %s" % (root))
return result
async def _do_gcode_upload(self, request):
start_print = print_ongoing = False
base_path = self.file_paths.get("gcodes", "")
if not base_path:
raise self.server.error("Gcodes root not available")
start_print = self._get_argument(request, 'print', "false") == "true"
upload = self._get_upload_info(request, base_path)
# Verify that the operation can be done if attempting to upload a gcode
try:
print_ongoing = await self._handle_operation_check(
upload['full_path'])
except self.server.error as e:
if e.status_code == 403:
raise self.server.error(
"File is loaded, upload not permitted", 403)
else:
# Couldn't reach Klippy, so it should be safe
# to permit the upload but not start
start_print = False
# Don't start if another print is currently in progress
start_print = start_print and not print_ongoing
self._write_file(upload)
if start_print:
# Make a Klippy Request to "Start Print"
gcode_apis = self.server.lookup_plugin('gcode_apis')
try:
await gcode_apis.gcode_start_print(
request.path, 'POST', {'filename': upload['filename']})
except self.server.error:
# Attempt to start print failed
start_print = False
self.notify_filelist_changed(upload['filename'], 'added', "gcodes")
return {'result': upload['filename'], 'print_started': start_print}
def _do_standard_upload(self, request, root):
path = self.file_paths.get(root, None)
if path is None:
raise self.server.error("Unknown root path: %s" % (root))
upload = self._get_upload_info(request, path)
self._write_file(upload)
self.notify_filelist_changed(upload['filename'], 'added', root)
return {'result': upload['filename']}
def _get_argument(self, request, name, default=None):
args = request.arguments.get(name, None)
if args is not None:
return args[0].decode().strip()
return default
def _get_upload_info(self, request, base_path):
# check relative path
dir_path = self._get_argument(request, 'path', "")
# fetch the upload from the request
if len(request.files) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
f_list = list(request.files.values())[0]
if len(f_list) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
upload = f_list[0]
if os.path.isfile(base_path):
filename = os.path.basename(base_path)
full_path = base_path
dir_path = ""
else:
filename = "_".join(upload['filename'].strip().split()).lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(base_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(base_path):
raise self.server.error(
"Cannot write to path: %s" % (full_path))
return {
'filename': filename,
'body': upload['body'],
'dir_path': dir_path,
'full_path': full_path}
def _write_file(self, upload):
try:
if upload['dir_path']:
os.makedirs(os.path.dirname(upload['full_path']), exist_ok=True)
with open(upload['full_path'], 'wb') as fh:
fh.write(upload['body'])
except Exception:
raise self.server.error("Unable to save file", 500)
def get_file_list(self, format_list=False, base='gcodes'):
try:
filelist = self._update_file_list(base)
except Exception:
msg = "Unable to update file list"
logging.exception(msg)
raise self.server.error(msg)
if format_list:
flist = []
for fname in sorted(filelist, key=str.lower):
fdict = {'filename': fname}
fdict.update(filelist[fname])
flist.append(fdict)
return flist
return filelist
def get_file_metadata(self, filename):
if filename[0] == '/':
filename = filename[1:]
# Remove "gcodes" of its added. It is valid for a request to
# include to the root or assume the root is gcodes
if filename.startswith('gcodes/'):
filename = filename[7:]
flist = self.get_file_list()
return self.gcode_metadata.get(filename, flist.get(filename, {}))
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root. Currently the only
# Supported root is "gcodes"
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
root = parts[0]
if root not in self.file_paths:
raise self.server.error(
"Invalid Directory Request: %s" % (directory))
path = self.file_paths[root]
if len(parts) == 1:
dir_path = path
else:
dir_path = os.path.join(path, parts[1])
if not os.path.isdir(dir_path):
raise self.server.error(
"Directory does not exist (%s)" % (dir_path))
flist = self._list_directory(dir_path)
if simple_format:
simple_list = []
for dirobj in flist['dirs']:
simple_list.append("*" + dirobj['dirname'])
for fileobj in flist['files']:
fname = fileobj['filename']
ext = fname[fname.rfind('.')+1:]
if root == "gcodes" and ext in VALID_GCODE_EXTS:
simple_list.append(fname)
return simple_list
return flist
def delete_file(self, path):
parts = path.split("/", 1)
root = parts[0]
if root not in self.file_paths or len(parts) != 2:
raise self.server.error("Invalid file path: %s" % (path))
root_path = self.file_paths[root]
full_path = os.path.join(root_path, parts[1])
if not os.path.isfile(full_path):
raise self.server.error("Invalid file path: %s" % (path))
os.remove(full_path)
def notify_filelist_changed(self, fname, action, base, params={}):
self._update_file_list(base)
result = {'filename': fname, 'action': action, 'root': base}
if params:
result.update(params)
self.server.send_event("file_manager:filelist_changed", result)
def load_plugin(server):
return FileManager(server)
-67
View File
@@ -1,67 +0,0 @@
# Map HTTP/Websocket APIs for specific gcode tasks
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
GCODE_ENDPOINT = "gcode/script"
class GCodeAPIs:
def __init__(self, server):
self.server = server
# Register GCode Endpoints
self.server.register_endpoint(
"/printer/print/pause", "printer_print_pause", ['POST'],
self.gcode_pause)
self.server.register_endpoint(
"/printer/print/resume", "printer_print_resume", ['POST'],
self.gcode_resume)
self.server.register_endpoint(
"/printer/print/cancel", "printer_print_cancel", ['POST'],
self.gcode_cancel)
self.server.register_endpoint(
"/printer/print/start", "printer_print_start", ['POST'],
self.gcode_start_print)
self.server.register_endpoint(
"/printer/restart", "printer_restart", ['POST'],
self.gcode_restart)
self.server.register_endpoint(
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
self.gcode_firmware_restart)
async def _send_gcode(self, script):
args = {'script': script}
request = self.server.make_request(
GCODE_ENDPOINT, 'POST', args)
result = await request.wait()
if isinstance(result, self.server.error):
raise result
return result
async def gcode_pause(self, path, method, args):
return await self._send_gcode("PAUSE")
async def gcode_resume(self, path, method, args):
return await self._send_gcode("RESUME")
async def gcode_cancel(self, path, method, args):
return await self._send_gcode("CANCEL_PRINT")
async def gcode_start_print(self, path, method, args):
filename = args.get('filename')
# XXX - validate that file is on disk
if filename[0] != '/':
filename = '/' + filename
script = "M23 " + filename + "\nM24"
return await self._send_gcode(script)
async def gcode_restart(self, path, method, args):
return await self._send_gcode("RESTART")
async def gcode_firmware_restart(self, path, method, args):
return await self._send_gcode("FIRMWARE_RESTART")
def load_plugin(server):
return GCodeAPIs(server)
-34
View File
@@ -1,34 +0,0 @@
# Machine manipulation request handlers
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class Machine:
def __init__(self, server):
self.server = server
self.server.register_endpoint(
"/machine/reboot", "machine_reboot", ['POST'],
self._handle_machine_request)
self.server.register_endpoint(
"/machine/shutdown", "machine_shutdown", ['POST'],
self._handle_machine_request)
async def _handle_machine_request(self, path, method, args):
if path == "/machine/shutdown":
cmd = "sudo shutdown now"
elif path == "/machine/reboot":
cmd = "sudo reboot now"
else:
raise self.server.error("Unsupported machine request")
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception("Error running cmd '%s'" % (cmd))
return "ok"
def load_plugin(server):
return Machine(server)
-685
View File
@@ -1,685 +0,0 @@
# PanelDue LCD display support
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import serial
import os
import time
import json
import errno
import logging
import tempfile
from utils import ServerError
from tornado import gen, netutil
from tornado.ioloop import IOLoop
from tornado.locks import Lock
MIN_EST_TIME = 10.
class PanelDueError(ServerError):
pass
class SerialConnection:
def __init__(self, paneldue):
self.ioloop = IOLoop.current()
self.paneldue = paneldue
self.port = ""
self.baud = 57200
self.sendlock = Lock()
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
def load_config(self, config):
port = config.get('serial', None)
baud = int(config.get('baud', 57200))
if port is None:
logging.info("No serial port specified, cannot connect")
return
if port != self.port or baud != self.baud or \
not self.connected:
self.disconnect()
self.port = port
self.baud = baud
self.ioloop.spawn_callback(self._connect)
def disconnect(self):
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
self.fd = None
self.connected = False
self.ser.close()
self.ser = None
logging.info("PanelDue Disconnected")
async def _connect(self):
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info("Attempting to connect to: %s" % (self.port))
try:
# XXX - sometimes the port cannot be exclusively locked, this
# would likely be due to a restart where the serial port was
# not correctly closed. Maybe don't use exclusive mode?
self.ser = serial.Serial(
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception("Unable to open port: %s" % (self.port))
await gen.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
os.set_blocking(self.fd, False)
self.ioloop.add_handler(
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect()
return
# Process incoming data using same method as gcode.py
try:
data = os.read(fd, 4096)
except os.error:
return
if not data:
# possibly an error, disconnect
self.disconnect()
logging.info("serial_display: No data received, disconnecting")
return
self.ioloop.spawn_callback(self._process_data, data)
async def _process_data(self, data):
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
line = line.strip().decode()
try:
await self.paneldue.process_line(line)
except ServerError:
logging.exception(
"GCode Processing Error: " + line)
self.paneldue.handle_gcode_response(
"!! GCode Processing Error: " + line)
except Exception:
logging.exception("Error during gcode processing")
async def send(self, data):
if self.connected:
async with self.sendlock:
while data:
try:
sent = os.write(self.fd, data)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
data = data[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect()
return
class PanelDue:
def __init__(self, server):
self.server = server
self.ioloop = IOLoop.current()
self.ser_conn = SerialConnection(self)
self.file_manager = self.server.load_plugin('file_manager')
self.kinematics = "none"
self.machine_name = "Klipper"
self.firmware_name = "Repetier | Klipper"
self.last_message = None
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
# Initialize tracked state.
self.printer_state = {
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
self.available_macros = {}
self.non_trivial_keys = []
self.extruder_count = 0
self.heaters = []
self.is_ready = False
self.is_shutdown = False
# Register server events
self.server.register_event_handler(
"server:klippy_state_changed", self.handle_klippy_state)
self.server.register_event_handler(
"server:status_update", self.handle_status_update)
self.server.register_event_handler(
"server:gcode_response", self.handle_gcode_response)
self.server.register_remote_method(
"paneldue_beep", self.handle_paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
'M408': self._run_paneldue_M408
}
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
'M25': lambda args: "PAUSE",
'M32': self._prepare_M32,
'M98': self._prepare_M98,
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
'M290': self._prepare_M290,
'M999': lambda args: "FIRMWARE_RESTART"
}
def load_config(self, config):
self.ser_conn.load_config(config)
self.machine_name = config.get('machine_name', self.machine_name)
macros = config.get('macros', None)
if macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
macros = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macros}
else:
self.available_macros = {}
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.ioloop.spawn_callback(self.write_response, {'status': 'C'})
logging.info("PanelDue Configured")
async def _klippy_request(self, command, method='GET', args={}):
request = self.server.make_request(command, method, args)
result = await request.wait()
if isinstance(result, self.server.error):
raise PanelDueError(str(result))
return result
async def handle_klippy_state(self, state):
if state == "ready":
await self._process_klippy_ready()
elif state == "shutdown":
await self._process_klippy_shutdown()
elif state == "disconnect":
await self._process_klippy_disconnect()
async def _process_klippy_ready(self):
# Request "info" and "configfile" status
retries = 10
while retries:
try:
printer_info = await self._klippy_request("info")
cfg_status = await self._klippy_request(
"objects/status", args={'configfile': []})
except PanelDueError:
logging.exception("PanelDue initialization request failed")
retries -= 1
if not retries:
raise
await gen.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + printer_info['version']
config = cfg_status.get('configfile', {}).get('config', {})
printer_cfg = config.get('printer', {})
self.kinematics = printer_cfg.get('kinematics', "none")
logging.info(
"PanelDue Config Received:\n"
"Firmware Name: %s\n"
"Kinematics: %s\n"
"Printer Config: %s\n"
% (self.firmware_name, self.kinematics, str(config)))
# Initalize printer state and make subscription request
self.printer_state = {
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
'pause_resume': {}, 'fan': {}, 'display_status': {}}
sub_args = {'gcode': [], 'toolhead': []}
self.extruder_count = 0
self.heaters = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = []
elif cfg in self.printer_state:
sub_args[cfg] = []
try:
await self._klippy_request(
"objects/subscription", method='POST', args=sub_args)
except PanelDueError:
logging.exception("Unable to complete subscription request")
self.is_shutdown = False
self.is_ready = True
async def _process_klippy_shutdown(self):
self.is_shutdown = True
async def _process_klippy_disconnect(self):
# Tell the PD that we are shutting down
await self.write_response({'status': 'S'})
self.is_ready = False
async def handle_status_update(self, status):
self.printer_state.update(status)
def handle_paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self._klippy_request("emergency_stop", method='POST')
return
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
await self._run_gcode(line[line_index+1:cs_index])
async def _run_gcode(self, script):
# Execute the gcode. Check for special RRF gcodes that
# require special handling
parts = script.split()
cmd = parts[0].strip()
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params = {}
for p in parts[1:]:
arg = p[0].lower() if p[0].lower() in "psr" else "p"
try:
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
except Exception:
msg = "paneldue: Error parsing direct gcode %s" % (script)
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params["arg_" + arg] = val
func = self.direct_gcodes[cmd]
await func(**params)
return
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
func = self.special_gcodes[cmd]
script = func(parts[1:])
try:
args = {'script': script}
await self._klippy_request(
"gcode/script", method='POST', args=args)
except PanelDueError:
msg = "Error executing script %s" % script
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
def _clean_filename(self, filename):
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
# Remove initial "gcodes" folder. This is necessary
# due to the HACK in the paneldue_M20 gcode.
if filename.startswith("gcodes/"):
filename = filename[6:]
elif filename.startswith("/gcodes/"):
filename = filename[7:]
# Start with a "/" so the gcode parser can correctly
# handle files that begin with digits or special chars
if filename[0] != "/":
filename = "/" + filename
return filename
def _prepare_M23(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename
def _prepare_M32(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename + "\n" + "M24"
def _prepare_M98(self, args):
macro = args[0][1:].strip()
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
if cmd is None:
raise PanelDueError("Macro %s invalid" % (macro))
return cmd
def _prepare_M290(self, args):
# args should in in the format Z0.02
offset = args[0][1:].strip()
return "SET_GCODE_OFFSET Z_ADJUST=%s MOVE=1" % (offset)
def handle_gcode_response(self, response):
# Only queue up "non-trivial" gcode responses. At the
# moment we'll handle state changes and errors
if "Klipper state" in response \
or response.startswith('!!'):
self.last_gcode_response = response
else:
for key in self.non_trivial_keys:
if key in response:
self.last_gcode_response = response
return
async def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
await self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
# PanelDue States applicable to Klipper:
# I = idle, P = printing from SD, S = stopped (shutdown),
# C = starting up (not ready), A = paused, D = pausing,
# B = busy
if self.is_shutdown:
return 'S'
printer_state = self.printer_state
is_active = printer_state['virtual_sdcard'].get('is_active', False)
paused = printer_state['pause_resume'].get('is_paused', False)
if paused:
if is_active:
return 'D'
else:
return 'A'
if is_active:
return 'P'
if printer_state['gcode'].get('busy', False):
return 'B'
return 'I'
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
sequence = arg_r
response_type = arg_s
if not self.is_ready:
# Klipper is still starting up, do not query status
response['status'] = 'S' if self.is_shutdown else 'C'
await self.write_response(response)
return
# Send gcode responses
if sequence is not None and self.last_gcode_response:
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
response['firmwareName'] = self.firmware_name
response['numTools'] = self.extruder_count
response['geometry'] = self.kinematics
response['axes'] = 3
p_state = self.printer_state
status = self._get_printer_status()
response['status'] = status
response['babystep'] = round(p_state['gcode'].get(
'homing_zpos', 0.), 3)
# Current position
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
response['homed'] = [int(a in homed_pos) for a in "xyz"]
sfactor = round(p_state['gcode'].get('speed_factor', 1.) * 100, 2)
response['sfactor'] = sfactor
# Print Progress Tracking
sd_status = p_state['virtual_sdcard']
fname = sd_status.get('filename', "")
if fname:
# We know a file has been loaded, initialize metadata
if self.current_file != fname:
self.current_file = fname
self.file_metadata = self.file_manager.get_file_metadata(fname)
progress = p_state['virtual_sdcard'].get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time = self.file_metadata.get('estimated_time', 0)
if est_time > MIN_EST_TIME:
# file read estimate
times_left = [int(est_time - est_time * progress)]
# filament estimate
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament = sd_status.get('filament_used', 0.)
fpct = min(1., cur_filament / est_total_fil)
times_left.append(int(est_time - est_time * fpct))
# object height estimate
obj_height = self.file_metadata.get('object_height')
if obj_height:
cur_height = p_state['gcode'].get('move_zpos', 0.)
hpct = min(1., cur_height / obj_height)
times_left.append(int(est_time - est_time * hpct))
else:
# The estimated time is not in the metadata, however we
# can still provide an estimate based on file progress
duration = sd_status.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
# clear filename and metadata
self.current_file = ""
self.file_metadata = {}
fan_speed = p_state['fan'].get('speed')
if fan_speed is not None:
response['fanPercent'] = [round(fan_speed * 100, 1)]
if self.extruder_count > 0:
extruder_name = p_state['toolhead'].get('extruder')
if extruder_name is not None:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor = round(p_state['gcode'].get('extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp = round(p_state[name].get('temperature', 0.0), 1)
target = round(p_state[name].get('target', 0.0), 1)
response.setdefault('heaters', []).append(temp)
response.setdefault('active', []).append(target)
response.setdefault('standby', []).append(target)
response.setdefault('hstat', []).append(2 if target else 0)
if name.startswith('extruder'):
response.setdefault('efactor', []).append(efactor)
response.setdefault('extr', []).append(round(pos[3], 2))
# Display message (via M117)
msg = p_state['display_status'].get('message')
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
await self.write_response(response)
async def _run_paneldue_M20(self, arg_p, arg_s=0):
response_type = arg_s
if response_type != 2:
logging.info(
"PanelDue: Cannot process response type %d in M20"
% (response_type))
return
path = arg_p
# Strip quotes if they exist
path = path.strip('\"')
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
# repetier compatibility enabled, the default folder is root,
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response = {'dir': path}
response['files'] = []
if path == "/macros":
response['files'] = list(self.available_macros.keys())
else:
# HACK: The PanelDue has a bug where it does not correctly detect
# subdirectories if we return the root as "/". Moonraker can
# support a "gcodes" directory, however we must choose between this
# support or disabling RRF specific gcodes (this is done by
# identifying as Repetier).
# The workaround below converts both "/" and "/gcodes" paths to
# "gcodes".
if path == "/":
response['dir'] = "/gcodes"
path = "gcodes"
elif path.startswith("/gcodes"):
path = path[1:]
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
await self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
# Delete a file. Clean up the file name and make sure
# it is relative to the "gcodes" root.
path = arg_p
path = path.strip('\"')
if path.startswith("0:/"):
path = path[3:]
elif path[0] == "/":
path = path[1:]
if not path.startswith("gcodes/"):
path = "gcodes/" + path
self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
if filename is None:
# PanelDue is requesting file information on a
# currently printed file
active = False
if sd_status:
filename = sd_status['filename']
active = sd_status['is_active']
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
await self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
# indicates Moonraker supports a "gcodes" directory.
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata = self.file_manager.get_file_metadata(filename)
if metadata:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + metadata['modified']
slicer = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time = metadata.get('estimated_time')
if est_time is not None:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
await self.write_response(response)
async def close(self):
self.ser_conn.disconnect()
def load_plugin(server):
return PanelDue(server)
-188
View File
@@ -1,188 +0,0 @@
# Raspberry Pi Power Control
#
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import os
from tornado.ioloop import IOLoop
from tornado import gen
class PrinterPower:
def __init__(self, server):
self.server = server
self.server.register_endpoint(
"/printer/power/devices", "power_devices", ['GET'],
self._handle_list_devices)
self.server.register_endpoint(
"/printer/power/status", "power_status", ['GET'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/on", "power_on", ['POST'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/off", "power_off", ['POST'],
self._handle_power_request)
self.current_dev = None
self.devices = {}
async def _handle_list_devices(self, path, method, args):
output = {"devices": []}
for dev in self.devices:
output['devices'].append({
"name": self.devices[dev]["name"],
"id": dev
})
return output
async def _handle_power_request(self, path, method, args):
if len(args) == 0:
if path == "/printer/power/status":
args = self.devices
else:
return "no_devices"
result = {}
for dev in args:
if dev not in self.devices:
result[dev] = "device_not_found"
continue
await GPIO.verify_pin(self.devices[dev]["pin"],
self.devices[dev]["active_low"])
if path == "/printer/power/on":
GPIO.set_pin_value(self.devices[dev]["pin"], 1)
elif path == "/printer/power/off":
GPIO.set_pin_value(self.devices[dev]["pin"], 0)
elif path != "/printer/power/status":
raise self.server.error("Unsupported power request")
self.devices[dev]["status"] = GPIO.is_pin_on(
self.devices[dev]["pin"])
result[dev] = self.devices[dev]["status"]
return result
def load_config(self, config):
if "devices" not in config:
return
devices = config["devices"].split(',')
logging.info("Power plugin loading devices: " + str(devices))
parsed_devices = {}
for dev in devices:
dev = dev.strip()
pin = config.get(dev + "_pin", "")
if not pin.isdigit():
logging.info(
"Power plugin: ERR %s does not have a pin defined" % (dev))
continue
name = config.get(dev + "_name", dev)
active_low = int(config.get(
dev + "_active_low", "false").lower() == "true")
parsed_devices[dev] = {
"name": name,
"pin": int(pin),
"active_low": active_low,
"status": None
}
ioloop = IOLoop.current()
ioloop.spawn_callback(self.initialize_devices, parsed_devices)
async def initialize_devices(self, devices):
for name, device in devices.items():
try:
logging.debug(
"Attempting to configure pin GPIO%d"
% (device["pin"]))
await GPIO.setup_pin(device["pin"], device["active_low"])
device["status"] = GPIO.is_pin_on(device["pin"])
except Exception:
logging.exception(
"Power plugin: ERR Problem configuring the output pin for"
" device %s. Removing device" % (name))
self.devices.pop(name, None)
continue
self.devices[name] = device
class GPIO:
gpio_root = "/sys/class/gpio"
@staticmethod
def _set_gpio_option(gpio, option, value):
GPIO._write(
os.path.join(GPIO.gpio_root, "gpio%d" % (gpio), option),
value
)
@staticmethod
def _get_gpio_option(pin, option):
return GPIO._read(
os.path.join(GPIO.gpio_root, "gpio%d" % (pin), option)
)
@staticmethod
def _write(file, data):
with open(file, 'w') as f:
f.write(str(data))
f.flush()
@staticmethod
def _read(file):
with open(file, 'r') as f:
f.seek(0)
return f.read().strip()
@staticmethod
async def verify_pin(pin, active_low=1):
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
if not os.path.exists(gpiopath):
logging.info("Re-intializing GPIO%d" % (pin))
await GPIO.setup_pin(pin, active_low)
return
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
@staticmethod
async def setup_pin(pin, active_low=1):
pin = int(pin)
active_low = 1 if active_low == 1 else 0
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
if not os.path.exists(gpiopath):
GPIO._write(
os.path.join(GPIO.gpio_root, "export"),
pin)
logging.info("Waiting for GPIO%d to initialize" % (pin))
while os.stat(os.path.join(
GPIO.gpio_root, "gpio%d" % (pin),
"active_low")).st_gid == 0:
await gen.sleep(.1)
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
@staticmethod
def is_pin_on(pin):
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
@staticmethod
def set_pin_value(pin, active):
value = 1 if (active == 1) else 0
GPIO._set_gpio_option(pin, "value", value)
def load_plugin(server):
return PrinterPower(server)
-88
View File
@@ -1,88 +0,0 @@
# linux shell command execution utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import shlex
import subprocess
import logging
import tornado
from tornado import gen
from tornado.ioloop import IOLoop
class ShellCommand:
def __init__(self, cmd, callback=None):
self.io_loop = IOLoop.current()
self.name = cmd
self.output_cb = callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.partial_output = b""
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
return
try:
data = os.read(fd, 4096)
except Exception:
return
data = self.partial_output + data
if b'\n' not in data:
self.partial_output = data
return
elif data[-1] != b'\n':
split = data.rfind(b'\n') + 1
self.partial_output = data[split:]
data = data[:split]
try:
self.output_cb(data)
except Exception:
logging.exception("Error writing command output")
async def run(self, timeout=2., verbose=True):
if not timeout or self.output_cb is None:
# Fire and forget commands cannot be verbose as we can't
# clean up after the process terminates
verbose = False
try:
proc = subprocess.Popen(
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except Exception:
logging.exception(
"shell_command: Command {%s} failed" % (self.name))
return
if verbose:
fd = proc.stdout.fileno()
self.io_loop.add_handler(
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
elif not timeout:
# fire and forget, return from execution
return
sleeptime = 0
complete = False
while sleeptime < timeout:
await gen.sleep(.05)
sleeptime += .05
if proc.poll() is not None:
complete = True
break
if not complete:
proc.terminate()
if verbose:
if self.partial_output:
self.output_cb(self.partial_output)
self.partial_output = b""
if complete:
msg = "Command {%s} finished" % (self.name)
else:
msg = "Command {%s} timed out" % (self.name)
logging.info(msg)
self.io_loop.remove_handler(fd)
class ShellCommandFactory:
def build_shell_command(self, cmd, callback):
return ShellCommand(cmd, callback)
def load_plugin(server):
return ShellCommandFactory()
-102
View File
@@ -1,102 +0,0 @@
# Heater sensor temperature storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
TEMPERATURE_STORE_SIZE = 20 * 60
class TemperatureStore:
def __init__(self, server):
self.server = server
# Temperature Store Tracking
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
# Register status update event
self.server.register_event_handler(
"server:status_update", self._set_current_temps)
self.server.register_event_handler(
"server:klippy_state_changed", self._init_sensors)
# Register endpoint
self.server.register_endpoint(
"/server/temperature_store", "server_temperature_store", ['GET'],
self._handle_temp_store_request)
async def _init_sensors(self, state):
if state != "ready":
return
# Fetch sensors
request = self.server.make_request(
"objects/status", 'GET', {'heaters': []})
result = await request.wait()
if isinstance(result, self.server.error):
logging.info("Error Configuring Sensors: %s" % (str(result)))
return
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub = {s: [] for s in sensors}
request = self.server.make_request(
"objects/subscription", 'POST', sub)
result = await request.wait()
if isinstance(result, self.server.error):
logging.info("Error subscribing to sensors: %s" %(str(result)))
return
logging.info("Configuring available sensors: %s" % (str(sensors)))
new_store = {}
for sensor in sensors:
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
if sensor not in self.temperature_store:
del self.last_temps[sensor]
self.temp_update_cb.start()
else:
logging.info("No sensors found")
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb.stop()
def _set_current_temps(self, data):
for sensor in self.temperature_store:
if sensor in data:
self.last_temps[sensor] = (
round(data[sensor].get('temperature', 0.), 2),
data[sensor].get('target', 0.))
def _update_temperature_store(self):
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, (temp, target) in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(temp)
self.temperature_store[sensor]['targets'].append(target)
async def _handle_temp_store_request(self, path, method, args):
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
return store
async def close(self):
self.temp_update_cb.stop()
def load_plugin(server):
return TemperatureStore(server)
+596
View File
@@ -0,0 +1,596 @@
#!/usr/bin/env python3
# Moonraker - HTTP/Websocket API Server for Klipper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import pathlib
import sys
import argparse
import importlib
import os
import io
import time
import socket
import logging
import signal
import asyncio
from . import confighelper
from .eventloop import EventLoop
from .app import MoonrakerApp
from .klippy_connection import KlippyConnection
from .utils import ServerError, Sentinel, get_software_version
from .loghelper import LogManager
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Dict,
List,
Tuple,
Union,
TypeVar,
)
if TYPE_CHECKING:
from .websockets import WebRequest, WebsocketManager
from .components.file_manager.file_manager import FileManager
from .components.machine import Machine
from .components.extensions import ExtensionManager
FlexCallback = Callable[..., Optional[Coroutine]]
_T = TypeVar("_T", Sentinel, Any)
API_VERSION = (1, 2, 1)
CORE_COMPONENTS = [
'dbus_manager', 'database', 'file_manager', 'klippy_apis',
'machine', 'data_store', 'shell_command', 'proc_stats',
'job_state', 'job_queue', 'http_client', 'announcements',
'webcam', 'extensions',
]
class Server:
error = ServerError
config_error = confighelper.ConfigError
def __init__(self,
args: Dict[str, Any],
log_manager: LogManager,
event_loop: EventLoop
) -> None:
self.event_loop = event_loop
self.log_manager = log_manager
self.app_args = args
self.events: Dict[str, List[FlexCallback]] = {}
self.components: Dict[str, Any] = {}
self.failed_components: List[str] = []
self.warnings: Dict[str, str] = {}
self._is_configured: bool = False
self.config = config = self._parse_config()
self.host: str = config.get('host', "0.0.0.0")
self.port: int = config.getint('port', 7125)
self.ssl_port: int = config.getint('ssl_port', 7130)
self.exit_reason: str = ""
self.server_running: bool = False
# Configure Debug Logging
config.getboolean('enable_debug_logging', False, deprecate=True)
self.debug = args["debug"]
log_level = logging.DEBUG if args["verbose"] else logging.INFO
logging.getLogger().setLevel(log_level)
self.event_loop.set_debug(args["asyncio_debug"])
self.klippy_connection = KlippyConnection(self)
# Tornado Application/Server
self.moonraker_app = app = MoonrakerApp(config)
self.register_endpoint = app.register_local_handler
self.register_debug_endpoint = app.register_debug_handler
self.register_static_file_handler = app.register_static_file_handler
self.register_upload_handler = app.register_upload_handler
self.register_api_transport = app.register_api_transport
self.log_manager.set_server(self)
for warning in args.get("startup_warnings", []):
self.add_warning(warning)
self.register_endpoint(
"/server/info", ['GET'], self._handle_info_request)
self.register_endpoint(
"/server/config", ['GET'], self._handle_config_request)
self.register_endpoint(
"/server/restart", ['POST'], self._handle_server_restart)
self.register_notification("server:klippy_ready")
self.register_notification("server:klippy_shutdown")
self.register_notification("server:klippy_disconnect",
"klippy_disconnected")
self.register_notification("server:gcode_response")
def get_app_args(self) -> Dict[str, Any]:
return dict(self.app_args)
def get_event_loop(self) -> EventLoop:
return self.event_loop
def get_api_version(self) -> Tuple[int, int, int]:
return API_VERSION
def get_warnings(self) -> List[str]:
return list(self.warnings.values())
def is_running(self) -> bool:
return self.server_running
def is_configured(self) -> bool:
return self._is_configured
def is_debug_enabled(self) -> bool:
return self.debug
def is_verbose_enabled(self) -> bool:
return self.app_args["verbose"]
def _parse_config(self) -> confighelper.ConfigHelper:
config = confighelper.get_configuration(self, self.app_args)
# log config file
cfg_files = "\n".join(config.get_config_files())
strio = io.StringIO()
config.write_config(strio)
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
cfg_item += strio.getvalue()
cfg_item += "#"*65
cfg_item += f"\nAll Configuration Files:\n{cfg_files}\n"
cfg_item += "#"*65
strio.close()
self.add_log_rollover_item('config', cfg_item)
return config
async def server_init(self, start_server: bool = True) -> None:
self.event_loop.add_signal_handler(
signal.SIGTERM, self._handle_term_signal)
# Perform asynchronous init after the event loop starts
optional_comps: List[Coroutine] = []
for name, component in self.components.items():
if not hasattr(component, "component_init"):
continue
if name in CORE_COMPONENTS:
# Process core components in order synchronously
await self._initialize_component(name, component)
else:
optional_comps.append(
self._initialize_component(name, component))
# Asynchronous Optional Component Initialization
if optional_comps:
await asyncio.gather(*optional_comps)
if not self.warnings:
await self.event_loop.run_in_thread(self.config.create_backup)
machine: Machine = self.lookup_component("machine")
if await machine.validate_installation():
return
if start_server:
await self.start_server()
async def start_server(self, connect_to_klippy: bool = True) -> None:
# Open Unix Socket Server
extm: ExtensionManager = self.lookup_component("extensions")
await extm.start_unix_server()
# Start HTTP Server
logging.info(
f"Starting Moonraker on ({self.host}, {self.port}), "
f"Hostname: {socket.gethostname()}")
self.moonraker_app.listen(self.host, self.port, self.ssl_port)
self.server_running = True
if connect_to_klippy:
self.klippy_connection.connect()
def add_log_rollover_item(self, name: str, item: str,
log: bool = True) -> None:
self.log_manager.set_rollover_info(name, item)
if log and item is not None:
logging.info(item)
def add_warning(
self, warning: str, warn_id: Optional[str] = None, log: bool = True
) -> str:
if warn_id is None:
warn_id = str(id(warning))
self.warnings[warn_id] = warning
if log:
logging.warning(warning)
return warn_id
def remove_warning(self, warn_id: str) -> None:
self.warnings.pop(warn_id, None)
# ***** Component Management *****
async def _initialize_component(self, name: str, component: Any) -> None:
logging.info(f"Performing Component Post Init: [{name}]")
try:
ret = component.component_init()
if ret is not None:
await ret
except Exception as e:
logging.exception(f"Component [{name}] failed post init")
self.add_warning(f"Component '{name}' failed to load with "
f"error: {e}")
self.set_failed_component(name)
def load_components(self) -> None:
config = self.config
cfg_sections = set([s.split()[0] for s in config.sections()])
cfg_sections.remove('server')
# load core components
for component in CORE_COMPONENTS:
self.load_component(config, component)
if component in cfg_sections:
cfg_sections.remove(component)
# load remaining optional components
for section in cfg_sections:
self.load_component(config, section, None)
self.klippy_connection.configure(config)
config.validate_config()
self._is_configured = True
def load_component(
self,
config: confighelper.ConfigHelper,
component_name: str,
default: _T = Sentinel.MISSING
) -> Union[_T, Any]:
if component_name in self.components:
return self.components[component_name]
if self.is_configured():
raise self.error(
"Cannot load components after configuration", 500
)
if component_name in self.failed_components:
raise self.error(
f"Component {component_name} previously failed to load", 500
)
try:
full_name = f"moonraker.components.{component_name}"
module = importlib.import_module(full_name)
is_core = component_name in CORE_COMPONENTS
fallback: Optional[str] = "server" if is_core else None
config = config.getsection(component_name, fallback)
load_func = getattr(module, "load_component")
component = load_func(config)
except Exception:
msg = f"Unable to load component: ({component_name})"
logging.exception(msg)
if component_name not in self.failed_components:
self.failed_components.append(component_name)
if default is Sentinel.MISSING:
raise
return default
self.components[component_name] = component
logging.info(f"Component ({component_name}) loaded")
return component
def lookup_component(
self, component_name: str, default: _T = Sentinel.MISSING
) -> Union[_T, Any]:
component = self.components.get(component_name, default)
if component is Sentinel.MISSING:
raise ServerError(f"Component ({component_name}) not found")
return component
def set_failed_component(self, component_name: str) -> None:
if component_name not in self.failed_components:
self.failed_components.append(component_name)
def register_component(self, component_name: str, component: Any) -> None:
if component_name in self.components:
raise self.error(
f"Component '{component_name}' already registered")
self.components[component_name] = component
def register_notification(self,
event_name: str,
notify_name: Optional[str] = None
) -> None:
wsm: WebsocketManager = self.lookup_component("websockets")
wsm.register_notification(event_name, notify_name)
def register_event_handler(self,
event: str,
callback: FlexCallback
) -> None:
self.events.setdefault(event, []).append(callback)
def send_event(self, event: str, *args) -> asyncio.Future:
fut = self.event_loop.create_future()
self.event_loop.register_callback(
self._process_event, fut, event, *args)
return fut
async def _process_event(self,
fut: asyncio.Future,
event: str,
*args
) -> None:
events = self.events.get(event, [])
coroutines: List[Coroutine] = []
try:
for func in events:
ret = func(*args)
if ret is not None:
coroutines.append(ret)
if coroutines:
await asyncio.gather(*coroutines)
except ServerError as e:
logging.exception(f"Error Processing Event: {fut}")
if not fut.done():
fut.set_result(None)
def register_remote_method(self,
method_name: str,
cb: FlexCallback
) -> None:
self.klippy_connection.register_remote_method(method_name, cb)
def get_host_info(self) -> Dict[str, Any]:
return {
'hostname': socket.gethostname(),
'address': self.host,
'port': self.port,
'ssl_port': self.ssl_port
}
def get_klippy_info(self) -> Dict[str, Any]:
return self.klippy_connection.klippy_info
def get_klippy_state(self) -> str:
return self.klippy_connection.state
def _handle_term_signal(self) -> None:
logging.info(f"Exiting with signal SIGTERM")
self.event_loop.register_callback(self._stop_server, "terminate")
async def _stop_server(self, exit_reason: str = "restart") -> None:
self.server_running = False
# Call each component's "on_exit" method
for name, component in self.components.items():
if hasattr(component, "on_exit"):
func: FlexCallback = getattr(component, "on_exit")
try:
ret = func()
if ret is not None:
await ret
except Exception:
logging.exception(
f"Error executing 'on_exit()' for component: {name}")
# Sleep for 100ms to allow connected websockets to write out
# remaining data
await asyncio.sleep(.1)
try:
await self.moonraker_app.close()
except Exception:
logging.exception("Error Closing App")
# Disconnect from Klippy
try:
await asyncio.wait_for(
asyncio.shield(self.klippy_connection.close(
wait_closed=True)), 2.)
except Exception:
logging.exception("Klippy Disconnect Error")
# Close all components
for name, component in self.components.items():
if name in ["application", "websockets", "klippy_connection"]:
# These components have already been closed
continue
if hasattr(component, "close"):
func = getattr(component, "close")
try:
ret = func()
if ret is not None:
await ret
except Exception:
logging.exception(
f"Error executing 'close()' for component: {name}")
# Allow cancelled tasks a chance to run in the eventloop
await asyncio.sleep(.001)
self.exit_reason = exit_reason
self.event_loop.remove_signal_handler(signal.SIGTERM)
self.event_loop.stop()
async def _handle_server_restart(self, web_request: WebRequest) -> str:
self.event_loop.register_callback(self._stop_server)
return "ok"
async def _handle_info_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
raw = web_request.get_boolean("raw", False)
file_manager: Optional[FileManager] = self.lookup_component(
'file_manager', None)
reg_dirs = []
if file_manager is not None:
reg_dirs = file_manager.get_registered_dirs()
wsm: WebsocketManager = self.lookup_component('websockets')
mreqs = self.klippy_connection.missing_requirements
if raw:
warnings = list(self.warnings.values())
else:
warnings = [
w.replace("\n", "<br/>") for w in self.warnings.values()
]
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_connection.state,
'components': list(self.components.keys()),
'failed_components': self.failed_components,
'registered_directories': reg_dirs,
'warnings': warnings,
'websocket_count': wsm.get_count(),
'moonraker_version': self.app_args['software_version'],
'missing_klippy_requirements': mreqs,
'api_version': API_VERSION,
'api_version_string': ".".join([str(v) for v in API_VERSION])
}
async def _handle_config_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
cfg_file_list: List[Dict[str, Any]] = []
cfg_parent = pathlib.Path(
self.app_args["config_file"]
).expanduser().resolve().parent
for fname, sections in self.config.get_file_sections().items():
path = pathlib.Path(fname)
try:
rel_path = str(path.relative_to(str(cfg_parent)))
except ValueError:
rel_path = fname
cfg_file_list.append({"filename": rel_path, "sections": sections})
return {
'config': self.config.get_parsed_config(),
'orig': self.config.get_orig_config(),
'files': cfg_file_list
}
def main(from_package: bool = True) -> None:
# Parse start arguments
parser = argparse.ArgumentParser(
description="Moonraker - Klipper API Server")
parser.add_argument(
"-d", "--datapath", default=None,
metavar='<data path>',
help="Location of Moonraker Data File Path"
)
parser.add_argument(
"-c", "--configfile", default=None, metavar='<configfile>',
help="Location of moonraker configuration file")
parser.add_argument(
"-l", "--logfile", default=None, metavar='<logfile>',
help="log file name and location")
parser.add_argument(
"-n", "--nologfile", action='store_true',
help="disable logging to a file")
parser.add_argument(
"-v", "--verbose", action="store_true",
help="Enable verbose logging"
)
parser.add_argument(
"-g", "--debug", action="store_true",
help="Enable Moonraker debug features"
)
parser.add_argument(
"-o", "--asyncio-debug", action="store_true",
help="Enable asyncio debug flag"
)
cmd_line_args = parser.parse_args()
startup_warnings: List[str] = []
dp: str = cmd_line_args.datapath or "~/printer_data"
data_path = pathlib.Path(dp).expanduser().resolve()
if not data_path.exists():
try:
data_path.mkdir()
except Exception:
startup_warnings.append(
f"Unable to create data path folder at {data_path}"
)
if cmd_line_args.configfile is not None:
cfg_file: str = cmd_line_args.configfile
else:
cfg_file = str(data_path.joinpath("config/moonraker.conf"))
app_args = {
"data_path": str(data_path),
"is_default_data_path": cmd_line_args.datapath is None,
"config_file": cfg_file,
"startup_warnings": startup_warnings,
"verbose": cmd_line_args.verbose,
"debug": cmd_line_args.debug,
"asyncio_debug": cmd_line_args.asyncio_debug,
"is_backup_config": False,
"is_python_package": from_package
}
# Setup Logging
version = get_software_version()
if cmd_line_args.nologfile:
app_args["log_file"] = ""
elif cmd_line_args.logfile:
app_args["log_file"] = os.path.normpath(
os.path.expanduser(cmd_line_args.logfile))
else:
app_args["log_file"] = str(data_path.joinpath("logs/moonraker.log"))
app_args["software_version"] = version
app_args["python_version"] = sys.version.replace("\n", " ")
log_manager = LogManager(app_args, startup_warnings)
# Start asyncio event loop and server
event_loop = EventLoop()
alt_config_loaded = False
estatus = 0
while True:
try:
server = Server(app_args, log_manager, event_loop)
server.load_components()
except confighelper.ConfigError as e:
backup_cfg = confighelper.find_config_backup(cfg_file)
logging.exception("Server Config Error")
if alt_config_loaded or backup_cfg is None:
estatus = 1
break
app_args["config_file"] = backup_cfg
app_args["is_backup_config"] = True
warn_list = list(startup_warnings)
app_args["startup_warnings"] = warn_list
warn_list.append(
f"Server configuration error: {e}\n"
f"Loaded server from most recent working configuration:"
f" '{app_args['config_file']}'\n"
f"Please fix the issue in moonraker.conf and restart "
f"the server."
)
alt_config_loaded = True
continue
except Exception:
logging.exception("Moonraker Error")
estatus = 1
break
try:
event_loop.register_callback(server.server_init)
event_loop.start()
except Exception:
logging.exception("Server Running Error")
estatus = 1
break
if server.exit_reason == "terminate":
break
# Restore the original config and clear the warning
# before the server restarts
if alt_config_loaded:
app_args["config_file"] = cfg_file
app_args["startup_warnings"] = startup_warnings
app_args["is_backup_config"] = False
alt_config_loaded = False
event_loop.close()
# Since we are running outside of the the server
# it is ok to use a blocking sleep here
time.sleep(.5)
logging.info("Attempting Server Restart...")
event_loop.reset()
event_loop.close()
logging.info("Server Shutdown")
log_manager.stop_logging()
exit(estatus)
+1
View File
@@ -0,0 +1 @@
# package definition for thirdparty package
+1
View File
@@ -0,0 +1 @@
# package definition for packagekit thirdparty files
+768
View File
@@ -0,0 +1,768 @@
# This file was autogenerated from pk-enum.h by pk-enum-converter.py
# on Fri Jan 21 16:01:47 2022 UTC
#
# License for original source:
#
# Copyright (C) 2007-2014 Richard Hughes <richard@hughsie.com>
#
# Licensed under the GNU Lesser General Public License Version 2.1
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
from __future__ import annotations
import sys
from enum import Flag, auto
class PkFlag(Flag):
@classmethod
def from_pkstring(cls, pkstring: str):
for name, member in cls.__members__.items():
if member.pkstring == pkstring:
return cls(member.value)
# Return "unknown" flag
return cls(1)
@classmethod
def from_index(cls, index: int):
return cls(1 << index)
@property
def pkstring(self) -> str:
if self.name is None:
return " | ".join([f.pkstring for f in self])
return self.name.lower().replace("_", "-")
@property
def desc(self) -> str:
if self.name is None:
return ", ".join([f.desc for f in self])
description = self.name.lower().replace("_", " ")
return description.capitalize()
@property
def index(self) -> int:
return self.value.bit_length() - 1
if sys.version_info < (3, 11):
def __iter__(self):
for i in range(self._value_.bit_length()):
val = 1 << i
if val & self._value_ == val:
yield self.__class__(val)
class Role(PkFlag):
"""
What we were asked to do, this never changes for the lifetime of the
transaction.
Icons that have to represent the whole "aim" of the transaction will use
these constants
* Role.UNKNOWN: Unknow request
* Role.CANCEL: Cancel transaction
* Role.DEPENDS_ON: Get package dependencies
* Role.GET_DETAILS: Get package details
* Role.GET_FILES:
* Role.GET_PACKAGES: Get available packages
* Role.GET_REPO_LIST: Get repository list
* Role.REQUIRED_BY: Get packages required by given package
* Role.GET_UPDATE_DETAIL: Get update details
* Role.GET_UPDATES: Get available updates
* Role.INSTALL_FILES: Install package files
* Role.INSTALL_PACKAGES: Install packages
* Role.INSTALL_SIGNATURE: Install signature
* Role.REFRESH_CACHE: Refresh cache
* Role.REMOVE_PACKAGES: Remove packages
* Role.REPO_ENABLE: Enable repository
* Role.REPO_SET_DATA:
* Role.RESOLVE: Resolve depdencies
* Role.SEARCH_DETAILS: Search for details
* Role.SEARCH_FILE: Search for file
* Role.SEARCH_GROUP: Search for group
* Role.SEARCH_NAME: Search for package name
* Role.UPDATE_PACKAGES: Update packages
* Role.WHAT_PROVIDES: Get what a package provides
* Role.ACCEPT_EULA: Accept an EULA
* Role.DOWNLOAD_PACKAGES: Download packages
* Role.GET_DISTRO_UPGRADES: Get available distribution upgrades
* Role.GET_CATEGORIES: Get available categories
* Role.GET_OLD_TRANSACTIONS: Get old transation information
* Role.REPAIR_SYSTEM: Repair system
* Role.GET_DETAILS_LOCAL: Get details on local package
* Role.GET_FILES_LOCAL: Get files provided by local package
* Role.REPO_REMOVE: Remove repository
* Role.UPGRADE_SYSTEM: Upgrade system
"""
UNKNOWN = auto()
CANCEL = auto()
DEPENDS_ON = auto()
GET_DETAILS = auto()
GET_FILES = auto()
GET_PACKAGES = auto()
GET_REPO_LIST = auto()
REQUIRED_BY = auto()
GET_UPDATE_DETAIL = auto()
GET_UPDATES = auto()
INSTALL_FILES = auto()
INSTALL_PACKAGES = auto()
INSTALL_SIGNATURE = auto()
REFRESH_CACHE = auto()
REMOVE_PACKAGES = auto()
REPO_ENABLE = auto()
REPO_SET_DATA = auto()
RESOLVE = auto()
SEARCH_DETAILS = auto()
SEARCH_FILE = auto()
SEARCH_GROUP = auto()
SEARCH_NAME = auto()
UPDATE_PACKAGES = auto()
WHAT_PROVIDES = auto()
ACCEPT_EULA = auto()
DOWNLOAD_PACKAGES = auto()
GET_DISTRO_UPGRADES = auto()
GET_CATEGORIES = auto()
GET_OLD_TRANSACTIONS = auto()
REPAIR_SYSTEM = auto()
GET_DETAILS_LOCAL = auto()
GET_FILES_LOCAL = auto()
REPO_REMOVE = auto()
UPGRADE_SYSTEM = auto()
class Status(PkFlag):
"""
What status we are now; this can change for each transaction giving a
status of what sort of thing is happening
Icons that change to represent the current status of the transaction will
use these constants
If you add to these, make sure you add filenames in gpk-watch.c also
A typical transaction will do:
- schedule task
WAIT
- run task
SETUP
- wait for lock
RUNNING
This means that backends should run pk_backend_set_status (backend,
PK_STATUS_ENUM_RUNNING)
when they are ready to start running the transaction and after a lock has
been got.
* Status.UNKNOWN: Unknown status
* Status.WAIT: Waiting
* Status.SETUP: Setting up
* Status.RUNNING: Running
* Status.QUERY:
* Status.INFO:
* Status.REMOVE: Removing
* Status.REFRESH_CACHE: Refreshing cache
* Status.DOWNLOAD: Downloading
* Status.INSTALL: Installing
* Status.UPDATE: Updating
* Status.CLEANUP: Cleaning up
* Status.OBSOLETE:
* Status.DEP_RESOLVE: Resolving dependencies
* Status.SIG_CHECK: Checking signatures
* Status.TEST_COMMIT: Testing commit
* Status.COMMIT: Committing
* Status.REQUEST:
* Status.FINISHED: Finished
* Status.CANCEL: Cancelling
* Status.DOWNLOAD_REPOSITORY: Downloading respository
* Status.DOWNLOAD_PACKAGELIST: Donwloading package list
* Status.DOWNLOAD_FILELIST: Downloading file list
* Status.DOWNLOAD_CHANGELOG: Downloading changelog information
* Status.DOWNLOAD_GROUP: Downloading group information
* Status.DOWNLOAD_UPDATEINFO: Downloading update information
* Status.REPACKAGING: Repackaging
* Status.LOADING_CACHE: Loading cache
* Status.SCAN_APPLICATIONS: Scanning for applications
* Status.GENERATE_PACKAGE_LIST: Generating package list
* Status.WAITING_FOR_LOCK: Waiting for lock
* Status.WAITING_FOR_AUTH: Waiting for authentication/authorization
* Status.SCAN_PROCESS_LIST: Scanning running processes
* Status.CHECK_EXECUTABLE_FILES: Checking executable files
* Status.CHECK_LIBRARIES: Checking libraries
* Status.COPY_FILES: Copying files
* Status.RUN_HOOK: Running package hook
"""
UNKNOWN = auto()
WAIT = auto()
SETUP = auto()
RUNNING = auto()
QUERY = auto()
INFO = auto()
REMOVE = auto()
REFRESH_CACHE = auto()
DOWNLOAD = auto()
INSTALL = auto()
UPDATE = auto()
CLEANUP = auto()
OBSOLETE = auto()
DEP_RESOLVE = auto()
SIG_CHECK = auto()
TEST_COMMIT = auto()
COMMIT = auto()
REQUEST = auto()
FINISHED = auto()
CANCEL = auto()
DOWNLOAD_REPOSITORY = auto()
DOWNLOAD_PACKAGELIST = auto()
DOWNLOAD_FILELIST = auto()
DOWNLOAD_CHANGELOG = auto()
DOWNLOAD_GROUP = auto()
DOWNLOAD_UPDATEINFO = auto()
REPACKAGING = auto()
LOADING_CACHE = auto()
SCAN_APPLICATIONS = auto()
GENERATE_PACKAGE_LIST = auto()
WAITING_FOR_LOCK = auto()
WAITING_FOR_AUTH = auto()
SCAN_PROCESS_LIST = auto()
CHECK_EXECUTABLE_FILES = auto()
CHECK_LIBRARIES = auto()
COPY_FILES = auto()
RUN_HOOK = auto()
class Exit(PkFlag):
"""
How the backend exited
* Exit.UNKNOWN: Unknown exit status
* Exit.SUCCESS: Backend exited successfully
* Exit.FAILED: Backend failed
* Exit.CANCELLED: Backend was cancelled
* Exit.KEY_REQUIRED: A repository encryption key needs installing
* Exit.EULA_REQUIRED: A EULA is required to be accepted
* Exit.KILLED: Backend was killed
* Exit.MEDIA_CHANGE_REQUIRED: Media change required
* Exit.NEED_UNTRUSTED:
* Exit.CANCELLED_PRIORITY: Cancelled due to higher priority task
* Exit.SKIP_TRANSACTION:
* Exit.REPAIR_REQUIRED: Package database requires repairing
"""
UNKNOWN = auto()
SUCCESS = auto()
FAILED = auto()
CANCELLED = auto()
KEY_REQUIRED = auto()
EULA_REQUIRED = auto()
KILLED = auto()
MEDIA_CHANGE_REQUIRED = auto()
NEED_UNTRUSTED = auto()
CANCELLED_PRIORITY = auto()
SKIP_TRANSACTION = auto()
REPAIR_REQUIRED = auto()
class Network(PkFlag):
"""
Network type
* Network.UNKNOWN: Unknown network
* Network.OFFLINE: Offline (no network)
* Network.ONLINE: Online (network type unknown)
* Network.WIRED: Wired network
* Network.WIFI: WiFi network
* Network.MOBILE: Mobile network
"""
UNKNOWN = auto()
OFFLINE = auto()
ONLINE = auto()
WIRED = auto()
WIFI = auto()
MOBILE = auto()
class Filter(PkFlag):
"""
The filter types
* Filter.UNKNOWN: Unknown filter
* Filter.NONE: No filter
* Filter.INSTALLED: Filter for installed packages
* Filter.NOT_INSTALLED: Filter for not installed packages
* Filter.DEVELOPMENT: Filter for development packages
* Filter.NOT_DEVELOPMENT: Filter for non-development packages
* Filter.GUI: Filter for GUI packages
* Filter.NOT_GUI: Filter for non-GUI packages
* Filter.FREE: Filter for free packages
* Filter.NOT_FREE: Filter for non-free packages
* Filter.VISIBLE: Filter for visible packages
* Filter.NOT_VISIBLE: Filter for invisible packages
* Filter.SUPPORTED: Filter for supported packages
* Filter.NOT_SUPPORTED: Filter for not supported packages
* Filter.BASENAME: Filter for packages that match basename
* Filter.NOT_BASENAME: Filter for packages that don't match basename
* Filter.NEWEST: Filter for newest packages
* Filter.NOT_NEWEST: Filter for not newest packages
* Filter.ARCH: Filter for packages that match architecture
* Filter.NOT_ARCH: Filter for packages that don't match architecture
* Filter.SOURCE: Filter for source packages
* Filter.NOT_SOURCE: Filter for non-source packages
* Filter.COLLECTIONS: Filter for collections
* Filter.NOT_COLLECTIONS: Filter for not collections
* Filter.APPLICATION: Filter for application packages
* Filter.NOT_APPLICATION: Filter for non-application packages
* Filter.DOWNLOADED: Filter for downloaded packages
* Filter.NOT_DOWNLOADED: Filter for not downloaded packages
"""
@property
def pkstring(self) -> str:
pks = self.name
if pks is None:
return " | ".join([f.pkstring for f in self])
if pks in ["DEVELOPMENT", "NOT_DEVELOPMENT"]:
pks = pks[:-6]
if pks[:4] == "NOT_":
pks = "~" + pks[4:]
return pks.lower().replace("_", "-")
UNKNOWN = auto()
NONE = auto()
INSTALLED = auto()
NOT_INSTALLED = auto()
DEVELOPMENT = auto()
NOT_DEVELOPMENT = auto()
GUI = auto()
NOT_GUI = auto()
FREE = auto()
NOT_FREE = auto()
VISIBLE = auto()
NOT_VISIBLE = auto()
SUPPORTED = auto()
NOT_SUPPORTED = auto()
BASENAME = auto()
NOT_BASENAME = auto()
NEWEST = auto()
NOT_NEWEST = auto()
ARCH = auto()
NOT_ARCH = auto()
SOURCE = auto()
NOT_SOURCE = auto()
COLLECTIONS = auto()
NOT_COLLECTIONS = auto()
APPLICATION = auto()
NOT_APPLICATION = auto()
DOWNLOADED = auto()
NOT_DOWNLOADED = auto()
class Restart(PkFlag):
"""
What restart we need to after a transaction, ordered by severity
* Restart.UNKNOWN: Unknown restart state
* Restart.NONE: No restart required
* Restart.APPLICATION: Need to restart the application
* Restart.SESSION: Need to restart the session
* Restart.SYSTEM: Need to restart the system
* Restart.SECURITY_SESSION:
* Restart.SECURITY_SYSTEM:
"""
UNKNOWN = auto()
NONE = auto()
APPLICATION = auto()
SESSION = auto()
SYSTEM = auto()
SECURITY_SESSION = auto()
SECURITY_SYSTEM = auto()
class Error(PkFlag):
"""
The error type
* Error.UNKNOWN:
* Error.OOM: Out of memory
* Error.NO_NETWORK: No network access available
* Error.NOT_SUPPORTED: Request not supported
* Error.INTERNAL_ERROR: Undefined internal error
* Error.GPG_FAILURE: GPG encryption failure
* Error.PACKAGE_ID_INVALID: Invalid package ID provided
* Error.PACKAGE_NOT_INSTALLED: Requested package not installed
* Error.PACKAGE_NOT_FOUND: Requested package not found
* Error.PACKAGE_ALREADY_INSTALLED: Requested package already installed
* Error.PACKAGE_DOWNLOAD_FAILED: Failed to download package
* Error.GROUP_NOT_FOUND: Requested group not gound
* Error.GROUP_LIST_INVALID: Invalid group list provided
* Error.DEP_RESOLUTION_FAILED: Failed to resolve dependencies
* Error.FILTER_INVALID: Invalid filter provides
* Error.CREATE_THREAD_FAILED: Failed to create thread
* Error.TRANSACTION_ERROR: Error occurred during transaction
* Error.TRANSACTION_CANCELLED: Transaction was cancelled
* Error.NO_CACHE: No cache available
* Error.REPO_NOT_FOUND: Requested repository not found
* Error.CANNOT_REMOVE_SYSTEM_PACKAGE: Not allowed to remove system package
* Error.PROCESS_KILL: Process killed
* Error.FAILED_INITIALIZATION:
* Error.FAILED_FINALISE:
* Error.FAILED_CONFIG_PARSING: Configuration is not valid
* Error.CANNOT_CANCEL:
* Error.CANNOT_GET_LOCK: Cannot get lock
* Error.NO_PACKAGES_TO_UPDATE: No packages to update
* Error.CANNOT_WRITE_REPO_CONFIG: Cannot write repository configuration
* Error.LOCAL_INSTALL_FAILED:
* Error.BAD_GPG_SIGNATURE: Bad GPG signature found
* Error.MISSING_GPG_SIGNATURE: Required GPG signature not found
* Error.CANNOT_INSTALL_SOURCE_PACKAGE: Cannot install source package
* Error.REPO_CONFIGURATION_ERROR:
* Error.NO_LICENSE_AGREEMENT:
* Error.FILE_CONFLICTS: File conflicts detected
* Error.PACKAGE_CONFLICTS: Package conflict
* Error.REPO_NOT_AVAILABLE: Repository not available
* Error.INVALID_PACKAGE_FILE:
* Error.PACKAGE_INSTALL_BLOCKED: Package installation blocked
* Error.PACKAGE_CORRUPT: Package corruption occurred
* Error.ALL_PACKAGES_ALREADY_INSTALLED: All packages already installed
* Error.FILE_NOT_FOUND: Required file not found
* Error.NO_MORE_MIRRORS_TO_TRY: Out of repository mirrors to try
* Error.NO_DISTRO_UPGRADE_DATA: No distribution upgrade path found
* Error.INCOMPATIBLE_ARCHITECTURE: Incompatible architecture found
* Error.NO_SPACE_ON_DEVICE: Out of required disk space
* Error.MEDIA_CHANGE_REQUIRED: Need to change media
* Error.NOT_AUTHORIZED: Authorization failed
* Error.UPDATE_NOT_FOUND: Update not found
* Error.CANNOT_INSTALL_REPO_UNSIGNED:
Installation repository missing signature
* Error.CANNOT_UPDATE_REPO_UNSIGNED: Update repository missing signature
* Error.CANNOT_GET_FILELIST: Cannot get file list
* Error.CANNOT_GET_REQUIRES: Cannot get package requirements
* Error.CANNOT_DISABLE_REPOSITORY: Cannot disable reposoitory
* Error.RESTRICTED_DOWNLOAD:
* Error.PACKAGE_FAILED_TO_CONFIGURE: Package failed to configure
* Error.PACKAGE_FAILED_TO_BUILD: Package failed to build
* Error.PACKAGE_FAILED_TO_INSTALL: Package failed to install
* Error.PACKAGE_FAILED_TO_REMOVE: Package failed to remove
* Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
* Error.PACKAGE_DATABASE_CHANGED:
* Error.PROVIDE_TYPE_NOT_SUPPORTED:
* Error.INSTALL_ROOT_INVALID: Installtion root not suitable
* Error.CANNOT_FETCH_SOURCES: Cannot fetch sources
* Error.CANCELLED_PRIORITY: Cancelled due to higher priority task
* Error.UNFINISHED_TRANSACTION: Transaction unfinished
* Error.LOCK_REQUIRED: Required lock not available
* Error.REPO_ALREADY_SET:
"""
@property
def pkstring(self) -> str:
if self == Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
return "failed-due-to-running-process"
return super().pkstring
UNKNOWN = auto()
OUT_OF_MEMORY = auto()
NO_NETWORK = auto()
NOT_SUPPORTED = auto()
INTERNAL_ERROR = auto()
GPG_FAILURE = auto()
PACKAGE_ID_INVALID = auto()
PACKAGE_NOT_INSTALLED = auto()
PACKAGE_NOT_FOUND = auto()
PACKAGE_ALREADY_INSTALLED = auto()
PACKAGE_DOWNLOAD_FAILED = auto()
GROUP_NOT_FOUND = auto()
GROUP_LIST_INVALID = auto()
DEP_RESOLUTION_FAILED = auto()
FILTER_INVALID = auto()
CREATE_THREAD_FAILED = auto()
TRANSACTION_ERROR = auto()
TRANSACTION_CANCELLED = auto()
NO_CACHE = auto()
REPO_NOT_FOUND = auto()
CANNOT_REMOVE_SYSTEM_PACKAGE = auto()
PROCESS_KILL = auto()
FAILED_INITIALIZATION = auto()
FAILED_FINALISE = auto()
FAILED_CONFIG_PARSING = auto()
CANNOT_CANCEL = auto()
CANNOT_GET_LOCK = auto()
NO_PACKAGES_TO_UPDATE = auto()
CANNOT_WRITE_REPO_CONFIG = auto()
LOCAL_INSTALL_FAILED = auto()
BAD_GPG_SIGNATURE = auto()
MISSING_GPG_SIGNATURE = auto()
CANNOT_INSTALL_SOURCE_PACKAGE = auto()
REPO_CONFIGURATION_ERROR = auto()
NO_LICENSE_AGREEMENT = auto()
FILE_CONFLICTS = auto()
PACKAGE_CONFLICTS = auto()
REPO_NOT_AVAILABLE = auto()
INVALID_PACKAGE_FILE = auto()
PACKAGE_INSTALL_BLOCKED = auto()
PACKAGE_CORRUPT = auto()
ALL_PACKAGES_ALREADY_INSTALLED = auto()
FILE_NOT_FOUND = auto()
NO_MORE_MIRRORS_TO_TRY = auto()
NO_DISTRO_UPGRADE_DATA = auto()
INCOMPATIBLE_ARCHITECTURE = auto()
NO_SPACE_ON_DEVICE = auto()
MEDIA_CHANGE_REQUIRED = auto()
NOT_AUTHORIZED = auto()
UPDATE_NOT_FOUND = auto()
CANNOT_INSTALL_REPO_UNSIGNED = auto()
CANNOT_UPDATE_REPO_UNSIGNED = auto()
CANNOT_GET_FILELIST = auto()
CANNOT_GET_REQUIRES = auto()
CANNOT_DISABLE_REPOSITORY = auto()
RESTRICTED_DOWNLOAD = auto()
PACKAGE_FAILED_TO_CONFIGURE = auto()
PACKAGE_FAILED_TO_BUILD = auto()
PACKAGE_FAILED_TO_INSTALL = auto()
PACKAGE_FAILED_TO_REMOVE = auto()
UPDATE_FAILED_DUE_TO_RUNNING_PROCESS = auto()
PACKAGE_DATABASE_CHANGED = auto()
PROVIDE_TYPE_NOT_SUPPORTED = auto()
INSTALL_ROOT_INVALID = auto()
CANNOT_FETCH_SOURCES = auto()
CANCELLED_PRIORITY = auto()
UNFINISHED_TRANSACTION = auto()
LOCK_REQUIRED = auto()
REPO_ALREADY_SET = auto()
OOM = OUT_OF_MEMORY
class Group(PkFlag):
"""
The group type
* Group.UNKNOWN: Unknown group
* Group.ACCESSIBILITY: Accessibility related packages
* Group.ACCESSORIES: Accessory packages
* Group.ADMIN_TOOLS: Administration tools packages
* Group.COMMUNICATION: Communication packages
* Group.DESKTOP_GNOME: GNOME packages
* Group.DESKTOP_KDE: KDE packages
* Group.DESKTOP_OTHER: Other desktop packages
* Group.DESKTOP_XFCE: XFCE packages
* Group.EDUCATION: Education packages
* Group.FONTS: Fonts
* Group.GAMES: Games
* Group.GRAPHICS: Graphics related packages
* Group.INTERNET: Internet related packages
* Group.LEGACY: Legacy packages
* Group.LOCALIZATION: Localization related packages
* Group.MAPS: Map related packages
* Group.MULTIMEDIA: Multimedia packages
* Group.NETWORK: Network related packages
* Group.OFFICE: Office packages
* Group.OTHER:
* Group.POWER_MANAGEMENT: Power-management related packages
* Group.PROGRAMMING: Programming packages
* Group.PUBLISHING: Publishing related packages
* Group.REPOS:
* Group.SECURITY: Security packages
* Group.SERVERS: Server related packages
* Group.SYSTEM: System packages
* Group.VIRTUALIZATION: Virtualization packages
* Group.SCIENCE: Science related packages
* Group.DOCUMENTATION: Documentation
* Group.ELECTRONICS: Electronics package
* Group.COLLECTIONS:
* Group.VENDOR: Vendor defined group
* Group.NEWEST: Special group for recently updated packages
"""
UNKNOWN = auto()
ACCESSIBILITY = auto()
ACCESSORIES = auto()
ADMIN_TOOLS = auto()
COMMUNICATION = auto()
DESKTOP_GNOME = auto()
DESKTOP_KDE = auto()
DESKTOP_OTHER = auto()
DESKTOP_XFCE = auto()
EDUCATION = auto()
FONTS = auto()
GAMES = auto()
GRAPHICS = auto()
INTERNET = auto()
LEGACY = auto()
LOCALIZATION = auto()
MAPS = auto()
MULTIMEDIA = auto()
NETWORK = auto()
OFFICE = auto()
OTHER = auto()
POWER_MANAGEMENT = auto()
PROGRAMMING = auto()
PUBLISHING = auto()
REPOS = auto()
SECURITY = auto()
SERVERS = auto()
SYSTEM = auto()
VIRTUALIZATION = auto()
SCIENCE = auto()
DOCUMENTATION = auto()
ELECTRONICS = auto()
COLLECTIONS = auto()
VENDOR = auto()
NEWEST = auto()
class UpdateState(PkFlag):
"""
What state the update is in
* UpdateState.UNKNOWN: Update stability unknown
* UpdateState.STABLE: Update is a stable release
* UpdateState.UNSTABLE: Update is an unstable release
* UpdateState.TESTING: Update is a testing release
"""
UNKNOWN = auto()
STABLE = auto()
UNSTABLE = auto()
TESTING = auto()
class Info(PkFlag):
"""
The enumerated types used in Package() - these have to refer to a specific
package action, rather than a general state
* Info.UNKNOWN: Package status is unknown
* Info.INSTALLED: Package is installed
* Info.AVAILABLE: Package is available to be installed
* Info.LOW:
* Info.ENHANCEMENT:
* Info.NORMAL:
* Info.BUGFIX:
* Info.IMPORTANT:
* Info.SECURITY:
* Info.BLOCKED: Package is blocked
* Info.DOWNLOADING: Package is downloading
* Info.UPDATING: Package is updating
* Info.INSTALLING: Package is being installed
* Info.REMOVING: Package is being removed
* Info.CLEANUP: Package is running cleanup
* Info.OBSOLETING:
* Info.COLLECTION_INSTALLED:
* Info.COLLECTION_AVAILABLE:
* Info.FINISHED:
* Info.REINSTALLING: Package is being reinstalled
* Info.DOWNGRADING: Package is being downgraded
* Info.PREPARING: Package is preparing for installation/removal
* Info.DECOMPRESSING: Package is decompressing
* Info.UNTRUSTED:
* Info.TRUSTED:
* Info.UNAVAILABLE: Package is unavailable
* Info.CRITICAL: Update severity is critical; Since: 1.2.4
"""
UNKNOWN = auto()
INSTALLED = auto()
AVAILABLE = auto()
LOW = auto()
ENHANCEMENT = auto()
NORMAL = auto()
BUGFIX = auto()
IMPORTANT = auto()
SECURITY = auto()
BLOCKED = auto()
DOWNLOADING = auto()
UPDATING = auto()
INSTALLING = auto()
REMOVING = auto()
CLEANUP = auto()
OBSOLETING = auto()
COLLECTION_INSTALLED = auto()
COLLECTION_AVAILABLE = auto()
FINISHED = auto()
REINSTALLING = auto()
DOWNGRADING = auto()
PREPARING = auto()
DECOMPRESSING = auto()
UNTRUSTED = auto()
TRUSTED = auto()
UNAVAILABLE = auto()
CRITICAL = auto()
class DistroUpgrade(PkFlag):
"""
The distro upgrade status
* DistroUpgrade.UNKNOWN: Unknown disto upgrade state
* DistroUpgrade.STABLE: Upgraded to stable release
* DistroUpgrade.UNSTABLE: Upgraded to unstable release
"""
UNKNOWN = auto()
STABLE = auto()
UNSTABLE = auto()
class SigType(PkFlag):
"""
The signature type type
* SigType.UNKNOWN: Unkwown signature type
* SigType.GPG: GPG signature
"""
UNKNOWN = auto()
GPG = auto()
class MediaType(PkFlag):
"""
The media type
* MediaType.UNKNOWN: Unknown media type
* MediaType.CD: Media is a CD
* MediaType.DVD: Media is a DVD
* MediaType.DISC: Media is a disc (not CD or DVD)
"""
UNKNOWN = auto()
CD = auto()
DVD = auto()
DISC = auto()
class Authorize(PkFlag):
"""
The authorization result
* Authorize.UNKNOWN: Unknown authorization status
* Authorize.YES: Authorized
* Authorize.NO: Not authorized
* Authorize.INTERACTIVE: Interaction required for authorization
"""
UNKNOWN = auto()
YES = auto()
NO = auto()
INTERACTIVE = auto()
class UpgradeKind(PkFlag):
"""
The type of distribution upgrade to perform
* UpgradeKind.UNKNOWN:
* UpgradeKind.MINIMAL: Perform minimal upgrade
* UpgradeKind.DEFAULT: Perform default upgrade
* UpgradeKind.COMPLETE: Perform complete upgrade
"""
UNKNOWN = auto()
MINIMAL = auto()
DEFAULT = auto()
COMPLETE = auto()
class TransactionFlag(PkFlag):
"""
The transaction flags that alter how the transaction is handled
* TransactionFlag.NONE: No transaction flag
* TransactionFlag.ONLY_TRUSTED: Only allow trusted packages
* TransactionFlag.SIMULATE: Simulate transaction
* TransactionFlag.ONLY_DOWNLOAD: Only download packages
* TransactionFlag.ALLOW_REINSTALL: Allow package reinstallation
* TransactionFlag.JUST_REINSTALL: Only allow package reinstallation
* TransactionFlag.ALLOW_DOWNGRADE: Allow packages to be downgraded
"""
NONE = auto()
ONLY_TRUSTED = auto()
SIMULATE = auto()
ONLY_DOWNLOAD = auto()
ALLOW_REINSTALL = auto()
JUST_REINSTALL = auto()
ALLOW_DOWNGRADE = auto()
-70
View File
@@ -1,70 +0,0 @@
# General Server Utilities
#
# 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 os
import subprocess
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)
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.header = "Moonraker Log Start...\n"
self.header += "Git Version: " + get_software_version() + "\n"
self.header += "="*80 + "\n"
if self.stream is not None:
self.stream.write(self.header)
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
if self.stream is not None:
self.stream.write(self.header)
# Parse the git version from the command line. This code
# is borrowed from Klipper.
def get_software_version():
moonraker_path = os.path.join(
os.path.dirname(__file__), '..')
# Obtain version info from "git" program
prog = ('git', '-C', moonraker_path, 'describe', '--always',
'--tags', '--long', '--dirty', "--all")
try:
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ver, err = process.communicate()
retcode = process.wait()
if retcode == 0:
version = ver.strip()
if isinstance(version, bytes):
version = version.decode()
return version
else:
logging.debug("Error getting git version: %s", err)
except OSError:
logging.exception("Error runing git describe")
return "?"
+196
View File
@@ -0,0 +1,196 @@
# General Server Utilities
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import os
import glob
import importlib
import pathlib
import sys
import subprocess
import asyncio
import hashlib
import json
import shlex
import re
import struct
import socket
import enum
from . import source_info
# Annotation imports
from typing import (
TYPE_CHECKING,
List,
Optional,
ClassVar,
Tuple,
Dict,
Union
)
if TYPE_CHECKING:
from types import ModuleType
from asyncio.trsock import TransportSocket
SYS_MOD_PATHS = glob.glob("/usr/lib/python3*/dist-packages")
SYS_MOD_PATHS += glob.glob("/usr/lib/python3*/site-packages")
class ServerError(Exception):
def __init__(self, message: str, status_code: int = 400) -> None:
Exception.__init__(self, message)
self.status_code = status_code
class Sentinel(enum.Enum):
MISSING = object()
def _run_git_command(cmd: str) -> str:
prog = shlex.split(cmd)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ret, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return ret.strip().decode()
raise Exception(f"Failed to run git command: {cmd}")
def _retrieve_git_tag(source_path: str) -> str:
cmd = f"git -C {source_path} rev-list --tags --max-count=1"
hash = _run_git_command(cmd)
cmd = f"git -C {source_path} describe --tags {hash}"
tag = _run_git_command(cmd)
cmd = f"git -C {source_path} rev-list {tag}..HEAD --count"
count = _run_git_command(cmd)
return f"{tag}-{count}"
# Parse the git version from the command line. This code
# is borrowed from Klipper.
def retrieve_git_version(source_path: str) -> str:
# Obtain version info from "git" program
cmd = f"git -C {source_path} describe --always --tags --long --dirty"
ver = _run_git_command(cmd)
tag_match = re.match(r"v\d+\.\d+\.\d+", ver)
if tag_match is not None:
return ver
# This is likely a shallow clone. Resolve the tag and manually create
# the version string
tag = _retrieve_git_tag(source_path)
return f"t{tag}-g{ver}-shallow"
def get_software_version() -> str:
pkg_ver = source_info.package_version()
if pkg_ver is not None:
return pkg_ver
version: str = "?"
src_path = source_info.source_path()
try:
version = retrieve_git_version(str(src_path))
except Exception:
vfile = src_path.joinpath("moonraker/.version")
if vfile.exists():
try:
version = vfile.read_text().strip()
except Exception:
logging.exception("Unable to extract version from file")
version = "?"
return version
def hash_directory(
dir_path: Union[str, pathlib.Path],
ignore_exts: List[str],
ignore_dirs: List[str]
) -> str:
if isinstance(dir_path, str):
dir_path = pathlib.Path(dir_path)
checksum = hashlib.blake2s()
if not dir_path.exists():
return ""
for dpath, dnames, fnames in os.walk(dir_path):
valid_dirs: List[str] = []
for dname in sorted(dnames):
if dname[0] == '.' or dname in ignore_dirs:
continue
valid_dirs.append(dname)
dnames[:] = valid_dirs
for fname in sorted(fnames):
ext = os.path.splitext(fname)[-1].lower()
if fname[0] == '.' or ext in ignore_exts:
continue
fpath = pathlib.Path(os.path.join(dpath, fname))
try:
checksum.update(fpath.read_bytes())
except Exception:
pass
return checksum.hexdigest()
def verify_source(
path: Optional[Union[str, pathlib.Path]] = None
) -> Optional[Tuple[str, bool]]:
if path is None:
path = source_info.source_path()
elif isinstance(path, str):
path = pathlib.Path(path)
rfile = path.joinpath(".release_info")
if not rfile.exists():
return None
try:
rinfo = json.loads(rfile.read_text())
except Exception:
return None
orig_chksum = rinfo['source_checksum']
ign_dirs = rinfo['ignored_dirs']
ign_exts = rinfo['ignored_exts']
checksum = hash_directory(path, ign_exts, ign_dirs)
return checksum, checksum == orig_chksum
def load_system_module(name: str) -> ModuleType:
for module_path in SYS_MOD_PATHS:
sys.path.insert(0, module_path)
try:
module = importlib.import_module(name)
except ImportError as e:
if not isinstance(e, ModuleNotFoundError):
logging.exception(f"Failed to load {name} module")
sys.path.pop(0)
else:
sys.path.pop(0)
break
else:
raise ServerError(f"Unable to import module {name}")
return module
def get_unix_peer_credentials(
writer: asyncio.StreamWriter, name: str
) -> Dict[str, int]:
sock: TransportSocket
sock = writer.get_extra_info("socket", None)
if sock is None:
logging.debug(
f"Unable to get underlying Unix Socket for {name}, "
"cant fetch peer credentials"
)
return {}
data: bytes = b""
try:
size = struct.calcsize("3I")
data = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, size)
pid, uid, gid = struct.unpack("3I", data)
except asyncio.CancelledError:
raise
except Exception:
logging.exception(
f"Failed to get Unix Socket Peer Credentials for {name}"
f", raw: 0x{data.hex()}"
)
return {}
return {
"process_id": pid,
"user_id": uid,
"group_id": gid
}
+77
View File
@@ -0,0 +1,77 @@
# General Server Utilities
#
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import importlib.resources as ilr
import pathlib
import sys
import site
# Annotation imports
from typing import (
Optional,
)
def package_path() -> pathlib.Path:
return pathlib.Path(__file__).parent.parent
def source_path() -> pathlib.Path:
return package_path().parent
def is_git_repo(src_path: Optional[pathlib.Path] = None) -> bool:
if src_path is None:
return source_path().joinpath(".git").is_dir()
return src_path.joinpath(".git").is_dir()
def is_dist_package(src_path: Optional[pathlib.Path] = None) -> bool:
if src_path is None:
# Fetch dist info for moonraker. This should be the most reliable
# method
src_path = source_path()
site_dirs = site.getsitepackages()
return str(src_path) in site_dirs
else:
# Make an assumption based on the source path. If its name is
# site-packages or dist-packages then presumably it is an
# installed package
return src_path.name in ["dist-packages", "site-packages"]
def package_version() -> Optional[str]:
try:
import moonraker.__version__ as ver # type: ignore
version = ver.__version__
except Exception:
pass
else:
if version:
return version
return None
def read_asset(asset_name: str) -> Optional[str]:
if sys.version_info < (3, 10):
with ilr.path("moonraker.assets", asset_name) as p:
if not p.is_file():
return None
return p.read_text()
else:
files = ilr.files("moonraker.assets")
with ilr.as_file(files.joinpath(asset_name)) as p:
if not p.is_file():
return None
return p.read_text()
def get_asset_path() -> Optional[pathlib.Path]:
if sys.version_info < (3, 10):
with ilr.path("moonraker.assets", "__init__.py") as p:
asset_path = p.parent
else:
files = ilr.files("moonraker.assets")
with ilr.as_file(files.joinpath("__init__.py")) as p:
asset_path = p.parent
if not asset_path.is_dir():
# Somehow running in a zipapp. This is an error.
return None
return asset_path
+923 -167
View File
File diff suppressed because it is too large. Load diff
Generated
+674
View File
@@ -0,0 +1,674 @@
# This file is @generated by PDM.
# It is not intended for manual editing.
[[package]]
name = "apprise"
version = "1.2.1"
requires_python = ">=3.6"
summary = "Push Notifications that work with just about every platform!"
dependencies = [
"PyYAML",
"certifi",
"click>=5.0",
"markdown",
"requests",
"requests-oauthlib",
]
[[package]]
name = "async-timeout"
version = "4.0.2"
requires_python = ">=3.6"
summary = "Timeout context manager for asyncio programs"
dependencies = [
"typing-extensions>=3.6.5; python_version < \"3.8\"",
]
[[package]]
name = "certifi"
version = "2022.12.7"
requires_python = ">=3.6"
summary = "Python package for providing Mozilla's CA Bundle."
[[package]]
name = "charset-normalizer"
version = "3.0.1"
summary = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
[[package]]
name = "click"
version = "8.1.3"
requires_python = ">=3.7"
summary = "Composable command line interface toolkit"
dependencies = [
"colorama; platform_system == \"Windows\"",
"importlib-metadata; python_version < \"3.8\"",
]
[[package]]
name = "colorama"
version = "0.4.6"
requires_python = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
summary = "Cross-platform colored terminal text."
[[package]]
name = "dbus-next"
version = "0.2.3"
requires_python = ">=3.6.0"
summary = "A zero-dependency DBus library for Python with asyncio support"
[[package]]
name = "distro"
version = "1.8.0"
requires_python = ">=3.6"
summary = "Distro - an OS platform information API"
[[package]]
name = "idna"
version = "3.4"
requires_python = ">=3.5"
summary = "Internationalized Domain Names in Applications (IDNA)"
[[package]]
name = "ifaddr"
version = "0.2.0"
summary = "Cross-platform network interface and IP address enumeration library"
[[package]]
name = "importlib-metadata"
version = "6.0.0"
requires_python = ">=3.7"
summary = "Read metadata from Python packages"
dependencies = [
"typing-extensions>=3.6.4; python_version < \"3.8\"",
"zipp>=0.5",
]
[[package]]
name = "inotify-simple"
version = "1.3.5"
requires_python = ">=2.7, !=3.0.*, !=3.1.*"
summary = "A simple wrapper around inotify. No fancy bells and whistles, just a literal wrapper with ctypes. Under 100 lines of code!"
[[package]]
name = "jinja2"
version = "3.1.2"
requires_python = ">=3.7"
summary = "A very fast and expressive template engine."
dependencies = [
"MarkupSafe>=2.0",
]
[[package]]
name = "ldap3"
version = "2.9.1"
summary = "A strictly RFC 4510 conforming LDAP V3 pure Python client library"
dependencies = [
"pyasn1>=0.4.6",
]
[[package]]
name = "libnacl"
version = "1.8.0"
summary = "Python bindings for libsodium based on ctypes"
[[package]]
name = "lmdb"
version = "1.3.0"
summary = "Universal Python binding for the LMDB 'Lightning' Database"
[[package]]
name = "markdown"
version = "3.4.1"
requires_python = ">=3.7"
summary = "Python implementation of Markdown."
dependencies = [
"importlib-metadata>=4.4; python_version < \"3.10\"",
]
[[package]]
name = "markupsafe"
version = "2.1.2"
requires_python = ">=3.7"
summary = "Safely add untrusted strings to HTML/XML markup."
[[package]]
name = "oauthlib"
version = "3.2.2"
requires_python = ">=3.6"
summary = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic"
[[package]]
name = "paho-mqtt"
version = "1.6.1"
summary = "MQTT version 5.0/3.1.1 client class"
[[package]]
name = "pillow"
version = "9.3.0"
requires_python = ">=3.7"
summary = "Python Imaging Library (Fork)"
[[package]]
name = "preprocess-cancellation"
version = "0.2.0"
requires_python = ">=3.6.2"
summary = "GCode processor to add klipper cancel-object markers"
[[package]]
name = "pyasn1"
version = "0.4.8"
summary = "ASN.1 types and codecs"
[[package]]
name = "pyserial"
version = "3.4"
summary = "Python Serial Port Extension"
[[package]]
name = "pyserial-asyncio"
version = "0.6"
summary = "Python Serial Port Extension - Asynchronous I/O support"
dependencies = [
"pyserial",
]
[[package]]
name = "pyyaml"
version = "6.0"
requires_python = ">=3.6"
summary = "YAML parser and emitter for Python"
[[package]]
name = "requests"
version = "2.28.2"
requires_python = ">=3.7, <4"
summary = "Python HTTP for Humans."
dependencies = [
"certifi>=2017.4.17",
"charset-normalizer<4,>=2",
"idna<4,>=2.5",
"urllib3<1.27,>=1.21.1",
]
[[package]]
name = "requests-oauthlib"
version = "1.3.1"
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
summary = "OAuthlib authentication support for Requests."
dependencies = [
"oauthlib>=3.0.0",
"requests>=2.0.0",
]
[[package]]
name = "streaming-form-data"
version = "1.11.0"
requires_python = ">=3.6"
summary = "Streaming parser for multipart/form-data"
[[package]]
name = "tornado"
version = "6.2"
requires_python = ">= 3.7"
summary = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed."
[[package]]
name = "typing-extensions"
version = "4.4.0"
requires_python = ">=3.7"
summary = "Backported and Experimental Type Hints for Python 3.7+"
[[package]]
name = "urllib3"
version = "1.26.14"
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"
summary = "HTTP library with thread-safe connection pooling, file post, and more."
[[package]]
name = "zeroconf"
version = "0.39.4"
requires_python = ">=3.7"
summary = "Pure Python Multicast DNS Service Discovery Library (Bonjour/Avahi compatible)"
dependencies = [
"async-timeout>=4.0.1",
"ifaddr>=0.1.7",
]
[[package]]
name = "zipp"
version = "3.13.0"
requires_python = ">=3.7"
summary = "Backport of pathlib-compatible object wrapper for zip files"
[metadata]
lock_version = "4.1"
content_hash = "sha256:0e54d8cb135fb11f1588c0d0208221cfcdbae6d54ed3ffa43012ec460bae6b34"
[metadata.files]
"apprise 1.2.1" = [
{url = "https://files.pythonhosted.org/packages/a4/3a/52ec5cf9ed71e3a068a208603e38471b686a59b548dda771f2975166e4a9/apprise-1.2.1-py2.py3-none-any.whl", hash = "sha256:679fb5d6232ec7748eef308bda9fe0f0707fa5e48eab247bfde83c3a024a21d1"},
{url = "https://files.pythonhosted.org/packages/d2/04/4285d864569dde4eece4b0e7bfa447a68e99240898537b10926cb5a53145/apprise-1.2.1.tar.gz", hash = "sha256:67e0c227eecee260000980dbbf8ba1e5eebdbe494f4730808297c9e645c03579"},
]
"async-timeout 4.0.2" = [
{url = "https://files.pythonhosted.org/packages/54/6e/9678f7b2993537452710ffb1750c62d2c26df438aa621ad5fa9d1507a43a/async-timeout-4.0.2.tar.gz", hash = "sha256:2163e1640ddb52b7a8c80d0a67a08587e5d245cc9c553a74a847056bc2976b15"},
{url = "https://files.pythonhosted.org/packages/d6/c1/8991e7c5385b897b8c020cdaad718c5b087a6626d1d11a23e1ea87e325a7/async_timeout-4.0.2-py3-none-any.whl", hash = "sha256:8ca1e4fcf50d07413d66d1a5e416e42cfdf5851c981d679a09851a6853383b3c"},
]
"certifi 2022.12.7" = [
{url = "https://files.pythonhosted.org/packages/37/f7/2b1b0ec44fdc30a3d31dfebe52226be9ddc40cd6c0f34ffc8923ba423b69/certifi-2022.12.7.tar.gz", hash = "sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3"},
{url = "https://files.pythonhosted.org/packages/71/4c/3db2b8021bd6f2f0ceb0e088d6b2d49147671f25832fb17970e9b583d742/certifi-2022.12.7-py3-none-any.whl", hash = "sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18"},
]
"charset-normalizer 3.0.1" = [
{url = "https://files.pythonhosted.org/packages/00/35/830c29e5dab61932224c7a6c89427090164a3e425cf03486ce7a3ce60623/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9d9153257a3f70d5f69edf2325357251ed20f772b12e593f3b3377b5f78e7ef8"},
{url = "https://files.pythonhosted.org/packages/01/ff/9ee4a44e8c32fe96dfc12daa42f29294608a55eadc88f327939327fb20fb/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:72966d1b297c741541ca8cf1223ff262a6febe52481af742036a0b296e35fa5a"},
{url = "https://files.pythonhosted.org/packages/02/49/78b4c1bc8b1b0e0fc66fb31ce30d8302f10a1412ba75de72c57532f0beb0/charset_normalizer-3.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:87701167f2a5c930b403e9756fab1d31d4d4da52856143b609e30a1ce7160f3c"},
{url = "https://files.pythonhosted.org/packages/03/5e/e81488c74e86eef85cf085417ed945da2dcca87ed22d76202680c16bd3c3/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:39049da0ffb96c8cbb65cbf5c5f3ca3168990adf3551bd1dee10c48fce8ae820"},
{url = "https://files.pythonhosted.org/packages/0b/8b/3cf0eff3c8b6734cd4336c23a3141846d579931a31e6476c8091961f1e25/charset_normalizer-3.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:eaa379fcd227ca235d04152ca6704c7cb55564116f8bc52545ff357628e10602"},
{url = "https://files.pythonhosted.org/packages/0e/d3/c5fa421dc69bb77c581ed561f1ec6656109c97731ad1128aa93d8bad3053/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:024e606be3ed92216e2b6952ed859d86b4cfa52cd5bc5f050e7dc28f9b43ec42"},
{url = "https://files.pythonhosted.org/packages/0e/fd/0d099502582af039ef8a8c954d69d7dadbe5f425cb1b24d175eb0034ea9e/charset_normalizer-3.0.1-cp37-cp37m-win32.whl", hash = "sha256:0bf2dae5291758b6f84cf923bfaa285632816007db0330002fa1de38bfcb7154"},
{url = "https://files.pythonhosted.org/packages/0f/45/f462f534dd2853ebbc186ed859661db454665b1dc9ae6c690d982153cda9/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:503e65837c71b875ecdd733877d852adbc465bd82c768a067badd953bf1bc5a3"},
{url = "https://files.pythonhosted.org/packages/12/e5/aa09a1c39c3e444dd223d63e2c816c18ed78d035cff954143b2a539bdc9e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0a590235ccd933d9892c627dec5bc7511ce6ad6c1011fdf5b11363022746c1"},
{url = "https://files.pythonhosted.org/packages/16/bd/671f11f920dfb46de848e9176d84ddb25b3bbdffac6751cbbf691c0b5b17/charset_normalizer-3.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3e45867f1f2ab0711d60c6c71746ac53537f1684baa699f4f668d4c6f6ce8e14"},
{url = "https://files.pythonhosted.org/packages/17/67/4b25c0358a2e812312b551e734d58855d58f47d0e0e9d1573930003910cb/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8eade758719add78ec36dc13201483f8e9b5d940329285edcd5f70c0a9edbd7f"},
{url = "https://files.pythonhosted.org/packages/17/da/fdf8ffc33716c82cae06008159a55a581fa515e8dd02e3395dcad42ff83d/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81d6741ab457d14fdedc215516665050f3822d3e56508921cc7239f8c8e66a58"},
{url = "https://files.pythonhosted.org/packages/20/a2/16b2cbf5f73bdd10624b94647b85c008ba25059792a5c7b4fdb8358bceeb/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e696f0dd336161fca9adbb846875d40752e6eba585843c768935ba5c9960722b"},
{url = "https://files.pythonhosted.org/packages/25/19/298089cef2eb82fd3810d982aa239d4226594f99e1fe78494cb9b47b03c9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:0f438ae3532723fb6ead77e7c604be7c8374094ef4ee2c5e03a3a17f1fca256c"},
{url = "https://files.pythonhosted.org/packages/25/b5/f477e419b06e49f3bae446cbdc1fd71d2599be8b12b4d45c641c5a4495b1/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:911d8a40b2bef5b8bbae2e36a0b103f142ac53557ab421dc16ac4aafee6f53dc"},
{url = "https://files.pythonhosted.org/packages/27/b1/8dfcfa5d9978b845466cd41973b3d714eba3926fcb50f6fcddd45cfb75a2/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:083c8d17153ecb403e5e1eb76a7ef4babfc2c48d58899c98fcaa04833e7a2f9a"},
{url = "https://files.pythonhosted.org/packages/2d/02/0f875eb6a1cf347bd3a6098f458f79796aafa3b51090fd7b2784736dc67d/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:44ba614de5361b3e5278e1241fda3dc1838deed864b50a10d7ce92983797fa76"},
{url = "https://files.pythonhosted.org/packages/2e/7b/5053a4a46fac017fd2aea3dc9abdd9983fd4cef153b6eb6aedcb0d7cb6e3/charset_normalizer-3.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:9ab77acb98eba3fd2a85cd160851816bfce6871d944d885febf012713f06659c"},
{url = "https://files.pythonhosted.org/packages/31/06/f6330ee70c041a032ee1a5d32785d69748cfa41f64b6d327cc08cae51de9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ab5de034a886f616a5668aa5d098af2b5385ed70142090e2a31bcbd0af0fdb3d"},
{url = "https://files.pythonhosted.org/packages/31/af/67b7653a35dbd56f6bb9ff54652a551eae8420d1d0545f0042c5bdb15fb0/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f6f45710b4459401609ebebdbcfb34515da4fc2aa886f95107f556ac69a9147e"},
{url = "https://files.pythonhosted.org/packages/35/86/d85885ed7ac236a297b0b8beab5f0703fc0516f803ddf7b1910f255b83f3/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:7eb33a30d75562222b64f569c642ff3dc6689e09adda43a082208397f016c39a"},
{url = "https://files.pythonhosted.org/packages/37/00/ca188e0a2b3cd3184cdd2521b8765cf579327d128caa8aedc3dc7614020a/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0298eafff88c99982a4cf66ba2efa1128e4ddaca0b05eec4c456bbc7db691d8d"},
{url = "https://files.pythonhosted.org/packages/37/60/7a01f3a129d1af1f26ab2c56aae89a72dbf33fd46a467c1aa994ec62b90b/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8af03d2e37866d023ad0ddea594edefc31e827fee64f8de5611a1dbc373174"},
{url = "https://files.pythonhosted.org/packages/3a/91/a233f06d33dc3ac90a9991d238fbc68c59615d9f71be1801e14ac4e42d7f/charset_normalizer-3.0.1-cp38-cp38-win32.whl", hash = "sha256:4457ea6774b5611f4bed5eaa5df55f70abde42364d498c5134b7ef4c6958e20e"},
{url = "https://files.pythonhosted.org/packages/46/69/9f42514a9f58c602ab89a2af89081a475dccd959f9bc01ba7e61372d31bd/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c95a03c79bbe30eec3ec2b7f076074f4281526724c8685a42872974ef4d36b72"},
{url = "https://files.pythonhosted.org/packages/55/2b/35619e03725bfa4af4a902e1996c9ee8052d6bce005ff79c9bd988820cb4/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:31a9ddf4718d10ae04d9b18801bd776693487cbb57d74cc3458a7673f6f34639"},
{url = "https://files.pythonhosted.org/packages/56/5d/275fb120957dfe5a2262d04f28bc742fd4bcc2bd270d19bb8757e09737ef/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9cf4e8ad252f7c38dd1f676b46514f92dc0ebeb0db5552f5f403509705e24753"},
{url = "https://files.pythonhosted.org/packages/5a/d8/9e76846e70e729de85ecc6af21edc584a2adfef202dc5f5ae00a02622e3d/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:11b53acf2411c3b09e6af37e4b9005cba376c872503c8f28218c7243582df45d"},
{url = "https://files.pythonhosted.org/packages/5b/e7/5527effca09d873e07e128d3daac7c531203b5105cb4e2956c2b7a8cc41c/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:109487860ef6a328f3eec66f2bf78b0b72400280d8f8ea05f69c51644ba6521a"},
{url = "https://files.pythonhosted.org/packages/67/c6/cf4e8a8f41201284bdf200f764b29a87f6f7d22fe3c9eddab602af489acc/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:cd6056167405314a4dc3c173943f11249fa0f1b204f8b51ed4bde1a9cd1834dc"},
{url = "https://files.pythonhosted.org/packages/68/2b/02e9d6a98ddb73fa238d559a9edcc30b247b8dc4ee848b6184c936e99dc0/charset_normalizer-3.0.1-py3-none-any.whl", hash = "sha256:7e189e2e1d3ed2f4aebabd2d5b0f931e883676e51c7624826e0a4e5fe8a0bf24"},
{url = "https://files.pythonhosted.org/packages/6a/ab/3a00ecbddabe25132c20c1bd45e6f90c537b5f7a0b5bcaba094c4922928c/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8499ca8f4502af841f68135133d8258f7b32a53a1d594aa98cc52013fff55678"},
{url = "https://files.pythonhosted.org/packages/6e/a3/997ff79260f76210b1d73463b9081ae7edbf16ff3d611b67f5e72c685cab/charset_normalizer-3.0.1-cp39-cp39-win32.whl", hash = "sha256:39cf9ed17fe3b1bc81f33c9ceb6ce67683ee7526e65fde1447c772afc54a1bb8"},
{url = "https://files.pythonhosted.org/packages/6e/d7/1d4035fcbf7d0f2e89588a142628355d8d1cd652a227acefb9ec85908cd4/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:772b87914ff1152b92a197ef4ea40efe27a378606c39446ded52c8f80f79702e"},
{url = "https://files.pythonhosted.org/packages/71/67/79be03bf7ab4198d994c2e8da869ca354487bfa25656b95cf289cf6338a2/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:16a8663d6e281208d78806dbe14ee9903715361cf81f6d4309944e4d1e59ac5b"},
{url = "https://files.pythonhosted.org/packages/80/54/183163f9910936e57a60ee618f4f5cc91c2f8333ee2d4ebc6c50f6c8684d/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4a8fcf28c05c1f6d7e177a9a46a1c52798bfe2ad80681d275b10dcf317deaf0b"},
{url = "https://files.pythonhosted.org/packages/82/49/ab81421d5aa25bc8535896a017c93204cb4051f2a4e72b1ad8f3b594e072/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:761e8904c07ad053d285670f36dd94e1b6ab7f16ce62b9805c475b7aa1cffde6"},
{url = "https://files.pythonhosted.org/packages/84/0e/5965dd90991e4f2588718b865115a78c8b040193ac3676f757b7fb6af9d0/charset_normalizer-3.0.1-cp311-cp311-win32.whl", hash = "sha256:71140351489970dfe5e60fc621ada3e0f41104a5eddaca47a7acb3c1b851d6d3"},
{url = "https://files.pythonhosted.org/packages/84/ff/78a4942ef1ea4d1c464cc9a132122b36c5390c5cf6301ed0f9e3e6e24bd9/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8ac7b6a045b814cf0c47f3623d21ebd88b3e8cf216a14790b455ea7ff0135d18"},
{url = "https://files.pythonhosted.org/packages/86/eb/31c9025b4ed7eddd930c5f2ac269efb953de33140608c7539675d74a2081/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:5995f0164fa7df59db4746112fec3f49c461dd6b31b841873443bdb077c13cfc"},
{url = "https://files.pythonhosted.org/packages/87/5d/0ebaee2249a04fd20bb4baeb9ea2c29dee17317175d9d67b4f5f34cf048d/charset_normalizer-3.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:e62164b50f84e20601c1ff8eb55620d2ad25fb81b59e3cd776a1902527a788af"},
{url = "https://files.pythonhosted.org/packages/89/87/c237a299a658b35d19fd531eeb8247480627fc2fb4b7a471334b48850f45/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:f9d0c5c045a3ca9bedfc35dca8526798eb91a07aa7a2c0fee134c6c6f321cbd7"},
{url = "https://files.pythonhosted.org/packages/8f/e2/73ea48d2608f71a879588b607e093d550b8eaa177eb31bbdf1c01e515818/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:f5057856d21e7586765171eac8b9fc3f7d44ef39425f85dbcccb13b3ebea806c"},
{url = "https://files.pythonhosted.org/packages/90/2c/bb5e4f7e2e9871793b5c0fb5c6c4056458a148a05143143320f2d4a410a9/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:59e5686dd847347e55dffcc191a96622f016bc0ad89105e24c14e0d6305acbc6"},
{url = "https://files.pythonhosted.org/packages/90/59/941e2e5ae6828a688c6437ad16e026eb3606d0cfdd13ea5c9090980f3ffd/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a8d0fc946c784ff7f7c3742310cc8a57c5c6dc31631269876a88b809dbeff3d3"},
{url = "https://files.pythonhosted.org/packages/92/00/b8dc8dd725297b05f1ab4929c9d7e879f31746131534221c5c8948bc7563/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:12db3b2c533c23ab812c2b25934f60383361f8a376ae272665f8e48b88e8e1c6"},
{url = "https://files.pythonhosted.org/packages/93/d1/569445a704414e150f198737c245ab96b40d28d5b68045a62c414a5157de/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:02a51034802cbf38db3f89c66fb5d2ec57e6fe7ef2f4a44d070a593c3688667b"},
{url = "https://files.pythonhosted.org/packages/96/d7/1675d9089a1f4677df5eb29c3f8b064aa1e70c1251a0a8a127803158942d/charset-normalizer-3.0.1.tar.gz", hash = "sha256:ebea339af930f8ca5d7a699b921106c6e29c617fe9606fa7baa043c1cdae326f"},
{url = "https://files.pythonhosted.org/packages/97/f9/366db2d2cf69d641159d6448b813ac9b1b5f9807a46fde6c50b36c1387f8/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:93ad6d87ac18e2a90b0fe89df7c65263b9a99a0eb98f0a3d2e079f12a0735837"},
{url = "https://files.pythonhosted.org/packages/98/e4/d4685870fda1cc7c5e29899ec329500460418e54f4f5df76ee520e30689a/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c512accbd6ff0270939b9ac214b84fb5ada5f0409c44298361b2f5e13f9aed9e"},
{url = "https://files.pythonhosted.org/packages/98/f4/5ca33ee1e0b3412cbd13eae230321a9fe819acf1a99ad6482420fb97cc6b/charset_normalizer-3.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:601f36512f9e28f029d9481bdaf8e89e5148ac5d89cffd3b05cd533eeb423b59"},
{url = "https://files.pythonhosted.org/packages/99/24/eb846dc9a797da58e6e5b3b5a71d3ff17264de3f424fb29aaa5d27173b55/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3b590df687e3c5ee0deef9fc8c547d81986d9a1b56073d82de008744452d6541"},
{url = "https://files.pythonhosted.org/packages/9a/bf/c9fa15ccf216a69aaaa735c961d7fac2a2801a1b01023fe05d194bf076b4/charset_normalizer-3.0.1-cp36-cp36m-win32.whl", hash = "sha256:95dea361dd73757c6f1c0a1480ac499952c16ac83f7f5f4f84f0658a01b8ef41"},
{url = "https://files.pythonhosted.org/packages/9c/42/c1ebc736c57459aab28bfb8aa28c6a047796f2ea46050a3b129b4920dbe4/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4b0d02d7102dd0f997580b51edc4cebcf2ab6397a7edf89f1c73b586c614272c"},
{url = "https://files.pythonhosted.org/packages/9c/94/1725fc3e0dbe8918a4ec6dd317ec1ef388e701bdfb5053e1f34f5c6d5a8e/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df2c707231459e8a4028eabcd3cfc827befd635b3ef72eada84ab13b52e1574d"},
{url = "https://files.pythonhosted.org/packages/9f/5a/9dc8932d1e5f8eeaa502e3c3fce91c86be20c04eb3ec202d2b7d74b567e5/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2edb64ee7bf1ed524a1da60cdcd2e1f6e2b4f66ef7c077680739f1641f62f555"},
{url = "https://files.pythonhosted.org/packages/a0/98/7b0d3a853af59e092cdd77c7e1c67ca92fd6acc126285240dbb552b4162f/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:74292fc76c905c0ef095fe11e188a32ebd03bc38f3f3e9bcb85e4e6db177b7ea"},
{url = "https://files.pythonhosted.org/packages/a2/93/0b1aa4dbc0ae2aa2e1b2e6d037ab8984dc09912d6b26d63ced14da07e3a7/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a16418ecf1329f71df119e8a65f3aa68004a3f9383821edcb20f0702934d8087"},
{url = "https://files.pythonhosted.org/packages/a2/a7/adc963ad8f8fddadd6be088e636972705ec9d1d92d1b45e6119eb02b7e9e/charset_normalizer-3.0.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:358a7c4cb8ba9b46c453b1dd8d9e431452d5249072e4f56cfda3149f6ab1405e"},
{url = "https://files.pythonhosted.org/packages/a3/09/a837b27b122e710dfad15b0b5df04cd0623c8d8d3382e4298f50798fb84a/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:2e396d70bc4ef5325b72b593a72c8979999aa52fb8bcf03f701c1b03e1166918"},
{url = "https://files.pythonhosted.org/packages/a3/4b/f565c852163312a0991c30598f403fd06796a12e408d7839cc46ca8d7f4a/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62595ab75873d50d57323a91dd03e6966eb79c41fa834b7a1661ed043b2d404d"},
{url = "https://files.pythonhosted.org/packages/aa/a4/2d6255d4db5d4558a92458fd8dacddfdda2fb4ad9c0a87db6f6034aded34/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:f97e83fa6c25693c7a35de154681fcc257c1c41b38beb0304b9c4d2d9e164479"},
{url = "https://files.pythonhosted.org/packages/af/63/2c00ff4e657fb9bb76306ffbc7878fd52067e39716f5e8b0dd5582caf1fa/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70990b9c51340e4044cfc394a81f614f3f90d41397104d226f21e66de668730d"},
{url = "https://files.pythonhosted.org/packages/b2/4c/9a4f30042bfee22d34d80daf75f51817cdd23180d718e0160aab235c4faf/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:88600c72ef7587fe1708fd242b385b6ed4b8904976d5da0893e31df8b3480cb6"},
{url = "https://files.pythonhosted.org/packages/b5/1a/932d86fde86bb0d2992c74552c9a422883fe0890132bbc9a5e2211f03318/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00d3ffdaafe92a5dc603cb9bd5111aaa36dfa187c8285c543be562e61b755f6b"},
{url = "https://files.pythonhosted.org/packages/b6/c2/da108d835354b49aa5c738906e9b6a197b071bc5d77d223f6cd98119172a/charset_normalizer-3.0.1-cp310-cp310-win32.whl", hash = "sha256:502218f52498a36d6bf5ea77081844017bf7982cdbe521ad85e64cabee1b608b"},
{url = "https://files.pythonhosted.org/packages/c0/4d/6b82099e3f25a9ed87431e2f51156c14f3a9ce8fad73880a3856cd95f1d5/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:14e76c0f23218b8f46c4d87018ca2e441535aed3632ca134b10239dfb6dadd6b"},
{url = "https://files.pythonhosted.org/packages/c1/06/b7b1d3d186e0f288500b8a1161ede6b38a0abbf878c2033d667e815e6bd7/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:292d5e8ba896bbfd6334b096e34bffb56161c81408d6d036a7dfa6929cff8783"},
{url = "https://files.pythonhosted.org/packages/c1/b2/d81606aebeb7e9a33dc877ff3a206c9946f5bb374c99d22d4a28825aa270/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a60332922359f920193b1d4826953c507a877b523b2395ad7bc716ddd386d866"},
{url = "https://files.pythonhosted.org/packages/c4/d4/94f1ea460cce04483d2460efba6fd4d66e6f60ad6fc6075dba13e3501e48/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9cb3032517f1627cc012dbc80a8ec976ae76d93ea2b5feaa9d2a5b8882597579"},
{url = "https://files.pythonhosted.org/packages/c8/a2/8f873138c99423de3b402daf8ccd7a538632c83d0c129444a6a18ef34e03/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c22d3fe05ce11d3671297dc8973267daa0f938b93ec716e12e0f6dee81591dc1"},
{url = "https://files.pythonhosted.org/packages/c9/dd/80a5e8c080b7e1cc2b0ca35f0d6aeedafd7bbd06d25031ac20868b1366d6/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:608862a7bf6957f2333fc54ab4399e405baad0163dc9f8d99cb236816db169d4"},
{url = "https://files.pythonhosted.org/packages/d2/7f/3c8a6db3eda16ce79a01552ec85ac8fd0ea6265976eb4db250a60b7416ab/charset_normalizer-3.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:84c3990934bae40ea69a82034912ffe5a62c60bbf6ec5bc9691419641d7d5c9a"},
{url = "https://files.pythonhosted.org/packages/d3/5b/4031145fcfb9ceaf49dad2fbf9a44e062eb2c08aff36f71d8aafbecf4567/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ff6f3db31555657f3163b15a6b7c6938d08df7adbfc9dd13d9d19edad678f1e8"},
{url = "https://files.pythonhosted.org/packages/d9/7a/60d45c9453212b30eebbf8b5cddbdef330eebddfcf335bce7920c43fb72e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79909e27e8e4fcc9db4addea88aa63f6423ebb171db091fb4373e3312cb6d603"},
{url = "https://files.pythonhosted.org/packages/dc/ff/2c7655d83b1d6d6a0e132d50d54131fcb8da763b417ccc6c4a506aa0e08c/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2ac1b08635a8cd4e0cbeaf6f5e922085908d48eb05d44c5ae9eabab148512ca"},
{url = "https://files.pythonhosted.org/packages/df/2f/4806e155191f75e720aca98a969581c6b2676f0379dd315c34c388bbf8b5/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cadaeaba78750d58d3cc6ac4d1fd867da6fc73c88156b7a3212a3cd4819d679d"},
{url = "https://files.pythonhosted.org/packages/df/c5/dd3a17a615775d0ffc3e12b0e47833d8b7e0a4871431dad87a3f92382a19/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c7fe7afa480e3e82eed58e0ca89f751cd14d767638e2550c77a92a9e749c317"},
{url = "https://files.pythonhosted.org/packages/e1/7f/64b51f144fa9e74da63fa690d9563eae627f4df6cc6ae5185a781e1912e5/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c75ffc45f25324e68ab238cb4b5c0a38cd1c3d7f1fb1f72b5541de469e2247db"},
{url = "https://files.pythonhosted.org/packages/e3/96/8cdbce165c96cce5f2c9c7748f7ed8e0cf0c5d03e213bbc90b7c3e918bf5/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ae1de54a77dc0d6d5fcf623290af4266412a7c4be0b1ff7444394f03f5c54e3"},
{url = "https://files.pythonhosted.org/packages/e7/0d/5eaceb5abfc000cca204af9f50e9839462dc0bb1c4e0f4b14ed370e3febd/charset_normalizer-3.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:0a11e971ed097d24c534c037d298ad32c6ce81a45736d31e0ff0ad37ab437d59"},
{url = "https://files.pythonhosted.org/packages/e8/80/141f6af05332cbb811ab469f64deb1e1d4cc9e8b0c003aa8a38d689ce84a/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:37f8febc8ec50c14f3ec9637505f28e58d4f66752207ea177c1d67df25da5aed"},
{url = "https://files.pythonhosted.org/packages/f0/78/30d853a3073c866b47abede6d86b5532aa99ac67a95e86077d20be1ce481/charset_normalizer-3.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:db72b07027db150f468fbada4d85b3b2729a3db39178abf5c543b784c1254539"},
{url = "https://files.pythonhosted.org/packages/f1/14/ed5990189a6a25ae9f8d63e74cd0336189f9ad7e51f066ba2f6cb73e8126/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4c39b0e3eac288fedc2b43055cfc2ca7a60362d0e5e87a637beac5d801ef478"},
{url = "https://files.pythonhosted.org/packages/f1/ff/9a1c65d8c44958f45ae40cd558ab63bd499a35198a2014e13c0887c07ed1/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:a152f5f33d64a6be73f1d30c9cc82dfc73cec6477ec268e7c6e4c7d23c2d2291"},
{url = "https://files.pythonhosted.org/packages/f5/84/cac681144a28114bd9e40d3cdbfd961c14ecc2b56f1baec2094afd6744c7/charset_normalizer-3.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3fc1c4a2ffd64890aebdb3f97e1278b0cc72579a08ca4de8cd2c04799a3a22be"},
{url = "https://files.pythonhosted.org/packages/f5/ec/a9bed59079bd0267d34ada58a4048c96a59b3621e7f586ea85840d41831d/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:356541bf4381fa35856dafa6a965916e54bed415ad8a24ee6de6e37deccf2786"},
{url = "https://files.pythonhosted.org/packages/fc/64/443267b7824283b3e0e33cee4240c079939a970c2c9a5a3164fc988d690b/charset_normalizer-3.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:2c03cc56021a4bd59be889c2b9257dae13bf55041a3372d3295416f86b295fb5"},
]
"click 8.1.3" = [
{url = "https://files.pythonhosted.org/packages/59/87/84326af34517fca8c58418d148f2403df25303e02736832403587318e9e8/click-8.1.3.tar.gz", hash = "sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e"},
{url = "https://files.pythonhosted.org/packages/c2/f1/df59e28c642d583f7dacffb1e0965d0e00b218e0186d7858ac5233dce840/click-8.1.3-py3-none-any.whl", hash = "sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48"},
]
"colorama 0.4.6" = [
{url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
"dbus-next 0.2.3" = [
{url = "https://files.pythonhosted.org/packages/ce/45/6a40fbe886d60a8c26f480e7d12535502b5ba123814b3b9a0b002ebca198/dbus_next-0.2.3.tar.gz", hash = "sha256:f4eae26909332ada528c0a3549dda8d4f088f9b365153952a408e28023a626a5"},
{url = "https://files.pythonhosted.org/packages/d2/fc/c0a3f4c4eaa5a22fbef91713474666e13d0ea2a69c84532579490a9f2cc8/dbus_next-0.2.3-py3-none-any.whl", hash = "sha256:58948f9aff9db08316734c0be2a120f6dc502124d9642f55e90ac82ffb16a18b"},
]
"distro 1.8.0" = [
{url = "https://files.pythonhosted.org/packages/4b/89/eaa3a3587ebf8bed93e45aa79be8c2af77d50790d15b53f6dfc85b57f398/distro-1.8.0.tar.gz", hash = "sha256:02e111d1dc6a50abb8eed6bf31c3e48ed8b0830d1ea2a1b78c61765c2513fdd8"},
{url = "https://files.pythonhosted.org/packages/f4/2c/c90a3adaf0ddb70afe193f5ebfb539612af57cffe677c3126be533df3098/distro-1.8.0-py3-none-any.whl", hash = "sha256:99522ca3e365cac527b44bde033f64c6945d90eb9f769703caaec52b09bbd3ff"},
]
"idna 3.4" = [
{url = "https://files.pythonhosted.org/packages/8b/e1/43beb3d38dba6cb420cefa297822eac205a277ab43e5ba5d5c46faf96438/idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"},
{url = "https://files.pythonhosted.org/packages/fc/34/3030de6f1370931b9dbb4dad48f6ab1015ab1d32447850b9fc94e60097be/idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"},
]
"ifaddr 0.2.0" = [
{url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748"},
{url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4"},
]
"importlib-metadata 6.0.0" = [
{url = "https://files.pythonhosted.org/packages/26/a7/9da7d5b23fc98ab3d424ac2c65613d63c1f401efb84ad50f2fa27b2caab4/importlib_metadata-6.0.0-py3-none-any.whl", hash = "sha256:7efb448ec9a5e313a57655d35aa54cd3e01b7e1fbcf72dce1bf06119420f5bad"},
{url = "https://files.pythonhosted.org/packages/90/07/6397ad02d31bddf1841c9ad3ec30a693a3ff208e09c2ef45c9a8a5f85156/importlib_metadata-6.0.0.tar.gz", hash = "sha256:e354bedeb60efa6affdcc8ae121b73544a7aa74156d047311948f6d711cd378d"},
]
"inotify-simple 1.3.5" = [
{url = "https://files.pythonhosted.org/packages/51/41/59ca6011f5463d5e5eefcfed2e7fe470922d3a958b7f3aad95eda208d7d3/inotify_simple-1.3.5.tar.gz", hash = "sha256:8440ffe49c4ae81a8df57c1ae1eb4b6bfa7acb830099bfb3e305b383005cc128"},
]
"jinja2 3.1.2" = [
{url = "https://files.pythonhosted.org/packages/7a/ff/75c28576a1d900e87eb6335b063fab47a8ef3c8b4d88524c4bf78f670cce/Jinja2-3.1.2.tar.gz", hash = "sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852"},
{url = "https://files.pythonhosted.org/packages/bc/c3/f068337a370801f372f2f8f6bad74a5c140f6fda3d9de154052708dd3c65/Jinja2-3.1.2-py3-none-any.whl", hash = "sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61"},
]
"ldap3 2.9.1" = [
{url = "https://files.pythonhosted.org/packages/43/ac/96bd5464e3edbc61595d0d69989f5d9969ae411866427b2500a8e5b812c0/ldap3-2.9.1.tar.gz", hash = "sha256:f3e7fc4718e3f09dda568b57100095e0ce58633bcabbed8667ce3f8fbaa4229f"},
{url = "https://files.pythonhosted.org/packages/4e/f6/71d6ec9f18da0b2201287ce9db6afb1a1f637dedb3f0703409558981c723/ldap3-2.9.1-py2.py3-none-any.whl", hash = "sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70"},
]
"libnacl 1.8.0" = [
{url = "https://files.pythonhosted.org/packages/9b/dd/395854871aa26b2d082d9c583a5ec807e26132029b0a5a935510b6ae515b/libnacl-1.8.0-py2.py3-none-any.whl", hash = "sha256:a2a4721e9d3d65a2630f9f904ab6624bb6f9e57ab0574244f666d1b58cea0f33"},
{url = "https://files.pythonhosted.org/packages/db/ab/1111466244a682121a86cf5360fb7c804e6c21edaf0b439bfd898f4a11fe/libnacl-1.8.0.tar.gz", hash = "sha256:f1037b85ca31fd8b02c43d66f78c2049bc58480e6a395dc9d27e6821b5fe185d"},
]
"lmdb 1.3.0" = [
{url = "https://files.pythonhosted.org/packages/19/78/bf28525ae03487162cee2e013cec3aeced349c3c2a8325a7dbfdcd61e680/lmdb-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:df2724bad7820114a205472994091097d0fa65a3e5fff5a8e688d123fb8c6326"},
{url = "https://files.pythonhosted.org/packages/2b/50/47b7cfe3973f787d2dc47ff3c41aac3dc37d0a10994ccd1129b18b64af68/lmdb-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ddd590e1c7fcb395931aa3782fb89b9db4550ab2d81d006ecd239e0d462bc41"},
{url = "https://files.pythonhosted.org/packages/3c/4e/bf7177e502593ac31a6a9fd05db2d767474483cde8a1702189f9e271ffb3/lmdb-1.3.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:eefb392f6b5cd43aada49258c5a79be11cb2c8cd3fc3e2d9319a1e0b9f906458"},
{url = "https://files.pythonhosted.org/packages/3f/31/fcdaedcbfdee59fc2a5643ced9c5af59ef54b8b11d8b40f3f420719c2b33/lmdb-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:d6a816954d212f40fd15007cd81ab7a6bebb77436d949a6a9ae04af57fc127f3"},
{url = "https://files.pythonhosted.org/packages/4c/e2/fb76e5f8bd60fda8d6672c921fc3f024542720bc0f35fa5e1f541f00c006/lmdb-1.3.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:008243762decf8f6c90430a9bced56290ebbcdb5e877d90e42343bb97033e494"},
{url = "https://files.pythonhosted.org/packages/4d/cf/3230b1c9b0bec406abb85a9332ba5805bdd03a1d24025c6bbcfb8ed71539/lmdb-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:17215a42a4b9814c383deabecb160581e4fb75d00198eef0e3cea54f230ffbea"},
{url = "https://files.pythonhosted.org/packages/50/e7/fb9f704d7db6fe10315ce22d173e2307565b62ee81df34079ca7f23d8b60/lmdb-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:18c69fabdaf04efaf246587739cc1062b3e57c6ef0743f5c418df89e5e7e7b9b"},
{url = "https://files.pythonhosted.org/packages/57/cc/36832bc3e04fa3a4cb61f02db0641b245d94b205ab215b967448ee36e3c9/lmdb-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:4172fba19417d7b29409beca7d73c067b54e5d8ab1fb9b51d7b4c1445d20a167"},
{url = "https://files.pythonhosted.org/packages/5b/f5/a20bb77dced2aadc7bd45cb7a136dc748119d78d405e2bf5746ed1325fc6/lmdb-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65334eafa5d430b18d81ebd5362559a41483c362e1931f6e1b15bab2ecb7d75d"},
{url = "https://files.pythonhosted.org/packages/60/af/f84c4dd2953e757701e2f027bc0637cce7f2784ea47297bd4d5ee98a14c9/lmdb-1.3.0-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:abbc439cd9fe60ffd6197009087ea885ac150017dc85384093b1d376f83f0ec4"},
{url = "https://files.pythonhosted.org/packages/62/66/764b581d5568d3f31340e970d8abc5a1c93cb65d1d0f3dd59f606bff6817/lmdb-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cfa4aa9c67f8aee89b23005e98d1f3f32490b6b905fd1cb604b207cbd5755ab"},
{url = "https://files.pythonhosted.org/packages/62/b1/b53765aafa2d508285718cdc7088332d3093ce36a8c989a224413783bdd8/lmdb-1.3.0-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:fa6439356e591d3249ab0e1778a6f8d8408e993f66dc911914c78208f5310309"},
{url = "https://files.pythonhosted.org/packages/65/01/ee604f15c55d72eb1216ab27eb36ca613a967ab05d6f83b44b7a36d73f29/lmdb-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:6260a526e4ad85b1f374a5ba9475bf369fb07e7728ea6ec57226b02c40d1976b"},
{url = "https://files.pythonhosted.org/packages/79/fb/36d8a180284d8967be737b68ef1ae163f00be8a38c1a77b840de8d6306fb/lmdb-1.3.0-pp27-pypy_73-win_amd64.whl", hash = "sha256:08f4b5129f4683802569b02581142e415c8dcc0ff07605983ec1b07804cecbad"},
{url = "https://files.pythonhosted.org/packages/7d/7d/9f45a8b64b398d0acedcfd5fe0049286b7488bf7d34a6a710520cff26d0c/lmdb-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:7da05d70fcc6561ac6b09e9fb1bf64b7ca294652c64c8a2889273970cee796b9"},
{url = "https://files.pythonhosted.org/packages/90/fd/788b49864b367199fe5ae97d391617b0d520645e65c9903884c10f89be2f/lmdb-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:62ab28e3593bdc318ea2f2fa1574e5fca3b6d1f264686d773ba54a637d4f563b"},
{url = "https://files.pythonhosted.org/packages/97/47/1e73bc4b4879d1be8dfed4d1dcd139d2f8dfd0c6f63ef4ff5e132b8890e9/lmdb-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e568ae0887ae196340947d9800136e90feaed6b86a261ef01f01b2ba65fc8106"},
{url = "https://files.pythonhosted.org/packages/a3/c8/832b2310460d1eeee9d51410dcb4ce41cbe17a9eeb8eba7c4f5eb9cf8beb/lmdb-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:394df860c3f93cfd92b6f4caba785f38208cc9614c18b3803f83a2cc1695042f"},
{url = "https://files.pythonhosted.org/packages/a4/8d/e27d341de15eb9cc3755d38542cc448ced1037e0eb641e38ad66a564ff6a/lmdb-1.3.0-pp27-pypy_73-macosx_10_7_x86_64.whl", hash = "sha256:e6a704b3baced9182836c7f77b769f23856f3a8f62d0282b1bc1feaf81a86712"},
{url = "https://files.pythonhosted.org/packages/aa/4a/a404ce11f448c424994096dc7c8a85c5e317cfaec98afc6f90a814e7c706/lmdb-1.3.0-cp35-cp35m-win_amd64.whl", hash = "sha256:c6adbd6f7f9048e97f31a069e652eb51020a81e80a0ce92dbb9810d21da2409a"},
{url = "https://files.pythonhosted.org/packages/af/ad/092d8863b765ccac995ce799c725d340d81b225e50c950d3cf801dba49ef/lmdb-1.3.0-pp36-pypy36_pp73-win32.whl", hash = "sha256:f291e3f561f58dddf63a92a5a6a4b8af3a0920b6705d35e2f80e52e86ee238a2"},
{url = "https://files.pythonhosted.org/packages/bb/6b/3cec989d03e31f4b7eac453de8ab394df24eb2ee75114b9135f0e2cd9e2a/lmdb-1.3.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:41318717ab5d15ad2d6d263d34fbf614a045210f64b25e59ce734bb2105e421f"},
{url = "https://files.pythonhosted.org/packages/c5/72/109e7264a6441b4d9d0031be67776d9ef5cf69448ebec71d00a877a2babd/lmdb-1.3.0-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:63cb73fe7ce9eb93d992d632c85a0476b4332670d9e6a2802b5062f603b7809f"},
{url = "https://files.pythonhosted.org/packages/d0/5b/8147d8ab13bfa57c5175803fd8796479da27298b828c95aa1d05e4b60c20/lmdb-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d9103aa4908f0bca43c5911ca067d4e3d01f682dff0c0381a1239bd2bd757984"},
{url = "https://files.pythonhosted.org/packages/db/bf/1fa60f5893263ef4d0a74994104650a002d2a970b183608e5b7497836bfc/lmdb-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5a14aca2651c3af6f0d0a6b9168200eea0c8f2d27c40b01a442f33329a6e8dff"},
{url = "https://files.pythonhosted.org/packages/ed/61/41f3c7cbd8a67202ef24fad3375ed936093a0547dc645581dd11c09581b7/lmdb-1.3.0.tar.gz", hash = "sha256:60a11efc21aaf009d06518996360eed346f6000bfc9de05114374230879f992e"},
{url = "https://files.pythonhosted.org/packages/f8/f7/4a889009d678cf7ce4e2349ed48a4f7c97c380018246e4f68b373192da75/lmdb-1.3.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:2df38115dd9428a54d59ae7c712a4c7cce0d6b1d66056de4b1a8c38718066106"},
]
"markdown 3.4.1" = [
{url = "https://files.pythonhosted.org/packages/85/7e/133e943e97a943d2f1d8bae0c5060f8ac50e6691754eb9dbe036b047a9bb/Markdown-3.4.1.tar.gz", hash = "sha256:3b809086bb6efad416156e00a0da66fe47618a5d6918dd688f53f40c8e4cfeff"},
{url = "https://files.pythonhosted.org/packages/86/be/ad281f7a3686b38dd8a307fa33210cdf2130404dfef668a37a4166d737ca/Markdown-3.4.1-py3-none-any.whl", hash = "sha256:08fb8465cffd03d10b9dd34a5c3fea908e20391a2a90b88d66362cb05beed186"},
]
"markupsafe 2.1.2" = [
{url = "https://files.pythonhosted.org/packages/02/2c/18d55e5df6a9ea33709d6c33e08cb2e07d39e20ad05d8c6fbf9c9bcafd54/MarkupSafe-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:835fb5e38fd89328e9c81067fd642b3593c33e1e17e2fdbf77f5676abb14a156"},
{url = "https://files.pythonhosted.org/packages/04/cf/9464c3c41b7cdb8df660cda75676697e7fb49ce1be7691a1162fc88da078/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:085fd3201e7b12809f9e6e9bc1e5c96a368c8523fad5afb02afe3c051ae4afcc"},
{url = "https://files.pythonhosted.org/packages/06/3b/d026c21cd1dbee89f41127e93113dcf5fa85c6660d108847760b59b3a66d/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40dfd3fefbef579ee058f139733ac336312663c6706d1163b82b3003fb1925c4"},
{url = "https://files.pythonhosted.org/packages/0a/88/78cb3d95afebd183d8b04442685ab4c70cfc1138b850ba20e2a07aff2f53/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65608c35bfb8a76763f37036547f7adfd09270fbdbf96608be2bead319728fcd"},
{url = "https://files.pythonhosted.org/packages/0d/15/82b108c697bec4c26c00aed6975b778cf0eac6cbb77598862b10550b7fcc/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2298c859cfc5463f1b64bd55cb3e602528db6fa0f3cfd568d3605c50678f8f03"},
{url = "https://files.pythonhosted.org/packages/19/00/3b8eb0093c885576a1ce7f2263e7b8c01e55b9977433f8246f57cd81b0be/MarkupSafe-2.1.2-cp311-cp311-win32.whl", hash = "sha256:7df70907e00c970c60b9ef2938d894a9381f38e6b9db73c5be35e59d92e06625"},
{url = "https://files.pythonhosted.org/packages/1f/20/76f6337f1e7238a626ab34405ddd634636011b2ff947dcbd8995f16a7776/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1bea30e9bf331f3fef67e0a3877b2288593c98a21ccb2cf29b74c581a4eb3af0"},
{url = "https://files.pythonhosted.org/packages/22/88/9c0cae2f5ada778182f2842b377dd273d6be689953345c10b165478831eb/MarkupSafe-2.1.2-cp39-cp39-win32.whl", hash = "sha256:137678c63c977754abe9086a3ec011e8fd985ab90631145dfb9294ad09c102a7"},
{url = "https://files.pythonhosted.org/packages/29/d2/243e6b860d97c18d848fc2bee2f39d102755a2b04a5ce4d018d839711b46/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:8db032bf0ce9022a8e41a22598eefc802314e81b879ae093f36ce9ddf39ab1ba"},
{url = "https://files.pythonhosted.org/packages/30/3e/0a69a24adb38df83e2f6989c38d68627a5f27181c82ecaa1fd03d1236dca/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ca244fa73f50a800cf8c3ebf7fd93149ec37f5cb9596aa8873ae2c1d23498601"},
{url = "https://files.pythonhosted.org/packages/34/19/64b0abc021b22766e86efee32b0e2af684c4b731ce8ac1d519c791800c13/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:340bea174e9761308703ae988e982005aedf427de816d1afe98147668cc03036"},
{url = "https://files.pythonhosted.org/packages/37/b2/6f4d5cac75ba6fe9f17671304fe339ea45a73c5609b5f5e652aa79c915c8/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:665a36ae6f8f20a4676b53224e33d456a6f5a72657d9c83c2aa00765072f31f7"},
{url = "https://files.pythonhosted.org/packages/39/8d/5c5ce72deb8567ab48a18fbd99dc0af3dd651b6691b8570947e54a28e0f3/MarkupSafe-2.1.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6d6607f98fcf17e534162f0709aaad3ab7a96032723d8ac8750ffe17ae5a0666"},
{url = "https://files.pythonhosted.org/packages/3d/66/2f636ba803fd6eb4cee7b3106ae02538d1e84a7fb7f4f8775c6528a87d31/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:28057e985dace2f478e042eaa15606c7efccb700797660629da387eb289b9323"},
{url = "https://files.pythonhosted.org/packages/41/54/6e88795c64ab5dcda31b06406c062c2740d1a64db18219d4e21fc90928c1/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c0a33bc9f02c2b17c3ea382f91b4db0e6cde90b63b296422a939886a7a80de1c"},
{url = "https://files.pythonhosted.org/packages/46/0c/10ee33673c5e36fa3809cf136971f81d951ca38516188ee11a965d9b2fe9/MarkupSafe-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:0576fe974b40a400449768941d5d0858cc624e3249dfd1e0c33674e5c7ca7aed"},
{url = "https://files.pythonhosted.org/packages/48/cc/d027612e17b56088cfccd2c8e083518995fcb25a7b4f17fc146362a0499d/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f8ffb705ffcf5ddd0e80b65ddf7bed7ee4f5a441ea7d3419e861a12eaf41af58"},
{url = "https://files.pythonhosted.org/packages/4b/34/dc837e5ad9e14634aac4342eb8b12a9be20a4f74f50cc0d765f7aa2fc1e3/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a4abaec6ca3ad8660690236d11bfe28dfd707778e2442b45addd2f086d6ef094"},
{url = "https://files.pythonhosted.org/packages/50/41/1442b693a40eb76d835ca2016e86a01479f17d7fd8288f9830f6790e366a/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b8526c6d437855442cdd3d87eede9c425c4445ea011ca38d937db299382e6fa3"},
{url = "https://files.pythonhosted.org/packages/52/36/b35c577c884ea352fc0c1eaed9ca4946ffc22cc9c3527a70408bfa9e9496/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f"},
{url = "https://files.pythonhosted.org/packages/56/0d/c9818629672a3368b773fa94597d79da77bdacc3186f097bb85023f785f6/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:0b462104ba25f1ac006fdab8b6a01ebbfbce9ed37fd37fd4acd70c67c973e460"},
{url = "https://files.pythonhosted.org/packages/5a/94/d056bf5dbadf7f4b193ee2a132b3d49ffa1602371e3847518b2982045425/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2bfb563d0211ce16b63c7cb9395d2c682a23187f54c3d79bfec33e6705473c6"},
{url = "https://files.pythonhosted.org/packages/5e/f6/8eb8a5692c1986b6e863877b0b8a83628aff14e5fbfaf11d9522b532bd9d/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22152d00bf4a9c7c83960521fc558f55a1adbc0631fbb00a9471e097b19d72e1"},
{url = "https://files.pythonhosted.org/packages/66/21/dadb671aade8eb67ef96e0d8f90b1bd5e8cfb6ad9d8c7fa2c870ec0c257b/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:55f44b440d491028addb3b88f72207d71eeebfb7b5dbf0643f7c023ae1fba619"},
{url = "https://files.pythonhosted.org/packages/76/b5/05ce70a3e31ecebcd3628cd180dc4761293aa496db85170fdc085ed2d79a/MarkupSafe-2.1.2-cp38-cp38-win32.whl", hash = "sha256:50c42830a633fa0cf9e7d27664637532791bfc31c731a87b202d2d8ac40c3ea2"},
{url = "https://files.pythonhosted.org/packages/77/26/af46880038c6eac3832e751298f1965f3a550f38d1e9ddaabd674860076b/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8bca7e26c1dd751236cfb0c6c72d4ad61d986e9a41bbf76cb445f69488b2a2bd"},
{url = "https://files.pythonhosted.org/packages/78/e6/91c9a20a943ea231c59024e181c4c5480097daf132428f2272670974637f/MarkupSafe-2.1.2-cp310-cp310-win32.whl", hash = "sha256:c4a549890a45f57f1ebf99c067a4ad0cb423a05544accaf2b065246827ed9603"},
{url = "https://files.pythonhosted.org/packages/79/e2/b818bf277fa6b01244943498cb2127372c01dde5eff7682837cc72740618/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da25303d91526aac3672ee6d49a2f3db2d9502a4a60b55519feb1a4c7714e07d"},
{url = "https://files.pythonhosted.org/packages/7b/0f/0e99c2f342933c43af69849a6ba63f2eef54e14c6d0e10a26470fb6b40a9/MarkupSafe-2.1.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a6e40afa7f45939ca356f348c8e23048e02cb109ced1eb8420961b2f40fb373a"},
{url = "https://files.pythonhosted.org/packages/7c/e6/454df09f18e0ea34d189b447a9e1a9f66c2aa332b77fd5577ebc7ca14d42/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2"},
{url = "https://files.pythonhosted.org/packages/80/64/ccb65aadd71e7685caa69a885885a673e8748525a243fb26acea37201b44/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f03a532d7dee1bed20bc4884194a16160a2de9ffc6354b3878ec9682bb623c54"},
{url = "https://files.pythonhosted.org/packages/82/70/b3978786c7b576c25d84b009d2a20a11b5300d252fc3ce984e37b932e97c/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2e7821bffe00aa6bd07a23913b7f4e01328c3d5cc0b40b36c0bd81d362faeb65"},
{url = "https://files.pythonhosted.org/packages/82/e3/4efcd74f10a7999783955aec36386f71082e6d7dafcc06b77b9df72b325a/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99625a92da8229df6d44335e6fcc558a5037dd0a760e11d84be2260e6f37002f"},
{url = "https://files.pythonhosted.org/packages/87/a1/d0f05a09c6c1aef89d1eea0ab0ff1ea897d4117d27f1571034a7e3ff515b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf877ab4ed6e302ec1d04952ca358b381a882fbd9d1b07cccbfd61783561f98a"},
{url = "https://files.pythonhosted.org/packages/93/ca/1c3ae0c6a5712d4ba98610cada03781ea0448436b17d1dcd4759115b15a1/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d9d971ec1e79906046aa3ca266de79eac42f1dbf3612a05dc9368125952bd1a1"},
{url = "https://files.pythonhosted.org/packages/93/fa/d72f68f84f8537ee8aa3e0764d1eb11e5e025a5ca90c16e94a40f894c2fc/MarkupSafe-2.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:bb06feb762bade6bf3c8b844462274db0c76acc95c52abe8dbed28ae3d44a147"},
{url = "https://files.pythonhosted.org/packages/95/7e/68018b70268fb4a2a605e2be44ab7b4dd7ce7808adae6c5ef32e34f4b55a/MarkupSafe-2.1.2.tar.gz", hash = "sha256:abcabc8c2b26036d62d4c746381a6f7cf60aafcc653198ad678306986b09450d"},
{url = "https://files.pythonhosted.org/packages/95/88/8c8cce021ac1b1eedde349c6a41f6c256da60babf95e572071361ff3f66b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63ba06c9941e46fa389d389644e2d8225e0e3e5ebcc4ff1ea8506dce646f8c8a"},
{url = "https://files.pythonhosted.org/packages/96/92/a873b4a7fa20c2e30bffe883bb560330f3b6ce03aaf278f75f96d161935b/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:7e007132af78ea9df29495dbf7b5824cb71648d7133cf7848a2a5dd00d36f9ff"},
{url = "https://files.pythonhosted.org/packages/9d/80/8320f182d06a9b289b1a9f266f593feb91d3781c7e104bbe09e0c4c11439/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4cf06cdc1dda95223e9d2d3c58d3b178aa5dacb35ee7e3bbac10e4e1faacb419"},
{url = "https://files.pythonhosted.org/packages/be/18/988e1913a40cc8eb725b1e073eacc130f7803a061577bdc0b9343eb3c696/MarkupSafe-2.1.2-cp37-cp37m-win32.whl", hash = "sha256:7668b52e102d0ed87cb082380a7e2e1e78737ddecdde129acadb0eccc5423859"},
{url = "https://files.pythonhosted.org/packages/c3/e5/42842a44bfd9ba2955c562b1139334a2f64cedb687e8969777fd07de42a9/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f1cd098434e83e656abf198f103a8207a8187c0fc110306691a2e94a78d0abb2"},
{url = "https://files.pythonhosted.org/packages/c7/0e/22d0c8e6ee84414e251bd1bc555b2705af6b3fb99f0ba1ead2a0f51d423b/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22731d79ed2eb25059ae3df1dfc9cb1546691cc41f4e3130fe6bfbc3ecbbecfa"},
{url = "https://files.pythonhosted.org/packages/cf/c1/d7596976a868fe3487212a382cc121358a53dc8e8d85ff2ee2c3d3b40f04/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:9cad97ab29dfc3f0249b483412c85c8ef4766d96cdf9dcf5a1e3caa3f3661cf1"},
{url = "https://files.pythonhosted.org/packages/d1/10/ff89b23d4a24051c4e4f689b79ee06f230d7e9431445e24f5dd9d9a89730/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:a806db027852538d2ad7555b203300173dd1b77ba116de92da9afbc3a3be3eed"},
{url = "https://files.pythonhosted.org/packages/e3/a9/e366665c7eae59c9c9d34b747cd5a3994847719a2304e0c8dec8b604dd98/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2ec4f2d48ae59bbb9d1f9d7efb9236ab81429a764dedca114f5fdabbc3788013"},
{url = "https://files.pythonhosted.org/packages/e6/ff/d2378ca3cb3ac4a37af767b820b0f0bf3f5e9193a6acce0eefc379425c1c/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:608e7073dfa9e38a85d38474c082d4281f4ce276ac0010224eaba11e929dd53a"},
{url = "https://files.pythonhosted.org/packages/e9/c6/2da36728c1310f141395176556500aeedfdea8c2b02a3b72ba61b69280e8/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:a6f2fcca746e8d5910e18782f976489939d54a91f9411c32051b4aab2bd7c513"},
{url = "https://files.pythonhosted.org/packages/ea/60/2400ba59cf2465fa136487ee7299f52121a9d04b2cf8539ad43ad10e70e8/MarkupSafe-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:e55e40ff0cc8cc5c07996915ad367fa47da6b3fc091fdadca7f5403239c5fec3"},
{url = "https://files.pythonhosted.org/packages/f9/aa/ebcd114deab08f892b1d70badda4436dbad1747f9e5b72cffb3de4c7129d/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:7313ce6a199651c4ed9d7e4cfb4aa56fe923b1adf9af3b420ee14e6d9a73df65"},
]
"oauthlib 3.2.2" = [
{url = "https://files.pythonhosted.org/packages/6d/fa/fbf4001037904031639e6bfbfc02badfc7e12f137a8afa254df6c4c8a670/oauthlib-3.2.2.tar.gz", hash = "sha256:9859c40929662bec5d64f34d01c99e093149682a3f38915dc0655d5a633dd918"},
{url = "https://files.pythonhosted.org/packages/7e/80/cab10959dc1faead58dc8384a781dfbf93cb4d33d50988f7a69f1b7c9bbe/oauthlib-3.2.2-py3-none-any.whl", hash = "sha256:8139f29aac13e25d502680e9e19963e83f16838d48a0d71c287fe40e7067fbca"},
]
"paho-mqtt 1.6.1" = [
{url = "https://files.pythonhosted.org/packages/f8/dd/4b75dcba025f8647bc9862ac17299e0d7d12d3beadbf026d8c8d74215c12/paho-mqtt-1.6.1.tar.gz", hash = "sha256:2a8291c81623aec00372b5a85558a372c747cbca8e9934dfe218638b8eefc26f"},
]
"pillow 9.3.0" = [
{url = "https://files.pythonhosted.org/packages/00/73/000575ca7b7635ecd4075e71925b71f2648300d725b6c9a1f969fe2d5a87/Pillow-9.3.0-cp37-cp37m-macosx_10_10_x86_64.whl", hash = "sha256:772a91fc0e03eaf922c63badeca75e91baa80fe2f5f87bdaed4280662aad25c9"},
{url = "https://files.pythonhosted.org/packages/06/2f/c17a2d559009b875f7da804a3a4e0f47baca6df2dfedb29a1df641c51e1a/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:12ce4932caf2ddf3e41d17fc9c02d67126935a44b86df6a206cf0d7161548627"},
{url = "https://files.pythonhosted.org/packages/0d/87/f696d8464c949c5a7ac133c8b7297a4243e0319fd29ae3a90b4ac90f0a5b/Pillow-9.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7db8b751ad307d7cf238f02101e8e36a128a6cb199326e867d1398067381bff4"},
{url = "https://files.pythonhosted.org/packages/15/13/232be66adb8482f0636b3f3e254d9e18d7093bd1848b3610ffaf72717924/Pillow-9.3.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:829f97c8e258593b9daa80638aee3789b7df9da5cf1336035016d76f03b8860c"},
{url = "https://files.pythonhosted.org/packages/16/11/da8d395299ca166aa56d9436e26fe8440e5443471de16ccd9a1d06f5993a/Pillow-9.3.0.tar.gz", hash = "sha256:c935a22a557a560108d780f9a0fc426dd7459940dc54faa49d83249c8d3e760f"},
{url = "https://files.pythonhosted.org/packages/1d/15/054644ecbed79d3af017a56eaabd13bf712b21c3a667b8a67a335174f4b7/Pillow-9.3.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:89dca0ce00a2b49024df6325925555d406b14aa3efc2f752dbb5940c52c56b11"},
{url = "https://files.pythonhosted.org/packages/23/b3/20f97e1bacd02b89953b50b2502be1b10e01d36a0618fb197e4a055e50f4/Pillow-9.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68943d632f1f9e3dce98908e873b3a090f6cba1cbb1b892a9e8d97c938871fbe"},
{url = "https://files.pythonhosted.org/packages/26/d6/9355d59a2ee9406e4d5129ff0ff99835e7f6adb6133815fab2099e1879b5/Pillow-9.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:0b7257127d646ff8676ec8a15520013a698d1fdc48bc2a79ba4e53df792526f2"},
{url = "https://files.pythonhosted.org/packages/2c/3d/36cd1f6c04ab30ab7e6bc8d17a4337fc29fa5b35ebd4c520d916ce7e39e6/Pillow-9.3.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:b03ae6f1a1878233ac620c98f3459f79fd77c7e3c2b20d460284e1fb370557d4"},
{url = "https://files.pythonhosted.org/packages/2c/74/109e3d1fd2847c19c556fe4ce9b3f4aac2147b56c7b5d0924ae9586d2a47/Pillow-9.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9a65733d103311331875c1dca05cb4606997fd33d6acfed695b1232ba1df193"},
{url = "https://files.pythonhosted.org/packages/2e/c8/03495501bb9beabf34979781b14cc625f39cbd8ff5310a93a85e45987590/Pillow-9.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:4390e9ce199fc1951fcfa65795f239a8a4944117b5935a9317fb320e7767b40f"},
{url = "https://files.pythonhosted.org/packages/2f/73/ec6b3e3f6b311cf1468eafc92a890f690a2cacac0cfd0f1bcc2b891d1334/Pillow-9.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af0372acb5d3598f36ec0914deed2a63f6bcdb7b606da04dc19a88d31bf0c05b"},
{url = "https://files.pythonhosted.org/packages/39/5e/585dfbe0eb4660ea3ee082289625f94e402239282458c4bf78ecc84fbb93/Pillow-9.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40e1ce476a7804b0fb74bcfa80b0a2206ea6a882938eaba917f7a0f004b42502"},
{url = "https://files.pythonhosted.org/packages/40/57/c8695a77561a83bd39eba30daf4d894b0b910aad55e2b60f0ef1b1b5205c/Pillow-9.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:9f47eabcd2ded7698106b05c2c338672d16a6f2a485e74481f524e2a23c2794b"},
{url = "https://files.pythonhosted.org/packages/41/e9/7bae68c360de8d1e7e32aeab252c6dc9336c0d779c9ad5e24ce475d523fd/Pillow-9.3.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ab388aaa3f6ce52ac1cb8e122c4bd46657c15905904b3120a6248b5b8b0bc228"},
{url = "https://files.pythonhosted.org/packages/47/b2/6e5fc952713bfee71c5e25e7917b18207b6f445d81746008b14d9c80a91b/Pillow-9.3.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:15c42fb9dea42465dfd902fb0ecf584b8848ceb28b41ee2b58f866411be33f07"},
{url = "https://files.pythonhosted.org/packages/48/92/820b43fcb333fe7f4cf726ed3c0cfcfd062f65b8fd23c0e6972a6107f440/Pillow-9.3.0-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:b59430236b8e58840a0dfb4099a0e8717ffb779c952426a69ae435ca1f57210c"},
{url = "https://files.pythonhosted.org/packages/4b/f9/2fa7d6cce0b9867ec3917878d03d5298d7a88522ed7dadc6cac4642bce8b/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bca31dd6014cb8b0b2db1e46081b0ca7d936f856da3b39744aef499db5d84d02"},
{url = "https://files.pythonhosted.org/packages/4e/8c/84131e85d4ebd600a823fad1707157d55055a7ea80ce6c8c2f6e2de93f2c/Pillow-9.3.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a0a06a052c5f37b4ed81c613a455a81f9a3a69429b4fd7bb913c3fa98abefc20"},
{url = "https://files.pythonhosted.org/packages/56/02/2c8fde18b251c6ce2061b23b4fa04f3e71d386c725a09753bad19649e1b1/Pillow-9.3.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:51e0e543a33ed92db9f5ef69a0356e0b1a7a6b6a71b80df99f1d181ae5875636"},
{url = "https://files.pythonhosted.org/packages/5b/48/1e4437f90c0531c0a8f5c5b1e793e0f234fe8203019de04001213b4fb38e/Pillow-9.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:90fb88843d3902fe7c9586d439d1e8c05258f41da473952aa8b328d8b907498c"},
{url = "https://files.pythonhosted.org/packages/5f/1e/8a26e1ff2064b665f3923a727cb9240919cdcdce303e4800729635aefc40/Pillow-9.3.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0915e734b33a474d76c28e07292f196cdf2a590a0d25bcc06e64e545f2d146c"},
{url = "https://files.pythonhosted.org/packages/5f/71/ad106c6e3a28f7ff81b2e172a05c158181b61de2a6292896355f0e50f46c/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c7025dce65566eb6e89f56c9509d4f628fddcedb131d9465cacd3d8bac337e7e"},
{url = "https://files.pythonhosted.org/packages/6c/a8/3cb2d902c4094b6ad06f069b937c2696fd47c5fc02da107e33470f468534/Pillow-9.3.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:3dd6caf940756101205dffc5367babf288a30043d35f80936f9bfb37f8355b32"},
{url = "https://files.pythonhosted.org/packages/6d/d2/610687610050eb3ce0ebdd0a3f87d4bb3f1637a89f9fe00060a080a167da/Pillow-9.3.0-1-cp37-cp37m-win32.whl", hash = "sha256:e6ea6b856a74d560d9326c0f5895ef8050126acfdc7ca08ad703eb0081e82b74"},
{url = "https://files.pythonhosted.org/packages/6f/64/3acfbffd532ec2e82f69d4f22de9c29197540ae61926f5b7072654281e91/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa4107d1b306cdf8953edde0534562607fe8811b6c4d9a486298ad31de733b2"},
{url = "https://files.pythonhosted.org/packages/77/56/bb8dc927b3c44df0ca938b4a17b08c59ef5e1e7cc06300bddf20d4e2935f/Pillow-9.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:276a5ca930c913f714e372b2591a22c4bd3b81a418c0f6635ba832daec1cbcfc"},
{url = "https://files.pythonhosted.org/packages/78/8c/ae0c7cfb6cae4eb0946b7369258f78e3104c22eeffda45ad6228bc0838f5/Pillow-9.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3033fbe1feb1b59394615a1cafaee85e49d01b51d54de0cbf6aa8e64182518a1"},
{url = "https://files.pythonhosted.org/packages/88/9f/012551c5a9d8b4d0304b66d16119b9c79bac052e0b0bd37de29b64c1bf0c/Pillow-9.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:073adb2ae23431d3b9bcbcff3fe698b62ed47211d0716b067385538a1b0f28b8"},
{url = "https://files.pythonhosted.org/packages/8a/e8/124718316b3f4f9fa24e4b7e915d8e02d58d43a5e3c44fcbceef17d60647/Pillow-9.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b90f7616ea170e92820775ed47e136208e04c967271c9ef615b6fbd08d9af0e3"},
{url = "https://files.pythonhosted.org/packages/a0/6c/6e11abff7f944b51dbeea1bdfe14ad21976858e822ef667fa4eb82ec6f7c/Pillow-9.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:41e0051336807468be450d52b8edd12ac60bebaa97fe10c8b660f116e50b30e4"},
{url = "https://files.pythonhosted.org/packages/a1/81/10f4f9665ce366c7501141c973c755cd5c9ebe577886ebfa7ca3e9a115f0/Pillow-9.3.0-cp38-cp38-win32.whl", hash = "sha256:f1ff2ee69f10f13a9596480335f406dd1f70c3650349e2be67ca3139280cade0"},
{url = "https://files.pythonhosted.org/packages/a7/9e/8acd4d170596fa876b0baaae3542de3b6d0a709b4652ce78285aff59e849/Pillow-9.3.0-cp37-cp37m-win32.whl", hash = "sha256:82409ffe29d70fd733ff3c1025a602abb3e67405d41b9403b00b01debc4c9a29"},
{url = "https://files.pythonhosted.org/packages/ac/0b/cb7ecd88cea2422818057db720966bbb56bbcec3b359f4a5cafdf737d9e5/Pillow-9.3.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9aaa107275d8527e9d6e7670b64aabaaa36e5b6bd71a1015ddd21da0d4e06448"},
{url = "https://files.pythonhosted.org/packages/af/7f/c5f7a35fd7053a4aee79c41fc4b125281745577c6ce3445e57ed8b4eff56/Pillow-9.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e0918e03aa0c72ea56edbb00d4d664294815aa11291a11504a377ea018330d3"},
{url = "https://files.pythonhosted.org/packages/b7/34/7a88f5ec5f26ac68d3d7a158c67c0a610a4e6b6d22c35266d0e715485b09/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:6c738585d7a9961d8c2821a1eb3dcb978d14e238be3d70f0a706f7fa9316946b"},
{url = "https://files.pythonhosted.org/packages/b9/b8/3e2c23766019a9a03ee26ac6b7af9392aba8574806ce10e5074733987240/Pillow-9.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1c7c8ae3864846fc95f4611c78129301e203aaa2af813b703c55d10cc1628535"},
{url = "https://files.pythonhosted.org/packages/bb/0e/83dd785dff8d62b4d663391ac62390ffadfcdfa4bd11959742f90d02127c/Pillow-9.3.0-cp39-cp39-win32.whl", hash = "sha256:bac18ab8d2d1e6b4ce25e3424f709aceef668347db8637c2296bcf41acb7cf48"},
{url = "https://files.pythonhosted.org/packages/bc/28/0bcf18f0c22cd89626ee2e071edbe5736d54f9031fe986ae94389776864b/Pillow-9.3.0-cp310-cp310-win32.whl", hash = "sha256:655a83b0058ba47c7c52e4e2df5ecf484c1b0b0349805896dd350cbc416bdd91"},
{url = "https://files.pythonhosted.org/packages/be/3e/a757fd2fdd5814aa0e9e1e838f79d33e0098e10a2e3afb7acdcb72278290/Pillow-9.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03150abd92771742d4a8cd6f2fa6246d847dcd2e332a18d0c15cc75bf6703040"},
{url = "https://files.pythonhosted.org/packages/c0/47/4023dab2d77ea3f687939770b06e0c191b4a5a20590f158a6e8dbb03e357/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:77ec3e7be99629898c9a6d24a09de089fa5356ee408cdffffe62d67bb75fdd72"},
{url = "https://files.pythonhosted.org/packages/c0/8f/dfa473f3a6241bff91ae8bb905bd0afceb827f37de2917a94b5c4b1112bf/Pillow-9.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:b472b5ea442148d1c3e2209f20f1e0bb0eb556538690fa70b5e1f79fa0ba8dc2"},
{url = "https://files.pythonhosted.org/packages/c1/c3/be8222fce0553e05264bfe66f2cc73483567b961f144acef88753fba9c6c/Pillow-9.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d77adcd56a42d00cc1be30843d3426aa4e660cab4a61021dc84467123f7a00c"},
{url = "https://files.pythonhosted.org/packages/c2/1d/5d0fd887bb790a42a9efb7fe742358f1eae332ee3120a7d4f79ee37358c9/Pillow-9.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:57751894f6618fd4308ed8e0c36c333e2f5469744c34729a27532b3db106ee20"},
{url = "https://files.pythonhosted.org/packages/c8/7c/f5fe5b37b6a8f2218db98f33d2278f2900e0fc4ef019cd4d9e522d6e3206/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae5331c23ce118c53b172fa64a4c037eb83c9165aba3a7ba9ddd3ec9fa64a699"},
{url = "https://files.pythonhosted.org/packages/c9/b8/27c526c45f482450a53c0faab6c0c4baf9cddee0a8f879a8526f7dd8adf0/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:828989c45c245518065a110434246c44a56a8b2b2f6347d1409c787e6e4651ee"},
{url = "https://files.pythonhosted.org/packages/ca/97/9677bf1d97c408779e5940b89675e38a8ebe8bcc9dbae8adfc9e7080a314/Pillow-9.3.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:73bd195e43f3fadecfc50c682f5055ec32ee2c933243cafbfdec69ab1aa87cad"},
{url = "https://files.pythonhosted.org/packages/cf/22/fed65d07e5e7b19cc608754e940a9b101bebe78cb6cd9d764639717848a4/Pillow-9.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:ebf2029c1f464c59b8bdbe5143c79fa2045a581ac53679733d3a91d400ff9efb"},
{url = "https://files.pythonhosted.org/packages/d0/ae/b5e8750a7e745926e2227a43766d905c8c6a0f03739c7aec5aea9e975355/Pillow-9.3.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:871b72c3643e516db4ecf20efe735deb27fe30ca17800e661d769faab45a18d7"},
{url = "https://files.pythonhosted.org/packages/d1/6f/b5e87428a5566563b6d661824c694bbc4b0386aed1c939b9aec47d9ee573/Pillow-9.3.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22b012ea2d065fd163ca096f4e37e47cd8b59cf4b0fd47bfca6abb93df70b34c"},
{url = "https://files.pythonhosted.org/packages/d4/0d/e8f6ed8e2328007020bb242a0443d925f23ee06d059486c5f1308f2a5e26/Pillow-9.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:18498994b29e1cf86d505edcb7edbe814d133d2232d256db8c7a8ceb34d18cef"},
{url = "https://files.pythonhosted.org/packages/d5/31/b026f9f7c87adf8027f51f98f392f6558982485b7202af5f9276492b2141/Pillow-9.3.0-1-cp37-cp37m-win_amd64.whl", hash = "sha256:32a44128c4bdca7f31de5be641187367fe2a450ad83b833ef78910397db491aa"},
{url = "https://files.pythonhosted.org/packages/d5/79/191ea841f818aba4eb9783b9f91a3c16c51deff7326f5a2f47de54959a28/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dbb8e7f2abee51cef77673be97760abff1674ed32847ce04b4af90f610144c7b"},
{url = "https://files.pythonhosted.org/packages/d6/be/996d629efd03aa305472a17183fcdfe2dd8529acea767d0ba2242d90cbfa/Pillow-9.3.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:801ec82e4188e935c7f5e22e006d01611d6b41661bba9fe45b60e7ac1a8f84de"},
{url = "https://files.pythonhosted.org/packages/db/b0/6438c96e80d4cad5b6381ba774018de9d8eae591d65bdfd80e3ad630928a/Pillow-9.3.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:97aabc5c50312afa5e0a2b07c17d4ac5e865b250986f8afe2b02d772567a380c"},
{url = "https://files.pythonhosted.org/packages/dc/20/30e5ea4ecb35b36d9bc4ff4e8edc048e017a8e3d2e087a512b0622bfdde3/Pillow-9.3.0-cp311-cp311-win32.whl", hash = "sha256:3168434d303babf495d4ba58fc22d6604f6e2afb97adc6a423e917dab828939c"},
{url = "https://files.pythonhosted.org/packages/e0/59/74d88751801101259abd695f77c44b97a828b6a4e7981a79a75d2c3379ae/Pillow-9.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:502526a2cbfa431d9fc2a079bdd9061a2397b842bb6bc4239bb176da00993812"},
{url = "https://files.pythonhosted.org/packages/ec/4f/bc65f543b4d774d6c888cb0936a8b91cf7c5fbb25e16f923e332822b279b/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b4012d06c846dc2b80651b120e2cdd787b013deb39c09f407727ba90015c684f"},
{url = "https://files.pythonhosted.org/packages/f1/e4/2f7e4efeb79ab0a2c5ecba320b2e5a3aad7a49cc543407f4c1268ed804bb/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:0b07fffc13f474264c336298d1b4ce01d9c5a011415b79d4ee5527bb69ae6f65"},
{url = "https://files.pythonhosted.org/packages/f7/11/763c3992c3e6d00e9f6de81b0d721306757bb7201155d135a16032460943/Pillow-9.3.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:ad58d27a5b0262c0c19b47d54c5802db9b34d38bbf886665b626aff83c74bacd"},
{url = "https://files.pythonhosted.org/packages/fc/12/32101461796addca02fd14dc4d2b76068a2cbf895002ed668550caf3fcc1/Pillow-9.3.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:be55f8457cd1eac957af0c3f5ece7bc3f033f89b114ef30f710882717670b2a8"},
]
"preprocess-cancellation 0.2.0" = [
{url = "https://files.pythonhosted.org/packages/64/45/8043211de9ecddf6c25fdd743abb168b198a4ee5e417012ec8f10c6ac91f/preprocess_cancellation-0.2.0-py3-none-any.whl", hash = "sha256:936e2d6f95eaf1c0dd8a00d4c9a0663fbb3ea9a6504bde36aa63509e079d9ee7"},
{url = "https://files.pythonhosted.org/packages/96/02/c8bd237196ca3ec99b0757744e591b3d7c64d7269c991bb7ca50008b6f8d/preprocess_cancellation-0.2.0.tar.gz", hash = "sha256:eb68494e35c0a1fe83716f2a14e12b3e1cdedf9458752be1cace00f944d90760"},
]
"pyasn1 0.4.8" = [
{url = "https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl", hash = "sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d"},
{url = "https://files.pythonhosted.org/packages/a4/db/fffec68299e6d7bad3d504147f9094830b704527a7fc098b721d38cc7fa7/pyasn1-0.4.8.tar.gz", hash = "sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba"},
]
"pyserial 3.4" = [
{url = "https://files.pythonhosted.org/packages/0d/e4/2a744dd9e3be04a0c0907414e2a01a7c88bb3915cbe3c8cc06e209f59c30/pyserial-3.4-py2.py3-none-any.whl", hash = "sha256:e0770fadba80c31013896c7e6ef703f72e7834965954a78e71a3049488d4d7d8"},
{url = "https://files.pythonhosted.org/packages/cc/74/11b04703ec416717b247d789103277269d567db575d2fd88f25d9767fe3d/pyserial-3.4.tar.gz", hash = "sha256:6e2d401fdee0eab996cf734e67773a0143b932772ca8b42451440cfed942c627"},
]
"pyserial-asyncio 0.6" = [
{url = "https://files.pythonhosted.org/packages/27/24/c820cf15f87f7b164e83710c1852d4f900d9793961579e5ef64189bc0c10/pyserial_asyncio-0.6-py3-none-any.whl", hash = "sha256:de9337922619421b62b9b1a84048634b3ac520e1d690a674ed246a2af7ce1fc5"},
{url = "https://files.pythonhosted.org/packages/4a/9a/8477699dcbc1882ea51dcff4d3c25aa3f2063ed8f7d7a849fd8f610506b6/pyserial-asyncio-0.6.tar.gz", hash = "sha256:b6032923e05e9d75ec17a5af9a98429c46d2839adfaf80604d52e0faacd7a32f"},
]
"pyyaml 6.0" = [
{url = "https://files.pythonhosted.org/packages/02/25/6ba9f6bb50a3d4fbe22c1a02554dc670682a07c8701d1716d19ddea2c940/PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5"},
{url = "https://files.pythonhosted.org/packages/08/f4/ffa743f860f34a5e8c60abaaa686f82c9ac7a2b50e5a1c3b1eb564d59159/PyYAML-6.0-cp39-cp39-win_amd64.whl", hash = "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c"},
{url = "https://files.pythonhosted.org/packages/0f/93/5f81d1925ce3b531f5ff215376445ec220887cd1c9a8bde23759554dbdfd/PyYAML-6.0-cp310-cp310-win32.whl", hash = "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513"},
{url = "https://files.pythonhosted.org/packages/12/fc/a4d5a7554e0067677823f7265cb3ae22aed8a238560b5133b58cda252dad/PyYAML-6.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0"},
{url = "https://files.pythonhosted.org/packages/21/67/b42191239c5650c9e419c4a08a7a022bbf1abf55b0391c380a72c3af5462/PyYAML-6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803"},
{url = "https://files.pythonhosted.org/packages/2e/b3/13dfd4eeb5e4b2d686b6d1822b40702e991bf3a4194ca5cbcce8d43749db/PyYAML-6.0-cp39-cp39-win32.whl", hash = "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb"},
{url = "https://files.pythonhosted.org/packages/36/2b/61d51a2c4f25ef062ae3f74576b01638bebad5e045f747ff12643df63844/PyYAML-6.0.tar.gz", hash = "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"},
{url = "https://files.pythonhosted.org/packages/44/e5/4fea13230bcebf24b28c0efd774a2dd65a0937a2d39e94a4503438b078ed/PyYAML-6.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53"},
{url = "https://files.pythonhosted.org/packages/4d/7d/c2ab8da648cd2b937de11fb35649b127adab4851cbeaf5fd9b60a2dab0f7/PyYAML-6.0-cp36-cp36m-win32.whl", hash = "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293"},
{url = "https://files.pythonhosted.org/packages/55/e3/507a92589994a5b3c3d7f2a7a066339d6ff61c5c839bae56f7eff03d9c7b/PyYAML-6.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86"},
{url = "https://files.pythonhosted.org/packages/56/8f/e8b49ad21d26111493dc2d5cae4d7efbd0e2e065440665f5023515f87f64/PyYAML-6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:432557aa2c09802be39460360ddffd48156e30721f5e8d917f01d31694216782"},
{url = "https://files.pythonhosted.org/packages/59/00/30e33fcd2a4562cd40c49c7740881009240c5cbbc0e41ca79ca4bba7c24b/PyYAML-6.0-cp311-cp311-win_amd64.whl", hash = "sha256:01b45c0191e6d66c470b6cf1b9531a771a83c1c4208272ead47a3ae4f2f603bf"},
{url = "https://files.pythonhosted.org/packages/5e/f4/7b4bb01873be78fc9fde307f38f62e380b7111862c165372cf094ca2b093/PyYAML-6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc"},
{url = "https://files.pythonhosted.org/packages/63/6b/f5dc7942bac17192f4ef00b2d0cdd1ae45eea453d05c1944c0573debe945/PyYAML-6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34"},
{url = "https://files.pythonhosted.org/packages/67/d4/b95266228a25ef5bd70984c08b4efce2c035a4baa5ccafa827b266e3dc36/PyYAML-6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174"},
{url = "https://files.pythonhosted.org/packages/68/3f/c027422e49433239267c62323fbc6320d6ac8d7d50cf0cb2a376260dad5f/PyYAML-6.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dbad0e9d368bb989f4515da330b88a057617d16b6a8245084f1b05400f24609f"},
{url = "https://files.pythonhosted.org/packages/6c/3d/524c642f3db37e7e7ab8d13a3f8b0c72d04a619abc19100097d987378fc6/PyYAML-6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba"},
{url = "https://files.pythonhosted.org/packages/74/68/3c13deaa496c14a030c431b7b828d6b343f79eb241b4848c7918091a64a2/PyYAML-6.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92"},
{url = "https://files.pythonhosted.org/packages/77/da/e845437ffe0dffae4e7562faf23a4f264d886431c5d2a2816c853288dc8e/PyYAML-6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3"},
{url = "https://files.pythonhosted.org/packages/7f/d9/6a0d14ac8d3b5605dc925d177c1d21ee9f0b7b39287799db1e50d197b2f4/PyYAML-6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa17f5bc4d1b10afd4466fd3a44dc0e245382deca5b3c353d8b757f9e3ecb8d"},
{url = "https://files.pythonhosted.org/packages/81/59/561f7e46916b78f3c4cab8d0c307c81656f11e32c846c0c97fda0019ed76/PyYAML-6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4"},
{url = "https://files.pythonhosted.org/packages/89/26/0bfd7b756b34c68f8fd158b7bc762b6b1705fc1b3cebf4cdbb53fd9ea75b/PyYAML-6.0-cp36-cp36m-win_amd64.whl", hash = "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57"},
{url = "https://files.pythonhosted.org/packages/91/49/d46d7b15cddfa98533e89f3832f391aedf7e31f37b4d4df3a7a7855a7073/PyYAML-6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c"},
{url = "https://files.pythonhosted.org/packages/9d/f6/7e91fbb58c9ee528759aea5892e062cccb426720c5830ddcce92eba00ff1/PyYAML-6.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c"},
{url = "https://files.pythonhosted.org/packages/a4/ba/e508fc780e3c94c12753a54fe8f74de535741a10d33b29a576a9bec03500/PyYAML-6.0-cp38-cp38-win32.whl", hash = "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78"},
{url = "https://files.pythonhosted.org/packages/a4/e6/4d7a01bc0730c8f958a62d6a4c4f3df23b6139ad68c132b168970d84f192/PyYAML-6.0-cp37-cp37m-win32.whl", hash = "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737"},
{url = "https://files.pythonhosted.org/packages/a8/32/1bbe38477fb23f1d83041fefeabf93ef1cd6f0efcf44c221519507315d92/PyYAML-6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f"},
{url = "https://files.pythonhosted.org/packages/a8/5b/c4d674846ea4b07ee239fbf6010bcc427c4e4552ba5655b446e36b9a40a7/PyYAML-6.0-cp38-cp38-win_amd64.whl", hash = "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07"},
{url = "https://files.pythonhosted.org/packages/b3/85/79b9e5b4e8d3c0ac657f4e8617713cca8408f6cdc65d2ee6554217cedff1/PyYAML-6.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4"},
{url = "https://files.pythonhosted.org/packages/b7/09/2f6f4851bbca08642fef087bade095edc3c47f28d1e7bff6b20de5262a77/PyYAML-6.0-cp310-cp310-win_amd64.whl", hash = "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a"},
{url = "https://files.pythonhosted.org/packages/cb/5f/05dd91f5046e2256e35d885f3b8f0f280148568f08e1bf20421887523e9a/PyYAML-6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:81957921f441d50af23654aa6c5e5eaf9b06aba7f0a19c18a538dc7ef291c5a1"},
{url = "https://files.pythonhosted.org/packages/d1/c0/4fe04181b0210ee2647cfbb89ecd10a36eef89f10d8aca6a192c201bbe58/PyYAML-6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d"},
{url = "https://files.pythonhosted.org/packages/d7/42/7ad4b6d67a16229496d4f6e74201bdbebcf4bc1e87d5a70c9297d4961bd2/PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287"},
{url = "https://files.pythonhosted.org/packages/db/4e/74bc723f2d22677387ab90cd9139e62874d14211be7172ed8c9f9a7c81a9/PyYAML-6.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b"},
{url = "https://files.pythonhosted.org/packages/df/75/ee0565bbf65133e5b6ffa154db43544af96ea4c42439e6b58c1e0eb44b4e/PyYAML-6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0"},
{url = "https://files.pythonhosted.org/packages/eb/5f/6e6fe6904e1a9c67bc2ca5629a69e7a5a0b17f079da838bab98a1e548b25/PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9"},
{url = "https://files.pythonhosted.org/packages/ef/ad/b443cce94539e57e1a745a845f95c100ad7b97593d7e104051e43f730ecd/PyYAML-6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b"},
{url = "https://files.pythonhosted.org/packages/f5/6f/b8b4515346af7c33d3b07cd8ca8ea0700ca72e8d7a750b2b87ac0268ca4e/PyYAML-6.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b"},
{url = "https://files.pythonhosted.org/packages/f8/54/799b059314b13e1063473f76e908f44106014d18f54b16c83a16edccd5ec/PyYAML-6.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d4b0ba9512519522b118090257be113b9468d804b19d63c71dbcf4a48fa32358"},
{url = "https://files.pythonhosted.org/packages/fc/48/531ecd926fe0a374346dd811bf1eda59a95583595bb80eadad511f3269b8/PyYAML-6.0-cp311-cp311-win32.whl", hash = "sha256:bfaef573a63ba8923503d27530362590ff4f576c626d86a9fed95822a8255fd7"},
]
"requests 2.28.2" = [
{url = "https://files.pythonhosted.org/packages/9d/ee/391076f5937f0a8cdf5e53b701ffc91753e87b07d66bae4a09aa671897bf/requests-2.28.2.tar.gz", hash = "sha256:98b1b2782e3c6c4904938b84c0eb932721069dfdb9134313beff7c83c2df24bf"},
{url = "https://files.pythonhosted.org/packages/d2/f4/274d1dbe96b41cf4e0efb70cbced278ffd61b5c7bb70338b62af94ccb25b/requests-2.28.2-py3-none-any.whl", hash = "sha256:64299f4909223da747622c030b781c0d7811e359c37124b4bd368fb8c6518baa"},
]
"requests-oauthlib 1.3.1" = [
{url = "https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl", hash = "sha256:2577c501a2fb8d05a304c09d090d6e47c306fef15809d102b327cf8364bddab5"},
{url = "https://files.pythonhosted.org/packages/95/52/531ef197b426646f26b53815a7d2a67cb7a331ef098bb276db26a68ac49f/requests-oauthlib-1.3.1.tar.gz", hash = "sha256:75beac4a47881eeb94d5ea5d6ad31ef88856affe2332b9aafb52c6452ccf0d7a"},
]
"streaming-form-data 1.11.0" = [
{url = "https://files.pythonhosted.org/packages/04/2f/2f35fbb41fc402f379081cf32f78cd750304fcb801b01d1307831225222b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:fe46eff0cb5aebcc752c7ee3258bbeaa6aa9007bad9c32cfbd46d00df5c1f4d4"},
{url = "https://files.pythonhosted.org/packages/08/7f/dcffefffde61a3cdcac981a81ff57164c44b64c92154c69742bdc8a27a7d/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:52fd1ea2a8c0b4ac56b99903214e239f0e8b9266f65c8cae6c00787aaf1f9cfe"},
{url = "https://files.pythonhosted.org/packages/0a/f1/a9f862f8d097371ca464ff723221568010762c55d2cdcc200821048d29e0/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:ab59d14825cb4ed9d96eb17a2f78f5a96935fb4e8e6b98fcae5ce07fcd6e0fa9"},
{url = "https://files.pythonhosted.org/packages/1d/cc/9110eaa9a045274d7ff48a66e9185af64ba42349ab7d9da0828606fa06bc/streaming_form_data-1.11.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9ff76ec968a1c04dcc94fd66fae343b9fc576cb455fdd3f93370dad5fa1d8771"},
{url = "https://files.pythonhosted.org/packages/1f/55/d09ebcc68fc24c15bea4c119247f4da38afbaefc302bfc90f567e3ab8394/streaming_form_data-1.11.0-cp36-cp36m-win_amd64.whl", hash = "sha256:5dfb34b8e147c4f30ada3ab333b517cbc8c273e06a0f464c85f92e70647bbbd6"},
{url = "https://files.pythonhosted.org/packages/2c/6c/a6666cadf14b7bcb27f214a2325b9c72a35a0f3f34fbcda3890e53488468/streaming-form-data-1.11.0.tar.gz", hash = "sha256:202cea84200e8d412dd22b3ae522e1896a8a7d041aae809278b003b64ed1712b"},
{url = "https://files.pythonhosted.org/packages/39/0c/5f68bd2f004a66af88b1509d15e8aab121a83d94b15103eef347a8378953/streaming_form_data-1.11.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:e551dc5604af5b971224c5c82c132ec8d99bc3da627ad6228ff899f1b1043839"},
{url = "https://files.pythonhosted.org/packages/3c/3f/2a637fee6d3ec836a24d3deb0bad343aec76458b24aebf5599d7265e0255/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:5358cc32bf775944d366525c2854620e55548563f40868f01ea4af6f252b682b"},
{url = "https://files.pythonhosted.org/packages/3f/2c/120ddd55d727e63a93a05e5da17a9d54f26570bf6cb5353211a0191bd858/streaming_form_data-1.11.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a780dc298ff4da1d20c9deae02f817c08de59e0094b591627727efe6e94574af"},
{url = "https://files.pythonhosted.org/packages/4b/70/7a372bddb2e413170fe3a2f90a4aef33efd8aa655b7dadf521d19512895e/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:f7bf111cd071853089b3904ec9dd9250959a45e88ea05ce078b2632375597cef"},
{url = "https://files.pythonhosted.org/packages/57/66/82ac7a98357c2062890cd2c2a19d7081ab877808bc49f5e8da779e7c63be/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:1eccecf020053de8bfba7844ac9e0ed2cb1ca2a3d39980aa9077ca3f31048b1f"},
{url = "https://files.pythonhosted.org/packages/63/6f/3df5b7b134c1d3e971a0319b9ffce963269cdab4810cd9977fff9fb22963/streaming_form_data-1.11.0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:27a21a95d9d05448f638c049b2da1406a6d4ac357c6e8bec4268d9a2f99bdd76"},
{url = "https://files.pythonhosted.org/packages/6e/00/c562082e709b96c54956a8631dcf086895a2504f46c25bbc1fa60e1b961b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:1428e0fe38d7d5dea984a772a235955a4f4e6e846d2f377239b7b8a42b2ab455"},
{url = "https://files.pythonhosted.org/packages/89/59/632ec49c341df95597f291eb7e818749287089b7166823b1e5397d1e855a/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:301dba4f0b634d4e7e632172cc9fb6e0db136ce6a12b0f5cf118d25f0aaa484e"},
{url = "https://files.pythonhosted.org/packages/9a/c5/4d6b7a2bc2b01c0f2085db522cb0c2785dd011e5d9f13c8b35c987a79e55/streaming_form_data-1.11.0-cp39-cp39-win_amd64.whl", hash = "sha256:d33096083ae86837b7f8dfd3653b7cf87044d7ffb6b52102114e46a74a3a1164"},
{url = "https://files.pythonhosted.org/packages/a3/64/efed10d21c999c79d87f7b187c861918c80af1e8243ab4f1d3fafcca0625/streaming_form_data-1.11.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:adc810f256214af1dc45b9351cca1f8e7af60fb9de07bb3ab9ba1379770c51f7"},
{url = "https://files.pythonhosted.org/packages/af/d7/da423d9a38e9459089155d8583e32e46ca61f6ae5f429022557603ff721d/streaming_form_data-1.11.0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:1fbdd0df497465524e2010ae1465582663c9fb2a1f933075fddb6710a0cf9f17"},
{url = "https://files.pythonhosted.org/packages/b2/2e/1d6a4ffe8650af67f3dbd9b84d2d369df14edc4559f4afb53c72914a1010/streaming_form_data-1.11.0-cp37-cp37m-win_amd64.whl", hash = "sha256:cf8de78d747e95db780cd18672783735bcb811ea495b8e4546c8fa534829d90d"},
{url = "https://files.pythonhosted.org/packages/bc/f6/804ff40efb9de1f4256f60e3faa507058349bc9086c5adad568692216a28/streaming_form_data-1.11.0-cp38-cp38-win32.whl", hash = "sha256:70321f427e0600c7d5b74fd8f91a4478edb92143bd9fd051dd11a18c1e08a37c"},
{url = "https://files.pythonhosted.org/packages/be/b0/91c341a58ea61c12c56dfc9ab101e495c08632bb74b1e6247e32641aea55/streaming_form_data-1.11.0-cp39-cp39-win32.whl", hash = "sha256:b208c0918cdf2e274d286c78f3f6b1fd5e9c0cf35bc1dc33a60d1c3c4edf0b51"},
{url = "https://files.pythonhosted.org/packages/d0/5b/f7ab5b7357fa274ce76f159d67ca6e52103e626ff9bbc82fc55cfa172888/streaming_form_data-1.11.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:f348e67d55dcb60ce8571647dd0e18aa4205091c9c1d1f1b0ee2816e8f612421"},
{url = "https://files.pythonhosted.org/packages/d3/28/b6cabf9b1e0c50140162bc369ff65d3535cef459f0264822d77b72a80ada/streaming_form_data-1.11.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:b073baa08f349ab4737ebb673e8dc5c4cd19be6c8d18f43262e659d95b290733"},
{url = "https://files.pythonhosted.org/packages/d8/e9/79041e6ed6b2ed56d8928eabaa5943da273dea3caf7b2e628c4a8c8e9a03/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:5bffc52d57f6733c5462b8fb19b4d7ce54c2faea3c7d5b12725b86740be1c7c9"},
{url = "https://files.pythonhosted.org/packages/df/63/c4fc00a6b4808b97f1fc46c2682a5154b81b99d2d3f2f4cd8bc61190426d/streaming_form_data-1.11.0-cp36-cp36m-win32.whl", hash = "sha256:8db536c6387d27b2ce9b89e58269ff79d8da197f1f3c300f53dc130271bb5f78"},
{url = "https://files.pythonhosted.org/packages/e0/4c/99315996886639c3887d5030f172ec14b6ffe5c9fffc4386ffbca95f3eff/streaming_form_data-1.11.0-cp38-cp38-win_amd64.whl", hash = "sha256:406cd5a23eef77f360b549b93fa64a8ee724309063ab1dce528e1c8e397cb56f"},
{url = "https://files.pythonhosted.org/packages/e0/51/09006f1ec2b562e3ca6d6fe82f878d8b2c66cd0ef56ce85d6225b8a6acc6/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:aa07f1c565436319862abb338e3a9ae68855b09fc5ceb83564c34a53af852c52"},
{url = "https://files.pythonhosted.org/packages/e2/91/a1172ef7d998efb97fe9fd5a56f13fad43d56bf7c53c87ec96c379654b53/streaming_form_data-1.11.0-cp37-cp37m-win32.whl", hash = "sha256:267a4921decbd3a800463d72b6a8df362e17cad7825924a5a61e3cbc7bacf96d"},
{url = "https://files.pythonhosted.org/packages/ee/1e/0c7f836410c809d9001c31fb2bf31bdc40a38671fc8e6820021e0f8cd878/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:1d56ac0fb880cb8143cbfd5c67361fc6caa0ab5e9863074555304ad27c1d0e2b"},
{url = "https://files.pythonhosted.org/packages/f0/37/5f4162304049e1a25974de914c9e21543bafd2218b396c2c3a313d575126/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:89a20560924bbbd07fc51f3f7b6710744e8b845028a9af338b6caa9c2611f7bb"},
]
"tornado 6.2" = [
{url = "https://files.pythonhosted.org/packages/11/30/ac70f5c5f03cf1cd0ae8199c80382387a9fe57e8f68853d5c9527c0219e5/tornado-6.2-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b8150f721c101abdef99073bf66d3903e292d851bee51910839831caba341a75"},
{url = "https://files.pythonhosted.org/packages/19/bb/b6c3d1668d2b10ad38a584f3a1ec9737984e274f8b708e09fcbb96427f5c/tornado-6.2-cp37-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3a2f5999215a3a06a4fc218026cd84c61b8b2b40ac5296a6db1f1451ef04c1e"},
{url = "https://files.pythonhosted.org/packages/1c/26/cbfa1103e74a02e09dd53291e419da3ad4c5b948f52aea5800e6671b56e0/tornado-6.2-cp37-abi3-win_amd64.whl", hash = "sha256:e5f923aa6a47e133d1cf87d60700889d7eae68988704e20c75fb2d65677a8e4b"},
{url = "https://files.pythonhosted.org/packages/5c/0c/cbc0a98f7b8ef833bcb13c58d35d09e2c288ae67a35af4c8960b88f99ae9/tornado-6.2-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:87dcafae3e884462f90c90ecc200defe5e580a7fbbb4365eda7c7c1eb809ebc9"},
{url = "https://files.pythonhosted.org/packages/60/08/e630a348b34a9ddd640aed67dafc6f0df425d8ac07d2fa60288f38321c69/tornado-6.2-cp37-abi3-musllinux_1_1_i686.whl", hash = "sha256:6fdfabffd8dfcb6cf887428849d30cf19a3ea34c2c248461e1f7d718ad30b66b"},
{url = "https://files.pythonhosted.org/packages/71/cc/c1342382484d0178a79029109c433e406a60095da1c3605ca966775a70e5/tornado-6.2-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ba09ef14ca9893954244fd872798b4ccb2367c165946ce2dd7376aebdde8e3ac"},
{url = "https://files.pythonhosted.org/packages/cd/a4/761e45cea12b2af076d36240d464b371ab1231272948cdc49b7d81855c5c/tornado-6.2-cp37-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:5f8c52d219d4995388119af7ccaa0bcec289535747620116a58d830e7c25d8a8"},
{url = "https://files.pythonhosted.org/packages/ec/01/93e63530851ba8ef9685f1a9b91e324b28d28323a6b67400114ea65c5110/tornado-6.2-cp37-abi3-win32.whl", hash = "sha256:5c87076709343557ef8032934ce5f637dbb552efa7b21d08e89ae7619ed0eb23"},
{url = "https://files.pythonhosted.org/packages/f3/9e/225a41452f2d9418d89be5e32cf824c84fe1e639d350d6e8d49db5b7f73a/tornado-6.2.tar.gz", hash = "sha256:9b630419bde84ec666bfd7ea0a4cb2a8a651c2d5cccdbdd1972a0c859dfc3c13"},
{url = "https://files.pythonhosted.org/packages/f9/51/6f63a166d9a3077be100cbb13dcbce434e5654daaaa7003b0a045b9f6edf/tornado-6.2-cp37-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:1d54d13ab8414ed44de07efecb97d4ef7c39f7438cf5e976ccd356bebb1b5fca"},
{url = "https://files.pythonhosted.org/packages/fb/bd/074254a55bfc82d7a1886abbd803600ef01cbd76ee66bc30307b2724130b/tornado-6.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:20f638fd8cc85f3cbae3c732326e96addff0a15e22d80f049e00121651e82e72"},
]
"typing-extensions 4.4.0" = [
{url = "https://files.pythonhosted.org/packages/0b/8e/f1a0a5a76cfef77e1eb6004cb49e5f8d72634da638420b9ea492ce8305e8/typing_extensions-4.4.0-py3-none-any.whl", hash = "sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e"},
{url = "https://files.pythonhosted.org/packages/e3/a7/8f4e456ef0adac43f452efc2d0e4b242ab831297f1bac60ac815d37eb9cf/typing_extensions-4.4.0.tar.gz", hash = "sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa"},
]
"urllib3 1.26.14" = [
{url = "https://files.pythonhosted.org/packages/c5/52/fe421fb7364aa738b3506a2d99e4f3a56e079c0a798e9f4fa5e14c60922f/urllib3-1.26.14.tar.gz", hash = "sha256:076907bf8fd355cde77728471316625a4d2f7e713c125f51953bb5b3eecf4f72"},
{url = "https://files.pythonhosted.org/packages/fe/ca/466766e20b767ddb9b951202542310cba37ea5f2d792dae7589f1741af58/urllib3-1.26.14-py2.py3-none-any.whl", hash = "sha256:75edcdc2f7d85b137124a6c3c9fc3933cdeaa12ecb9a6a959f22797a0feca7e1"},
]
"zeroconf 0.39.4" = [
{url = "https://files.pythonhosted.org/packages/3f/ff/a8d7faaa3573b6e4c775cacbf911a0afbcb4928ce71b3de43119227a396a/zeroconf-0.39.4-py3-none-any.whl", hash = "sha256:d60eae9e9c99d1a168ce9ff9de7e7398c23754a0c2004ded230f8d529c5260a0"},
{url = "https://files.pythonhosted.org/packages/f5/4f/c47cea73d7ae5467b63de3999d7207fd5b14d70cb2f35ce81c4ab7d7a52e/zeroconf-0.39.4.tar.gz", hash = "sha256:701e4d697f89fe952aa9c13a512ed6bf472dcf4f0a6d275e71085604b3882295"},
]
"zipp 3.13.0" = [
{url = "https://files.pythonhosted.org/packages/95/7b/1608a7344743f54a8c072d64d2a279934fd204d6d015278b0a0ed4ce104b/zipp-3.13.0-py3-none-any.whl", hash = "sha256:e8b2a36ea17df80ffe9e2c4fda3f693c3dad6df1697d3cd3af232db680950b0b"},
{url = "https://files.pythonhosted.org/packages/d1/2f/ba544a8a6ad5ad9dcec1b00f536bb9fb078f5f50d1a1408876de18a9151b/zipp-3.13.0.tar.gz", hash = "sha256:23f70e964bc11a34cef175bc90ba2914e1e4545ea1e3e2f67c079671883f9cb6"},
]
+64
View File
@@ -0,0 +1,64 @@
[project]
name = "moonraker"
dynamic = ["version"]
description = "API Server for Klipper"
authors = [
{name = "Eric Callahan"},
{email = "arksine.code@gmail.com"},
]
dependencies = [
"tornado==6.2.0",
"pyserial==3.4",
"pyserial-asyncio==0.6",
"pillow==9.3.0",
"lmdb==1.3.0",
"streaming-form-data==1.11.0",
"distro==1.8.0",
"inotify-simple==1.3.5",
"libnacl==1.8.0",
"paho-mqtt==1.6.1",
"zeroconf==0.39.4",
"preprocess-cancellation==0.2.0",
"jinja2==3.1.2",
"dbus-next==0.2.3",
"apprise==1.2.1",
"ldap3==2.9.1"
]
requires-python = ">=3.7"
readme = "README.md"
license = {text = "GPL-3.0-only"}
keywords = ["klipper", "3D printing", "server", "moonraker"]
classifiers = [
"Development Status :: 4 - Beta",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
]
[project.urls]
homepage = "https://github.com/Arksine/moonraker"
repository = "https://github.com/Arksine/moonraker"
documentation = "https://moonraker.readthedocs.io"
changelog = "https://moonraker.readthedocs.io/en/latest/changelog/"
[tool.pdm.version]
source = "scm"
write_to = "moonraker/__version__.py"
write_template = "__version__ = '{}'\n"
[tool.pdm.build]
excludes = ["./**/.git", "moonraker/moonraker.py"]
includes = ["moonraker"]
editable-backend = "path"
custom-hook = "scripts/pdm_build_dist.py"
[project.scripts]
moonraker = "moonraker.server:main"
[build-system]
requires = ["pdm-backend>=2.0.2"]
build-backend = "pdm.backend"
+13
View File
@@ -0,0 +1,13 @@
[pytest]
minversion = 7.0
pythonpath = moonraker scripts
testpaths = tests
required_plugins =
pytest-asyncio>=0.17.2
pytest-timeout>=2.1.0
asyncio_mode = strict
timeout = 60
timeout_method = signal
markers =
run_paths
no_ws_connect
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
# LMDB Database backup utility
DATABASE_PATH="${HOME}/printer_data/database"
MOONRAKER_ENV="${HOME}/moonraker-env"
OUPUT_FILE="${HOME}/database.backup"
print_help()
{
echo "Moonraker Database Backup Utility"
echo
echo "usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -e <env path> Moonraker Python Environment"
echo " -d <database path> Moonraker LMDB database to backup"
echo " -o <output file> backup file to save to"
exit 0
}
# Parse command line arguments
while getopts "he:d:o:" arg; do
case $arg in
h) print_help;;
e) MOONRAKER_ENV=$OPTARG;;
d) DATABASE_PATH=$OPTARG;;
o) OUPUT_FILE=$OPTARG;;
esac
done
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
DB_TOOL="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/dbtool.py"
if [ ! -f $PYTHON_BIN ]; then
echo "No Python binary found at '${PYTHON_BIN}'"
exit -1
fi
if [ ! -f "$DATABASE_PATH/data.mdb" ]; then
echo "No Moonraker database found at '${DATABASE_PATH}'"
exit -1
fi
if [ ! -f $DB_TOOL ]; then
echo "Unable to locate dbtool.py at '${DB_TOOL}'"
exit -1
fi
${PYTHON_BIN} ${DB_TOOL} backup ${DATABASE_PATH} ${OUPUT_FILE}
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# This script builds a zipped source release for Moonraker and Klipper.
install_packages()
{
PKGLIST="python3-dev curl"
# Update system package info
report_status "Running apt-get update..."
sudo apt-get update
# Install desired packages
report_status "Installing packages..."
sudo apt-get install --yes $PKGLIST
}
report_status()
{
echo -e "\n\n###### $1"
}
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
if [ ! -d "$SRCDIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
if [ ! -d "$KLIPPER_DIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
}
# Force script to exit if an error occurs
set -e
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
OUTPUT_DIR="$SRCDIR/.dist"
KLIPPER_DIR="$HOME/klipper"
BETA=""
# Parse command line arguments
while getopts "o:k:b" arg; do
case $arg in
o) OUTPUT_DIR=$OPTARG;;
k) KLIPPER_DIR=$OPTARG;;
b) BETA="-b";;
esac
done
[ ! -d $OUTPUT_DIR ] && mkdir $OUTPUT_DIR
verify_ready
if [ "$BETA" = "" ]; then
releaseTag=$( git -C $KLIPPER_DIR describe --tags `git -C $KLIPPER_DIR rev-list --tags --max-count=1` )
echo "Checking out Klipper release $releaseTag"
git -C $KLIPPER_DIR checkout $releaseTag
fi
python3 "$SRCDIR/scripts/build_release.py" -k $KLIPPER_DIR -o $OUTPUT_DIR $BETA
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more