1972 Commits
Author SHA1 Message Date
Eric Callahan 1ed102edfb docs: add new metadata fields
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-23 20:03:01 -04:00
Eric Callahan 5b81a641d6 assets: clarify the welcome message
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-23 19:57:38 -04:00
Franklyn Tackitt 4ba6fd228f metadata: Add printer model and profile version
Adds `printer_vendor`, `printer_model`, `printer_variant`, and
`profile_version` to parsed metadata. Currently only parsed for
PrusaSlicer derivatives.

Signed-off-by: Franklyn Tackitt <git@frank.af>
2026-03-23 19:31:17 -04:00
Eric Callahan e8d4a66fc9 notifier: log version of Apprise library
Add a note in the notifier documentation indicating the
relationship between the installed version of Apprise and
notification services available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-21 10:38:27 -04:00
Eric Callahan 9fc3a70570 build: bump apprise to version 1.9.8
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-21 06:19:33 -04:00
Eric Callahan 5f8a801a45 docs: clarify notifier configuration instructions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-21 06:14:52 -04:00
Eric Callahan 9e6eeead5b docs: update requirements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-17 06:31:59 -04:00
Eric Callahan 7e92d8a2a9 build: bump tornado to version 6.5.5
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-17 06:14:54 -04:00
Eric Callahan 811347c663 build: use uv for project management
Switch to "uv" for package and project management.  Currently
the pdm backend is still used to perform the build due to its
built-in scm versioning and flexible build hooks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-16 19:48:52 -04:00
Eric Callahan fb257f8ab8 authorization: only authenticate passwords for local users
Refactor the _login_jwt_user to make it more clear and streamlined.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-03-06 15:24:41 -05:00
Eric Callahan 3fbe6ee218 mqtt: fix tls for version 2.0+ clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-02-25 15:28:40 -05:00
Eric Callahan 293a4cfc21 docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-02-08 14:30:09 -05:00
Eric Callahan 179011f29f metadata: streamline PrusaSlicer identity detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-02-03 12:34:18 -05:00
Eric Callahan 3252bc232b metadata: refactor supported field detection
Rather than keep a separate list of supported fields, use the BaseSlicer
class to track them.  All fields must implement a "parse_{field name}"
method in the BaseSlicer, overridden as necessary in child classes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-02-03 12:34:18 -05:00
Eric Callahan 1e84ecaadd metadata: auto register slicer parsing implementations
Use a metaclass to track and register subclasses of
BaseSlicer.  This removes the need to keep a separate
"SUPPORTED_SLICERS" constant.  Registered slicers are
sorted so that derivative classes are inserted before
parents.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-02-03 12:34:18 -05:00
Eric Callahan 4637d70ac1 metadata: add support for unknown PrusaSlicer forks
Match any slicer conforming to the original identifier provided
used by PrusaSlicer.  This allows Moonraker to process metadata
for the numerous PS forks that are created.

Create a derivative class for BambuStudio, as it is sufficiently
different  that it requires its own implementation to correctly
process all metadata.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-31 20:18:18 +00:00
Eric Callahan 343bba4c60 machine: support reboot and shutdown on more distros
Previously a change was made away from the standard "reboot" and
"poweroff" commands as not every systemd distro had the correct
symbolic links available.  However, there are other distros that do
not use systemd.  To support the maximum number of distros detect
if systemctl is available and prefix it to the command if so.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-28 15:57:36 +00:00
Eric Callahan 3e29720cb2 docs: fix headers for example secrets file
Make the title header clear for the examples.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-22 20:32:30 +00:00
Eric Callahan 290e537a84 docs: add a security policy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-22 08:16:57 -05:00
Eric Callahan 16e530eb66 docs: prepare for version 0.10.0 release
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-21 19:08:15 +00:00
Eric Callahan a577b061ac docs: bring up changelog and configuration.md
Document all recent changes, particularly to the LDAP module.

Signed-of-by: Eric Callahan <arksine.code@gmail.com>
2026-01-21 19:08:15 +00:00
Eric Callahan 6e6d51c213 ldap: support case insensitive group comparisons
By default the comparison between the `group_dn` option and
group DNs reported by the server are case sensitive.   Add a
"check_dn_case" option to toggle this behavior.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-21 19:08:15 +00:00
Eric Callahan 4baff7a54b ldap: support alternate membership attributes
Allow "isMemberOf" in addition to "memberOf".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-21 19:08:15 +00:00
Eric Callahan 7bcba99e37 ldap: use consistent error responses
Previously 401 errors returned a response with a descriptive message,
useful in determining the reason for failure.  These descriptions could
be used in combination with filter injection to determine the success
or failure of an ldap filter search.

To avoid this return the generic "Unauthorized" message for all ldap
401 errors.  The descriptive failure will be present in moonraker.log.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-15 21:36:26 +00:00
Eric Callahan 74c5d8e44c ldap: resolve filter injection vulnerability
Escape filter characters from the username before substituting in the filter.   This resolves a vulnerability where Moonraker could be used to dump all users and their attributes from a configured ldap server.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-15 21:36:26 +00:00
Eric Callahan bac55c65f8 workflows: delete stale github workflow
The "zip" style distribution of Moonraker was never deployed.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2026-01-15 13:00:38 +00:00
Eric Callahan 63672ea38b mqtt: update static types to support client version 2.0 or greater
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-15 12:55:40 +00:00
Eric Callahan 4b751e79e1 build: update universal zeroconf wheels
Version 0.136.2 is the last release supporting Python 3.8,  0.148.0 is the latest release at the time of this commit.  These provide fallback options for
platforms for which wheels are not available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-15 00:26:27 +00:00
Eric Callahan 3ea83163b0 build: update python dependencies to their latest versions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-14 16:21:49 +00:00
Eric Callahan 0e8dd923f8 install: add support for dev container installs
Add support for installing Moonraker inside a vscode "python"
dev container.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-14 12:49:16 +00:00
Eric Callahan 2b1c70a9e1 build: update python dev requirements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-14 12:49:16 +00:00
Eric Callahan d7df2876dd sysdeps_parser: add support for env exclusions
A list of system package exclusions may be set via the
MOONRAKER_EXCLUDED_PKGS environment variable.
In addition, a MOONRAKER_VENDOR enviroment
variable has been added to allow for manually setting
the vendor name.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-14 12:49:16 +00:00
Eric Callahan 3e6378fbc6 repo: update gitignore file
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2026-01-14 12:49:16 +00:00
Eric Callahan bdeddcabad system_deploy: check update severity bits in info_code
The update severity is stored in the upper 16 bits of the info code in
newer versions of package kit.  Some backends may omit the lower
16-bits and only store the severity, in those cases use the update
severity enum value in place of the info value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2026-01-14 12:49:16 +00:00
igiannakas b3f9566b8b spoolman: fix filament accounting on MMU setups (happy hare, AFC)
Rebase E high-water mark on active spool change to prevent spoolman undercount after tool changes

Signed-off-by: Ioannis Giannakas <ioannis@my-spot.co.uk>
2026-01-06 10:33:38 -05:00
Pedro Lamas 5b92e52e29 metadata: filament_name and filament_type as array
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-12-13 12:46:00 -05:00
Michał Ciesielski 058517b5b4 json_wrapper: don't include spaces in encoded json
msgspec doesn't encodes into compact JSON, without spaces. Make default json.dumps do the same.

Signed-off-by: Michal Ciesielski <michal@ciesie.com>
2025-12-04 19:45:20 -05:00
Eric Callahan 960e933837 thirdparty: update packagekit enums
Add new packagekit enumerations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-11-23 11:19:55 +00:00
Eric Callahan 37d46d284f scripts: update pk-enum-converter.py
Minor improvement to docstring item description formatting.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-11-23 11:17:45 +00:00
Eric Callahan be41e8ded6 system_deploy: fix Info enum instantiation
The info_code included in the package signal may
contain a "package_severity" value in the upper
16-bits.  Mask off the lower 16 bits to avoid an
instantiation error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-11-22 15:39:11 +00:00
Javad Asgari Shafique 3129d89f0f simplyprint: increase connect timeout from 5.0 to 15.0 seconds
Signed-off-by: Javad Asgari Shafique <me@javad.sh>
2025-11-16 06:02:14 -05:00
Jonas Damtoft abd2026b90 python_deploy: use --pre flag for pip beta channel
Signed-off-by: Jonas Damtoft <jonasdamtoft@gmail.com>
2025-11-10 07:53:36 -05:00
Eric Callahan 8426f4107c simplyprint: avoid divide by zero in layer detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-10-20 10:47:57 -04:00
Eric Callahan 3eb575d0ec td1: add annotations future import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-10-12 07:46:50 -04:00
Eric Callahan f2bb93ffc4 common: use the 'data' field for agent error info
The JSON-PRC specs "data" as the correct field name for
extra error data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-10-04 17:02:53 -04:00
martijnvanduijneveldt 5836eab233 proc_stats : Add support for cpu temperature readout on intel and amd
thermal_zone0 doesn't exist on amd, and can be wrongly mapped on intel
Detect correct thermal zone based on hwmon name, fallback to thermal_zone0

Signed-off-by: Martijn van Duijneveldt <martijnvanduijneveldt@gmail.com>
2025-10-02 14:20:01 -04:00
matszwe02 0775e3f4fc metadata: allow generating thumbnails for unknown slicer
This will allow for less common or newly created slicers to attach thumbnails into gcode, without a need to report as being a different slicer

Signed-off-by: Mateusz Szwedka <matszwe02@gmail.com>
2025-10-02 07:40:45 -04:00
Eric Callahan 1bc2189b72 common: improve agent error handling
Introduce an AgentError exception which contains error
details provided by the agent in response to a client
request.  These details are included in an "extra" field
of the error object in the response.

Use code error code 424 (Failed Dependency) when an agent
responds to a request with an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-10-02 07:30:54 -04:00
Eric Callahan 9098675ede td1: various cleanup
- Limit imports to those necessary during type checking
- Fix ambiguous annotations
- Remove calls to deprecated "datetime.utcnow"
- Rename TD1Protocol to TD1Connection
- Remove extraneous whitespace
- Remove duplicative "TD1._known_serials" class member.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-10-02 07:30:54 -04:00
jimmyjon711 b11a791566 docs: Adding documentation for TD-1 module
Signed-off-by: Jim Madill <jcmadill1@gmail.com>
2025-09-25 05:53:38 -04:00
jimmyjon711 e22da356d1 td1: Adding support for interfacing with TD-1 devices
Signed-off-by: Jim Madill <jcmadill1@gmail.com>
2025-09-25 05:53:38 -04:00
Eric Callahan 72ca7dbe05 asyncio_serial: add force option to set_read_callback
If force == true and None is passed as the read callback then
the existing reader will be closed and a new reader is created.
This can be used to exit an existing reader's iterator without
closing the serial connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-22 15:10:57 -04:00
Eric Callahan 596e7d9e79 async_serial: fix linter error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-21 14:23:06 -04:00
Eric Callahan 3fe343db57 async_serial: allow custom read callbacks
AsyncSerialConnection consumers may switch between Stream Reader mode and callback mode to process incoming data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-20 10:31:33 -04:00
Eric Callahan a18a18c1b1 async_serial: add from_config static method
Allow AsyncSerialConnection class instantiation with or without a
ConfigHelper object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-20 05:54:58 -04:00
Eric Callahan 00170f3505 pip_utils: bump pip version to 25.2
Python 3.7 and 3.8 are now EOL and not supported by the latest version
of Pip, so pip version pinning and updates required refactoring.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-16 07:47:32 -04:00
Eric Callahan 01963c45c1 metadata: improve handling of file encoding
The size of the file is not necessarily equal to the number of characters
read due to variable length utf8 encoding.  Read gcode files in binary mode then encode to a string.

When determining the "gcode start byte" and "gcode end byte" use
the length of the decoded string to determine the correct value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-16 07:47:32 -04:00
Eric Callahan fa90202eb9 metadata: support more PrusaSlicer thumbnail formats
Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-12 14:15:14 -04:00
Eric Callahan df3965e896 python_deploy: bump pip refresh timeout to 10 minutes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-12 14:15:14 -04:00
Eric Callahan b9b1c899b3 app_deploy: refactor pip update check
Reduce time spent running "pip --version" by storing the version
info and last time checked.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-11 16:52:14 -04:00
Eric Callahan 29083b7c49 python_deploy: update pip prior to refresh
Packages updated via PyPI require a recent version of Pip
to perform the "dry run" installation used to determine
upstream version info.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-09-08 10:33:21 -04:00
Javad Shafique 52e315868b simplyprint: extend job_info with objects and job_id
- Restructered `exclude_object` handling to be sent over `job_info` as
  `skipped_objects`
- Append and track current job_id in `job_info` and `file_progress`
  messages
- Fixed old test-url (internal usage)
- Send `current_object` as `job_info.object`

Signed-off-by: Javad Asgari Shafique <me@javad.sh>
2025-08-31 12:24:24 -04:00
Eric Callahan bbda9e2f55 simplyprint: forward exclude_object status
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-08-31 12:24:24 -04:00
Eric Callahan f20feff6c6 job_state: refactor print start detection
Any transition to from an idle state to any state other
than "standby" should emit a started event.  This should
nearly always be a "printing" state, however it is possible
that Klipper's API server will not have a chance to push
a  "printing" status update if the print is immediately
paused, cancelled, or aborted due to an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-08-01 18:17:31 -04:00
Božo Dragojevič 77c9149348 git_deploy: Support relative paths in gitfile
When a git project managed by moonraker is a submodule of a superproject, gitfile
contains a relative path.

Resolve contents of the gitfile relative to the directory containing the gitfile.

Signed-off-by: Božo Dragojevič <bozzo.dragojevic@gmail.com>
2025-07-28 16:27:58 -04:00
Eric Callahan cea6fbcf17 machine: fix typo in usb_id storage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-26 14:05:49 -04:00
Thijs Triemstra 00720f5bf0 moonraker: fix typos in source
Signed-off-by: Thijs Triemstra <info@collab.nl>
2025-07-26 14:03:29 -04:00
Thijs Triemstra 46913913be git deploy: fix typos
Signed-off-by: Thijs Triemstra <info@collab.nl>
2025-07-26 13:59:29 -04:00
Eric Callahan 72b89d905e build: add libcamera2 optional dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

fix
2025-07-24 06:15:34 -04:00
Eric Callahan 206fd4828d sysdeps_parser: add support for vendor specifier
Currently the vendor is only detected for systems running
Raspberry Pi OS and reported as 'raspberry-pi'.  This may be
used to filter Pi specific dependencies.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-23 19:28:01 -04:00
Eric Callahan b1b515a1fb power: fix linting error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-16 06:39:08 -04:00
Eric Callahan 83034dd2fc docs: document new power options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-16 06:31:27 -04:00
Eric Callahan 3df6a1eafd power: silence polling errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-15 10:35:12 -04:00
Eric Callahan 8d4244ba87 power: improve device initialization
Remove duplicate code and improve error handling
during device init.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-13 13:52:52 -04:00
Eric Callahan 3072882495 power: add device polling
Implement optional polling for devices that are not updated
asynchronously.  GPIO, RF, Klipper, and MQTT devices are
excluded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-13 13:52:52 -04:00
Eric Callahan a6862fba03 power: klipper device improvements
Avoid binding to the detected unit name of the Klipper
service, if available.  Exclude all async notifications
sent when  the device is processing a request.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2025-07-12 06:18:14 -04:00
Eric Callahan 8d67e65c7f power: process initial bound services for uhubctl and klipper devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-12 06:17:14 -04:00
Eric Callahan a78e704b0d power: add restrict action processing option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-12 06:17:10 -04:00
Eric Callahan 06cdffa169 application: disable websocket pinging for older versions of tornado
Version of Tornado prior to 6.5.0 have a bug that may
prematurely close websocket connections when pinging
is enabled.  Disable pinging for Moonraker's websocket
server and spoolman's client.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-07-08 06:24:45 -04:00
Julien Batonnet 3c1f31874a simplyprint: Improve progess calculation mimicing what's being done in Mainsail and Fluidd
Signed-off-by: Julien Batonnet <julien.batonnet@gmail.com>
2025-07-06 12:40:35 -04:00
Karcsesz 6ff9a7ca7a docs: Fix typos and amend a missing field description
Signed-off-by: Veres Károly <git@karcsesz.hu>
2025-06-27 14:58:37 -04:00
Eric Callahan 12bfb15d64 docs: update documentation with latest changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 14:16:31 -04:00
Eric Callahan 826f0e3ea3 spoolman: fix ping timeout
Tornado client websockets treat the ping timeout differently
from server websockets.  The ping timeout should be less than
the ping interval.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 14:00:37 -04:00
Eric Callahan bfdf2a91ef template: add debug logging environment global
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 10:41:04 -04:00
Eric Callahan 0cc941f7e0 build: bump tornado and dbus-fast
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 10:41:04 -04:00
Eric Callahan bd266cdce2 eventloop: store reference to all background tasks
Newer versions of Python can potentially destroy tasks
before they are complete due to garbage collection.   To
prevent this a reference to all created tasks are kept in
a set and removed when the task is done.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 10:41:04 -04:00
Eric Callahan 0c848948b4 power: extend context for the mqtt state response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-27 10:41:04 -04:00
Eric Callahan dbe0dc4d08 update_manager: add report_anomalies option
Anomalies do not prevent updates, they are intended to alert
users of potential issues detected within an extension for
update.  Anomalies are always logged, however it is not
necessary for them to be reported to frontends.  This option
gives users the ability to silence anomalies on a per extension
basis.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-25 07:49:23 -04:00
Eric Callahan ccbfd64989 analysis: remove trailing slash from dump url
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-12 05:20:05 -04:00
Eric Callahan 6d65a914a2 analysis: include route prefix in dump url
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-06-11 05:26:45 -04:00
Eric Callahan 0310d0be9f build: bump pdm-backend version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-05-22 11:44:36 -04:00
Eric Callahan 1c12414972 analysis: fix dump url detection
Don't use the detected public IP when the user
has configured Moonraker to listen exclusively
on the localhost.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-04-22 05:46:53 -04:00
Thijs Triemstra 5ee0adc553 docs: fix typos
Signed-off-by: Thijs Triemstra <info@collab.nl>
2025-04-19 05:22:23 -04:00
Icenowy Zheng 7cdcca3cb4 build: bump pillow for Python >=3.9
Pillow 10 does not support Python 3.13 and Pillow 11 does not support
Python 3.8.

Allowing Pillow from 9.5.0 to 11.1.0 in requirements to adapt Pillow 11
when it's available.

Signed-off-by: Icenowy Zheng <uwu@icenowy.me>
2025-04-03 10:32:01 -04:00
Pedro Lamas 63bcf0b99d power: removes extra space from command
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-04-03 05:21:46 -04:00
Eric Callahan b90c96524c server: skip pip recovery when the missing module is a component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-03-26 05:53:25 -04:00
Eric Callahan 1226a08176 loghelper: add support for structured logging
Support logging to json structures, useful for log parsers
and analytics.  When enabled logging to stdout is still human
readable, so both forms of logging are available simultaneously.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2025-03-26 05:29:33 -04:00
Pedro Lamas ebaa6645b2 metadata: improves Cura multi-extruder support
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-03-14 05:31:53 -04:00
Pedro Lamas 4eb23ef281 metadata: balanced quoted string split
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-03-06 11:43:52 -05:00
Wondro 18f3da59b0 file_manager: Fix total filament change count parsing for PS/SS
Signed-off-by: Tyler Wondrasek <wondro18@hotmail.com>
2025-03-03 05:30:56 -05:00
Eric Callahan 91b6bfbd09 workflows: update bug template
Add OctoApp to the client list.  Make it clear that moonaker.log is
required.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-03-01 08:10:00 -05:00
Wondro 4889a2dd38 file_manager: Added per tool weights and total filament change count metadata
Signed-off-by: Tyler Wondrasek <wondro18@hotmail.com>
2025-02-26 18:08:53 -05:00
moggieuk 9b4b3def44 file_manager: Added additional metadata to aid tool selection on single extruder multi-material prints
Added additional essential metdata for single extruder multi-material printing.  This is critical to new Mainsail functionality to map tools to MMU spools when using Happy Hare (Klipper MMU driver)

Signed-off-by: Paul Morgan (moggieuk@hotmail.com)
2025-02-26 12:32:10 -05:00
Eric Callahan f2d53fe386 install: update package resolution method
Embed the sysdeps_parser module in the install script
for package dependency resolution.  This method is
more robust than the bash implementation and adds
support for the new requirement specifiers.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-21 16:54:12 -05:00
Eric Callahan 31cb1fc94c update_manager: use sysdeps_parser
Use the sysdeps_parser utility to parse the correct dependencies
out of the data returned by the configured system dependencies
json file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-21 16:54:12 -05:00
Eric Callahan 4b4ca76558 utils: add sysdeps_parser utility module
This functionality is used by the update manager to parse
the result from system dependency files.  By moving it
out of the update manager it becomes easier to test,
extend, and maintain.  Additionally it can be embedded
in the install script.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2025-02-21 05:22:58 -05:00
Pedro Lamas 62051108ea docs: JSON typo fix
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-02-18 10:23:11 -05:00
Eric Callahan a0164e1575 docs: typo fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 18:17:31 -05:00
Eric Callahan c35353ed2a file_manager: delay file observer initialization
The addition of "gcode file processors" makes it possible
for processor registration to occur in "component_init".
The file observer init must be delayed until after all processors
are registered to correctly process metadata for gcode files
added while Moonraker was not running.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 15:32:45 -05:00
Eric Callahan 35cb7501c6 docs: update analysis and metadata docs
Signed-off-by:  Eric Callahan
2025-02-17 15:32:45 -05:00
Eric Callahan 58f060730b analysis: add process endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 15:32:45 -05:00
Eric Callahan cb39c8c88a analysis: don't allow an estimate to update metadata
Early feedback is that replacing the "estimated_time" field of the metadata
with the value returned by Klipper Estimator is not sufficient.  The
post-process performed by Klipper Estimator also updates M73 gcode
commands, ETAs calculated based on progress are inaccurate without
these mods.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 15:32:45 -05:00
Eric Callahan a95405f800 file_manager: handle inotify edge move case
It is possible to create, move, then close a file.  Handle this case
by rescheduling the "create_file" event under the new name.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 15:32:45 -05:00
Eric Callahan 1f4888cded analysis: change behavior of auto analysis
Perform a post-process with Klipper Estimator rather than
analyze and replace the "estimated_time" field in the metadata.
This updates the M73 commands in the gcode file, allowing for
more accurate ETAs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 15:32:45 -05:00
Eric Callahan b8b28bc0c9 file_manager: add support for metadata gcode processors
Allow components to register gcode processors which will modify
the gcode file prior to metadata processing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 08:06:46 -05:00
Eric Callahan e338f537f5 pip_utils: handle exceptions when updating pip
Don't propagate exceptions when update_pip fails.  Some
systems may not be able to update pip, and the current
version of pip should be sufficient to install packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-17 08:06:46 -05:00
Pedro Lamas ccbb03f5f3 docs: fixes invalid JSON in example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2025-02-17 08:05:17 -05:00
Eric Callahan 354cc11b8e docs: fix typos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-12 06:28:53 -05:00
Eric Callahan 706455a6f8 source_info: include git worktree detection
Standard git repos contain a ".git" folder, however worktrees
contain a ".git" file.  The file provides the path to the worktree's
git directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-11 16:51:04 -05:00
Eric Callahan 2fcc542d85 docs: update documentation with latest changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-11 08:01:50 -05:00
Eric Callahan f2c564cfb7 analysis: initial implementation
Adds support for GCode file time analysis using Klipper Estimator.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-11 08:01:50 -05:00
Eric Callahan 3ec968d873 python_deploy: update local state on refresh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-10 18:17:39 -05:00
Eric Callahan c7c2bb20d9 python_deploy: fix rollback procedure
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-10 18:17:39 -05:00
Eric Callahan 7f1907beb3 python_deploy: enable the eager pip update strategy
Attempt to update all dependencies of a python package to the
latest version compatible with its requirement specifier.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-10 18:17:39 -05:00
Eric Callahan bda03dcf29 file_manager: emit event after gcode metadata has been processed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-10 18:17:39 -05:00
Eric Callahan 530f1c2016 update_manager: add support for executable types
This change refactors zip_deploy.py, renaming it net_deploy.py.
Net hosted executables that currently exist on the system
with a valid `release_info.json` file can now be updated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-10 18:17:39 -05:00
Eric Callahan 636626506a file_manager: provide method to look up paths by root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 15:20:46 -05:00
Eric Callahan 152837959a authorization: add method to return api key
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 15:20:46 -05:00
Eric Callahan ff2571180c update_manager: support internal updaters
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 15:20:46 -05:00
Eric Callahan 1117890327 docs: update changelog
Also add a warning to the "webhooks" printer object description
stating that it should not be used to receive async "ready"
updates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 10:31:56 -05:00
Eric Callahan fb6e416e1c mqtt: push Klipper status updates after subscription
This resolves an issue where MQTT clients miss the first status
update after a Klipper restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 06:15:26 -05:00
Eric Callahan b8388db18d klippy_connection: improve subscription request handling
If the connection requesting the subscription already had
an outstanding subscription, remove it before processing.
This prevents immediate status updates from being pushed
to the requesting connection.

Don't add connections to the dictionary of subscribed
connections if the request is an empty object, as this
is a request to unsubscribe from all objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-07 06:08:49 -05:00
Eric Callahan 71ab2fb80e docs: update readthedocs configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-06 19:17:41 -05:00
Eric Callahan fae2b31acc docs: config doc formatting improvements
Use block style admonitions and add titles to
fenced code.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-06 19:15:38 -05:00
Eric Callahan 9c550a8f9a docs: complete API documentation rework
Moonraker's external API documentation has been significantly
overhauled in an effort to improve clarity and readability.
All parameters and responses are documented with specifications.
Tables and other elements are used to make documentation more
visible and less verbose.

Spelling and other corrections have also been added.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-06 19:15:38 -05:00
Eric Callahan 5a3b35f5ac docs: add collapse_code extension from pymdown-ex
This extension is used to collapse the example responses presented
in the API documentation, which can be quite long.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-05 07:35:31 -05:00
Eric Callahan 549f9fe91d build: bump pdm-backend to 2.4.3
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-04 05:44:32 -05:00
Eric Callahan f3b0afd574 build: bump streaming-form-data package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-03 06:08:49 -05:00
Eric Callahan ac4959cfbf build: bump tornado and apprise packages
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-03 05:37:27 -05:00
dependabot[bot] 8f4ed621a7 build(deps): bump jinja2 from 3.1.4 to 3.1.5
Bumps [jinja2](https://github.com/pallets/jinja) from 3.1.4 to 3.1.5.
- [Release notes](https://github.com/pallets/jinja/releases)
- [Changelog](https://github.com/pallets/jinja/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/jinja/compare/3.1.4...3.1.5)

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

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-03 05:25:08 -05:00
Eric Callahan fad1a1531b docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-01 08:15:43 -05:00
Eric Callahan e417d80244 update_manager: add upgrade endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-02-01 07:49:25 -05:00
Eric Callahan 7e3c86e09a docs: update documentation with latest changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-30 07:43:54 -05:00
Eric Callahan 0848fa1b59 update_manager: support "extra" reqs for python updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-29 16:31:58 -05:00
Eric Callahan 50e1f3c0c4 update_manager: report name and type for os package manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-29 16:28:33 -05:00
Eric Callahan 52781fbd9e update_manager: report updater name for git_repo types
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-27 20:25:04 -05:00
Eric Callahan d4d2074466 scripts: update fetch-apikey.sh
Fetch the API Key from Moonraker's SQL database when available.

Add a -g option which will generate a new API Key and insert it into the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-24 07:42:19 -05:00
Eric Callahan db64bc02c8 pip_utils: upgrade existing packages during installation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-24 05:22:46 -05:00
Eric Callahan 432a3a653a application: log http API request exceptions in verbose mode
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-23 08:11:41 -05:00
Eric Callahan 72ed175c52 src: type comparison fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 12:35:08 -05:00
Eric Callahan 7e765b667c wled: lint fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 12:31:55 -05:00
Eric Callahan 73dc4e50eb build: remove pyserial-asyncio requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan 239494e4dc wled: initial support for responses
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan ca2772df79 wled: formatting and annotation fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan 308a5eb5d4 wled: use async_serial utility
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan 0307a32e1b paneldue: use async_serial utility
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan 60c2bef474 async_serial: support for asyncio serial devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-13 11:13:41 -05:00
Eric Callahan fe60ebd89a wled: don't import tornado dependencies
Use Moonraker's http client to communicate with the wled device.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-12 10:24:56 -05:00
Eric Callahan fccffa96c6 build: replace dbus_next with dbus_fast
The dbus_next dependency is no longer maintained.  Replace
it with dbus_fast, which is a fork and drop in compatible.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-12 07:39:35 -05:00
Eric Callahan 73ad860bb9 install: add ubuntu specific dependencies
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-09 16:29:44 -05:00
Eric Callahan c79ba01dba install: support for package requirement specifiers
Initial support for pip-like requirement specifiers applicable
to system packages.  This allows for a package dependencies
specific to distribution version.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2025-01-09 16:28:03 -05:00
Eric Callahan a4604e3380 python_deploy: fix github dev channel updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-12-22 07:38:06 -05:00
Eric Callahan ccfe32f236 datastore: store multiline commands as one entry
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-11-17 15:18:32 -05:00
Eric Callahan d4ef626961 datastore: gcode command storage fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-11-17 14:51:03 -05:00
Eric Callahan 4e00a0760e application: verify upload filename
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-10-22 05:37:30 -04:00
Eric Callahan 71f9e677b8 docs: update changelog for release 0.9.3
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-09-05 08:15:21 -04:00
Eric Callahan d1c2dcca0b install: update location of policy-rules script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-09-05 08:15:21 -04:00
Eric Callahan 8df98908ca build: add scripts directly to the moonraker package
Per maintainers setuptool maintainers, the use of the "shared data"
path is deprecated and no longer recommended.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-09-05 08:15:21 -04:00
Eric Callahan f735c04194 power: fix 'address' option percent encoding
Allow "/" separators in the address.  This patch also resolves a regression in  the generic http client.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-11 13:52:00 -04:00
Eric Callahan e66744b6e9 power: improve basic auth implementation
Rather than pass the user name and password via the
url, supply them directly to the http request.  This should guarantee that the authorization header is
generated correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-11 06:26:23 -04:00
Eric Callahan 30ac5dfae9 docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-09 05:58:35 -04:00
Eric Callahan 0a8590643f server: refactor startup
Use asyncio.run() to launch the server application as recommended
by the Python docs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-08 16:29:01 -04:00
Eric Callahan 3a42dac02b announcements: use data path for dev mode
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-08 15:02:23 -04:00
Eric Callahan 863d0c1e4b confighelper: don't resolve backup path
If the configuration file is a symbolic link we want the backup
generated in the config folder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-08-08 15:02:13 -04:00
Eric Callahan b40751ba9d docs: update install documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-30 14:01:49 -04:00
Eric Callahan c2409e813e build: shared data fix
Make sure the scripts directory is included in the "data/share"
folder in the wheel.  In addition, remove the stray .gitignore
that is included when building a wheel from an sdist.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-30 14:01:49 -04:00
Eric Callahan 83371cf135 project: add support for dependency syncing
Use pre-commit to synchronize python requirements between
pyproject.toml and the various requirements files.  In addition,
syncronize the contents of system-dependencies.json with
Moonraker's installer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-30 14:01:49 -04:00
Eric Callahan 247640cc27 install: add support for installing from pip
Include distribution  detection for future support of
distros not compatible with Debian.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-30 14:01:49 -04:00
Eric Callahan 63578aefd0 release: bump version to 0.9.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 15:02:46 -04:00
Eric Callahan 8debbf8ba4 source_info: resolve importlib_metadata compatibility issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 14:16:42 -04:00
Eric Callahan 6f2c79f985 build: note support for Python 3.12
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 13:44:23 -04:00
Eric Callahan 7117cfc273 python_deploy: minor reporting fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 12:46:21 -04:00
Eric Callahan 5fec55f5a0 release: bump version to v0.9.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 11:46:30 -04:00
Eric Callahan 92ce2a5a5d update_manager: correct base configuration
Remove deprecated "host_repo" option, update Klipper's venv args to invoke Python 3.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-25 10:27:21 -04:00
Eric Callahan 54d68d9394 docs: add python package update documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 16:35:37 -04:00
Eric Callahan 003acd5f64 update_manager: fetch klipper paths from klippy_connection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 16:35:37 -04:00
Eric Callahan 9097cfcce7 klippy_connection: store klipper source path and python path
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 16:35:37 -04:00
Eric Callahan 484551e5bf app_deploy: streamline type and channel config
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 16:35:37 -04:00
Eric Callahan 9beecbda92 confighelper: add getchoice method
This getter provides a pattern for configuring an item that
within a range of choices.

Signed-off-by:  Eric Callahan <arksine@gmail.com>
2024-07-24 07:37:08 -04:00
Eric Callahan 96b1c22e28 update_manager: add support for python applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2024-07-24 07:37:08 -04:00
Eric Callahan b8921ca593 python_deploy: support for updating python apps
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 07:37:08 -04:00
Eric Callahan 17dc05c9b7 versions: expand support for Python Package Versions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 07:37:08 -04:00
Eric Callahan 0ff1d79b5b server: improve add_warning method
Add an exc_info parameter that optionally takes an
exception that is passed to the logging function. This
will log the traceback without an additional logging call.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 07:37:08 -04:00
Eric Callahan 11d15f96d1 pip_utils: add async method to invoke pip directly
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 07:37:08 -04:00
Eric Callahan ecb6ebcc18 pip_utils: bump pip version to 24.0.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 07:37:01 -04:00
Eric Callahan 0fb48fb9bf app_deploy: separate out pip update method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 06:29:59 -04:00
Eric Callahan 4e8d50367d app_deploy: fix unbound variable
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 06:29:59 -04:00
Eric Callahan cdef4e7393 build: add importlib_metadata dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 06:29:59 -04:00
Eric Callahan a101815a47 utils: add support for extracting project dist info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-24 06:29:59 -04:00
Eric Callahan b8ba6c0d2b mqtt: add support for a user configured client id
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-22 13:55:33 -04:00
Eric Callahan 5c62149fc4 simplyprint: remove AI functionality
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-22 10:34:08 -04:00
Eric Callahan dc00d38b01 job_queue: improve state reporting
Only report ready when an item is in the queue and automatic transition is enabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-07-05 07:23:28 -04:00
Eric Callahan 8f3b30a04f build: bump tornado to version 6.4.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-06-23 05:42:18 -04:00
Eric Callahan b07b2be5ca docs: update uhubctl power documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-06-23 05:39:20 -04:00
Eric Callahan dfa38a0ddc power: uhubctl Pi 4 bugfix
Default the port option to None if omitted.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-06-23 05:39:20 -04:00
Nick Gon 2dbea4f4cd metadata: Add support to extract metadata from g-code files generated by QIDISlicer
This PR adds support to extract metadata from the g-code files generated by QIDISlicer

Signed-off-by: Nick Gon <albatar@trance.fr>
2024-06-23 05:31:45 -04:00
Moggie 4d6037c3d3 module: file_manager
Allow default metadata parser timeout to be configurable

Signed-off-by: Paul Morgan moggieuk@hotmail.com
2024-06-23 05:31:18 -04:00
Eric Callahan 346a3d7c9d history: fix default for unknown filename during migration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-06-02 07:37:05 -04:00
Eric Callahan f2f2c93aa1 history: check for null values during database migration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-06-02 07:17:15 -04:00
Eric Callahan 4fe89d5571 database: don't warn on UUID mismatch
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-28 18:07:18 -04:00
Eric Callahan 7f89bd7d62 git_deploy: limit corruption detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-28 16:13:13 -04:00
Eric Callahan 3b1c21a72d database: attempt to install lmdb if missing
When attempting a conversion, install the lmdb package if its missing.
This should resolve issues with containers or new installations that
want to migrate a previous db to sqlite.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-28 06:11:42 -04:00
Eric Callahan 5332eab258 database: skip invalid values when migrating namespaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-27 10:49:34 -04:00
Eric Callahan c9581205d3 docs: add pinned commit documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-25 12:30:56 -04:00
Eric Callahan fa1dc438fa git_deploy: add support for pinned commits
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-25 12:30:56 -04:00
Eric Callahan bc34ebdff9 filelock: fix lockfile cleanup
Python 3.7 does not support the "missing_ok" argument
in pathlib.unlink().

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan e41a934f74 database: support legacy sqlite_master table
Sqlite versions older than 3.33.0 store schema information in the
sqlite_master table rather than the sqlite_schema table.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 7e16dded0b docs: add sqlite documentation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 6b31076a43 machine: skip validation for new installs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 3f62bb6fb4 database: add backup, restore, and compact endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 64ffe22545 build: dependency updates
Remove lmdb python and system dependencies.  Bump
streaming-form-data to 1.15.0 and remove smart_open
as the issue import issue has been resolved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 0b1fce8a6d file_manager: minor type checking fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan bb0266f5c4 app: replace dict with UserInfo throughout Moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan eddf47e4a3 authorization: use SQL tables to store user info
Add a UserInfo class which provides type annotations for each member.
This class easily converts to a dict or tuple, simplifying conversion
for usage in SQL statements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 3f0d20ed8c history: use tables for history and totals storage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-21 06:18:46 -04:00
Eric Callahan 80c762074f database: migrate from lmdb to sqlite
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-18 08:03:47 -04:00
Eric Callahan 9d0d09de80 eventloop: add low level eventloop property
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-18 08:03:47 -04:00
dependabot[bot] 73df63db1f build(deps): bump jinja2 from 3.1.3 to 3.1.4
Bumps [jinja2](https://github.com/pallets/jinja) from 3.1.3 to 3.1.4.
- [Release notes](https://github.com/pallets/jinja/releases)
- [Changelog](https://github.com/pallets/jinja/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/jinja/compare/3.1.3...3.1.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-18 08:02:28 -04:00
Eric Callahan fca0cf3027 docs: update sensor documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-15 07:31:57 -04:00
Eric Callahan 76704feee4 sensor: add support for parameter configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-15 07:31:57 -04:00
Eric Callahan c5bf6e77a7 confighelper: type checking fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-14 20:08:40 -04:00
Eric Callahan 9c6048a759 confighelper: store deep copies of parsed options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-14 18:05:19 -04:00
Eric Callahan ba9428558a docs: add uhubctl documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-06 07:56:42 -04:00
Eric Callahan ddc0e76ffc power: add support for uhubctl devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-06 06:46:53 -04:00
Eric Callahan 326d23a509 docs: document history additions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-05 06:29:21 -04:00
Eric Callahan 81899e04fd sensor: add history field options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-05 06:29:21 -04:00
Eric Callahan b60e6dc311 spoolman: add history field tracking spool ids
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-04 08:16:37 -04:00
Eric Callahan 531028ef4f history: report user in job history
When possible record the name of the user that requested the
job.  The klippy_api's component now takes an optional user
argument in its "start_print" method.  This user is broadcast
in an event after a print request successfully returns.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-04 08:16:37 -04:00
Eric Callahan 1dfbffb422 history: add support for auxiliary fields
Allow other components to register custom fields tracked and reported
in job history.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-04 08:16:37 -04:00
Eric Callahan b6896c7c0a common: add common history tracking implementation
The HistoryDataField class can be instantiated by any
component.  It can then be used to register additional fields
tracked in the job history.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-04 08:16:37 -04:00
Eric Callahan e7d3f3e961 job_state: track and store most recent Job Event
Signed-off-by:  Eric Callahan <arksine.codee@gmail.com>
2024-05-03 08:22:41 -04:00
Eric Callahan 4b1a3b8792 sensor: minor refactoring
Remove dataclasses, refactor for consistency with
other components.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-03 08:22:41 -04:00
Eric Callahan 8d59c424d7 server: convert history a core component
The history component requires no specific configuration, is
generally always used, and has no dependencies that prevent
loading at startup.  Convert history to a core component,
making it eligible for lookup/use in optional components.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-05-03 08:22:41 -04:00
Eric Callahan 0f2e3d7c99 mqtt: fix whitespace error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 12:32:34 -04:00
Eric Callahan 48cb177ef0 docs: update configuration and changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 12:21:24 -04:00
Eric Callahan ac550bac24 mqtt: add support for tls connections
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 12:08:30 -04:00
Eric Callahan 5570ab02ee power: remove state check when performing job queue requests
Allow the device to refresh the state in the event that its stale.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 12:08:30 -04:00
Eric Callahan 1ab413e9bc mqtt: add support for paho client version 2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 12:08:30 -04:00
Eric Callahan a802e10725 mqtt: support configurable status update interval
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-28 06:03:12 -04:00
Eric Callahan 546a17f5d3 filelock: add missing newline
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-27 11:10:24 -04:00
Eric Callahan 7394a22c2d filelock: fix type annotation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-27 11:08:18 -04:00
Eric Callahan 379a26600c update_manager: use temporary file storage for iids
The default behavior of systemd is to remove shared memory
files when the user that created them logs out.  This breaks
instance ID tracking for most installations.  While its possible
to overcome this by changing the user type or the logind
configuration, these solutions required elevated privileges.
The simple solution is to store iids in a temporary file, with
access protected by a flock.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-27 10:52:22 -04:00
Eric Callahan 683d93a894 utils: add file lock utility
Uses linux flock to create lock files that can be used
to protect access across multiple processes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-27 10:24:44 -04:00
David Zwart 02144b472a docs: more tweaks in remote API JSON formatting
Remote API docs tweaks. Some leading commas removed for JSON serialization. Also found an unclosed json section.

Signed-off-by: David Zwart <davidzwa@gmail.com>
2024-04-27 06:16:59 -04:00
David Zwart 763d987309 docs: fix remote API JSON formatting and url(s)
"Delete a webcam" section contained a wrong url. Some response examples were wrapped in result, and some others were not. I've removed "result": { } for consistency. Finally I've removed many leading commas causing problems with JSON deserialization.

Signed-off-by: David Zwart <davidzwa@gmail.com>
2024-04-27 06:16:59 -04:00
Patrick Schmidt c857e1a99f spoolman: Add spoolman response headers to proxy results
Added the response headers to the V2 response of the proxy implementation as a new field named "response_headers".

Signed-off-by: Patrick Schmidt <ps.patti1998@gmail.com>
2024-04-24 13:51:23 -04:00
Eric Callahan b631ec44bb docs: update contributing documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-24 07:51:42 -04:00
Eric Callahan 2bf6d609cb klippy_apis: add print/job request logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-24 07:22:19 -04:00
dependabot[bot] 5a60d64f04 build(deps): bump pillow from 9.5.0 to 10.3.0
Bumps [pillow](https://github.com/python-pillow/Pillow) from 9.5.0 to 10.3.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/9.5.0...10.3.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-23 19:55:27 -04:00
Eric Callahan 9447494bd5 file_manager: static type checking fixes 2024-04-19 11:28:01 -04:00
Eric Callahan 44a5600038 job_state; check stored state on disconnect
If Klipper disconnects while printing manually set the state
to "error".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-04 20:15:33 -04:00
Eric Callahan 99b97afc7d simplyprint: fix layer detect divide by zero
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-04-03 10:47:34 -04:00
Pedro Lamas a3e4dac5fb docs: corrects canbus peripherals response example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2024-03-16 05:23:24 -04:00
Eric Callahan affe196ff6 machine: move default allowed services to an asset file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-03-15 15:07:29 -04:00
Eric Callahan 98bb40bd80 utils: add kernel version
Move the kernel version tuple calculation out of gpio.py into
the utils package so its available for any module that requires
it.  In addition, report the kernel version string with the distribution
info and log the platform in the rollover header.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-03-11 06:26:18 -04:00
Eric Callahan 10dfb0d477 update_manager: improve instance detection
Implement instance package wide for the update_manager.  This
only requires detecting multiple instances once and eliminates
costly calls to git.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-03-11 06:26:17 -04:00
bakatrouble 6b1b8c5102 metadata: support multiple filament lengths for prusaslicer
Signed-off-by: Aleksey Frolov <bakatrouble@gmail.com>
2024-03-05 19:42:59 -05:00
Eric Callahan f0ae51792f power: add support for custom Homeseer ports
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-03-01 05:50:03 -05:00
Eric Callahan 9813011db2 build: pin smart_open to 6.4.0 or lower
This is a temporary workaround to resolve a bug in smart_open 7.0.
Moonraker does not depend on smart_open directly or use its
functionality, however `streaming_form_data` pulls in in.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-26 05:54:41 -05:00
Eric Callahan 0850c16b00 sensor: require the 'state_response_template'
The sensor configuration isn't useful unless the user configures a
template that calls "set_result" to update fields for the desired
template.  Remove the default payload template and require
that it be configured.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-24 06:05:07 -05:00
Eric Callahan 90e13c07f7 git_deploy: fix initialization regression
New repos have not yet saved the valid state, so it is necessary to
provide a default value when attempting to access the "is_valid"
field.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-24 05:40:33 -05:00
Eric Callahan 119f579a44 git_deploy: improve refresh error handling
Save repo state if an exception is raised during a refresh
attempt.   Add additional repo warnings with for better
descriptions regarding repo issues.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-23 18:22:38 -05:00
Thijs Triemstra aadff0d54e docs: fix fluidd link
Signed-off-by: Thijs Triemstra <info@collab.nl>
2024-02-19 19:54:29 -05:00
Eric Callahan e87ab4a895 build: remove pdm.lock
Currently Moonraker's dependencies aren't managed by PDM.
Remove the lockfile and badge.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-02-17 14:00:16 -05:00
Kamil Domański 04b1103778 Allow configuring the update refresh window
This enables customizing the time of day within which periodic refresh occurs.

Previously docs said it happens between 12am-4am which is misleading,
because the code effectively allowed refresh until 4:59:59 AM.
The default window is now '0-5', which is practically the same as before.

The comment about checking every 24h hours has been fixed as well.
This hasn't been true since commit c4fa76f217

Signed-off-by: Kamil Domański <kamil@domanski.co>
2024-02-17 12:41:51 -05:00
Eric Callahan 65a8271925 spoolman: fix exception handling
Make sure the connection delay isn't skipped if the
error list is full.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-14 20:34:33 -05:00
Eric Callahan 67c98f6a76 announcements: push notification for internal announcements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-07 10:55:41 -05:00
Eric Callahan f946e6a28d sysfs_devs: implement mode query
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-03 11:47:23 -05:00
Eric Callahan 71b46cc768 build: bump preprocess-cancellation in pyproject
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:35:01 -05:00
Frank Tackitt d18021950d build: bump preprocess_cancellation to 0.2.1
0.2.1 ensures that the exclude_object markers are the first
 non-comment g-code in the files, fixing issues with klipper adaptive
 meshing

Signed-off-by: Franklyn Tackitt <git@frank.af>
2024-02-01 10:34:08 -05:00
Eric Callahan 71517b255d machine: dont allow usb id request to block initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:28:20 -05:00
Eric Callahan 6ec37fdacc docs: add new doc structure for peripheral requests
This adds a new structure for API documentation, making each
aspect visible and uniform.  The parameters, response, and
schema are collapsible, allowing for easier navigation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:28:20 -05:00
Eric Callahan 931e88b9f0 docs: move to material theme
The material theme is more feature complete and flexibile,
providing better documentation for APIs and such.  This
commit is just the initial move.  The documents are functional,
but the layout and color schemes are subject to change.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:28:19 -05:00
Eric Callahan 948b842351 docs: add peripheral API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:28:14 -05:00
Eric Callahan 145968af0f sysdevs: report paths for all devices
While a hardware UART generally won't have symlinks in the "by-path"
and "by-id" folders, it is possible to configure udev to add them.
In addition, adding these fields makes the schema consistent.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:22 -05:00
Eric Callahan 6f4a0480f3 machine: add video peripheral API request
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:22 -05:00
Eric Callahan 522b4df989 sysfs_devs: add v4l2 video campture device detection
Signed-off-by:  Eric Callahan  <arksine.code@gmail.com>
2024-02-01 10:27:21 -05:00
Eric Callahan eb1599fa07 machine: add support for peripheral queries
Implement endpoints to query the following:
- Serial Devices (including Hardware UART)
- USB Devices using lsusb
- Klipper CAN Node UUIDs

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:21 -05:00
Eric Callahan 0fb997285b sysfs_devs: hardware discovery utils using sysfs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:21 -05:00
Eric Callahan d6c8d6d3a6 server: add method to get individual app args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:20 -05:00
Eric Callahan 088a7e4e70 server: create a misc folder in the datapath
This folder contains miscellaneous files used by Moonraker
or other applications in the Klipper ecosystem.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:20 -05:00
Eric Callahan 2cebf5cc03 cansocket: utility for querying klipper can nodes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-02-01 10:27:19 -05:00
Eric Callahan 61ea86033a docs: update changelog and configuration docs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-28 06:12:13 -05:00
Eric Callahan 896cd8c41e klippy_connection: exclude configfile attrs from subscription cache
The configfile "config" and "settings" attributes never change, and
therefore do not need to be stored in the subscription cache.  They
can be significantly large, so this change can free up some memory
on low resource systems.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-28 05:55:50 -05:00
Eric Callahan 4b9973826e file_manager: add "enable_config_write_access" option
Some installations, such as those in public areas, may wish disallow
changes to the configuration.

This option defaults to True, so no change in behavior is introduced.

Signed-off-by:  Eric  Callahan <arksine.code@gmail.com>
2024-01-28 05:55:29 -05:00
Eric Callahan bc18e3174a server: load "authorization" as a core component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-28 05:42:22 -05:00
Eric Callahan c756a9029a authorization: don't raise config errors
Don't raise an exception if the default source is incorrect as this
disables authorization.  Fallback to moonraker.  When supplied an
invalid CORS domain warn the user and skip adding it to the list.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-27 19:51:34 -05:00
Eric Callahan 43efe40cd8 authorization: report more details in /access/info
Add "login_required" and "trusted" fields.  The "login_required"
field indicates that force_logins is enabled and at least one
user has been created.  The "trusted" field indicates that the
connection is configured as trusted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-27 19:42:59 -05:00
Eric Callahan 3f7cae09bb git_deploy: specify branch in clone command
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-27 17:31:27 -05:00
Eric Callahan 52ebc2b404 application: fix cors check
It is necessary to perform a cors check before authenticating
the user to make sure that the headers are set if authentication
fails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-27 17:04:39 -05:00
Eric Callahan f44fc4b85b docs: update changelog and add note about trusted domains
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-22 12:42:25 -05:00
Eric Callahan d1f97f2658 authorization: fix blocking call to socket.getfqdn()
If the upstream DNS server is not available the call to socket.getfqdn()
will block until a timeout occurs.  This blocks Moonraker's event loop,
resulting in carnage.

Call getfqdn() in a thread with a timeout of 5 seconds.  In addition,
only request the fqdn if the user has one or more trusted domains
configured.  Finally, cache resolved  FQDNs for 24 hours to limit
repeated DNS queries.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-22 12:03:01 -05:00
Eric Callahan 3d44c51613 docs: minor spelling fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 13:50:30 -05:00
Eric Callahan d10ce8772d docs: add zip type documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:06 -05:00
Eric Callahan 652bb46f60 spoolman: improve connection error reporting
Reduce verbosity in release mode and add connection status to the log rollover.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:05 -05:00
Eric Callahan 994123e92e update_manager: use ZipDeploy to instantate web types
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:05 -05:00
Eric Callahan 8010c51521 app_deploy: add support for web types
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:05 -05:00
Eric Callahan 55454a300e zip_deploy: bring up for usage
This performs a significant refactor to the ZipDeploy class, making it near identiical to WebClientDeploy.  Zipped applications have the same
"release_info" requirement as web clients.  Unlike web clients, they may also
configure the dependency and service options available to git repos.

The ZipDeploy class can also support we clients, eliminating duplicate code
and the need to keep web_deploy.py.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:04 -05:00
Eric Callahan daad786072 git_deploy: move generic dependency methods to app_deploy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:04 -05:00
Eric Callahan b620ebbc29 docs: document status endpoint and notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:03 -05:00
Eric Callahan d410731faa spoolman: add a status notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:03 -05:00
Eric Callahan a5128f06ad spoolman: add a status endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:02 -05:00
Eric Callahan bf9223225c eventloop: fix timer reentrancy
Avoid running multiple callbacks if a timer is stopped and restarted
in quick succession.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:02 -05:00
Eric Callahan d4316d9878 spoolman: refactor tracking
Use a python dict to act as a queue for reporting used filament
per spool.  This eliminates the need for locks and resolves
potential issues with spool changes when the Spoolman
service is not available.

In addition, add support for tracking multiple tools

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:02 -05:00
Eric Callahan 045075c396 docs: update spoolman proxy documentation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:01 -05:00
Eric Callahan 3102391234 spoolman: implement alternate proxy responses
The exisiting implementation of spoolman's proxy endpoint
returns responses and errors exactly as they are received
by spoolman.  This creates a problem of ambiguity, as the
frontend cannot easily diffentiate between an error returned
by Moonraker and an error returned by Spoolman.

This implements a "v2" alternate response to proxy requests.
All requests to spoolman will return success, with responses
wrapped in a top level object.  Successful requests will be
returned in a "spoolman_response" object, errors in a
"spoolman_error" object.

Initially v2 responses will be opt-in to prevent breaking existing
spoolman implementations.  However, as of this commit the v1
response is deprecated and will be removed in a future version
of Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:01 -05:00
Eric Callahan e9ad278286 spoolman: use loop time rather than datetime
The loop time is monotonic and can't be affected by
changes to the system clock.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-21 08:24:00 -05:00
Eric Callahan b836d618c9 spoolman: add a websocket connect
Connect to the spoolman sevice via websocket to receive
spool events.  In addition, this gives Moonraker a persistent
connection to know when the service is available.

Signed-off-by:  Eric Callahan  <arksine.code@gmail.com>
2024-01-21 08:24:00 -05:00
Eric Callahan a23187b4af authorization: fix access.refresh regression
Allow expired JWTs for HTTP endpoints that do not require authentication.
This is technically an error by the client, as it should not provide
invalid JWTs for an endpoint, however Moonraker previously allowed
this as the token was not verified on unathenticated endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-20 06:21:36 -05:00
Eric Callahan 66de18f9b6 spoolman: really fix type checking this time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-16 13:57:20 -05:00
Eric Callahan 8d6def7e41 spoolman: type checking fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-16 13:53:21 -05:00
Eric Callahan c196f7548c update_manager: workaround zipfile permission issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-16 12:35:38 -05:00
Eric Callahan 15fed2e819 spoolman: check for deleted spools
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-16 11:57:53 -05:00
Eric Callahan 374516a00a spoolman: remove class variables
Variables should be contained within the spoolman instance, as in the
future it could be desirable to support multiple instances.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-16 07:58:22 -05:00
Eric Callahan c4f1d251c3 klippy_connection: add support for service info fallback
If Klipper is using systemd socket activation to generate its
unix socket the PID reported by PEERCRED will be 1, that of
systemd itself.  Klipper now reports its process id in the
"info" endpoint, use that as a fallback to retreive service info.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-01-15 12:20:05 -05:00
Eric Callahan 619a588683 application: add error handling to listen()
It is possible that Moonraker cannot bind to an address if its
already in use.  Handle bind errors and warn/log when they are
encountered.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-15 08:17:35 -05:00
Eric Callahan 7beca7a1a3 application: refactor HTTP routing
Moonraker dynamically registers its routes, so we cannot easily
use the routers provided by tornado.Application.  Previously
all routes went through tornado.Application, then went to
our mutable router.  This refactor avoids that by having our
mutable router contain the tornadoapp instance, only using
it to provide the application delegate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-15 08:17:34 -05:00
Eric Callahan 35785be5dc application: remove direct websockets import
Provide a method for websocket handler registration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-15 06:03:43 -05:00
Eric Callahan 69f527b7c7 secrets: remove dependency on file_manager
It is desirable to use templates (and therefore secrets) in
the server's configuration options.  We need to defer loading
the "file_manager", remove its dependency from secrets.  When
the file_manager is loaded it will look up "secrets" and register
the file path as reserved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-15 06:03:43 -05:00
Eric Callahan 60f4a82873 confighelper: avoid direct import of JinjaTemplate
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-15 06:03:35 -05:00
Eric Callahan ddd735feba refactor: convert klippy_connection into a component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:15 -05:00
Eric Callahan a88468eb79 refactor: convert websockets into a component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:15 -05:00
Eric Callahan d506c9241f refactor: convert application into a component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:14 -05:00
Eric Callahan 94b1896e28 server: add support for python dependency recovery
It is possible that older versions of Moonraker's update_manager
will fail in its attempt to update python packages.  This can lead
to missing modules when the new version of Moonraker is loaded.

When a `ModuleNotFound` error is received during a call to
"load_component" Moonraker will attempt to install its
missing dependencies.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:14 -05:00
Eric Callahan 01ad427d75 build: bump dependency versions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:13 -05:00
Eric Callahan cf99b78489 app_deploy: use pip_utils for python package updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:13 -05:00
Eric Callahan 20871e2171 pip_utils: utilities for managing python packages via pip
This module implements both syncronous and async calls
to pip, separating it from the rest of the application.  The
syncronous implementation has no dependencies on Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-13 15:15:12 -05:00
Eric Callahan f1de614027 shell_command: refactor retrires to attempts
This is consistent with the http_client.  The argument "attempts" is more
accurate than retries, as the first attempt is not a retry.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-11 16:51:41 -05:00
Eric Callahan eee1eda6bc shell_command: add run_cmd_async method to factory
This builds and runs an async command request, providing
a shortcut similar to "exec_cmd".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-11 16:51:11 -05:00
Eric Callahan 3008a13efb update_manager: fix web_deploy persistent_files
If the destination file exists it is necessary to explicitly use
the filename to overwrite.  Otherwise an error is generated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-10 12:00:36 -05:00
Eric Callahan ea6df41f05 gpio: fix initial state for inverted gpios
The python-periphery library XORs the initial value based on
whether or not its inverted.  This requires consumers to set
the direction to "high" for inverted pins that are off, and
"low" otherwise.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-10 06:22:39 -05:00
Eric Callahan 27a0295218 eventloop: remove deprecated uvloop method
Starting in Python 3.12 uvloop.install() is deprecated.  Directly
set the event_loop_policy as advised by the documentation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-07 19:51:48 -05:00
Eric Callahan 6e6388d673 update_manager: fix race condition
Previously the Klipper repo location can be changed outside of
the lock.  If the location of the Klipper path is moved while an autorefresh is occurring it is possible for Moonraker to call refresh
and/or notify_update_refreshed before the repo has been initialized.

This commit moves the re-assignment of the "klipper" updated inside
the lock.  In addition AppDeploy._is_valid is now defined in the
__init__() method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-06 11:54:33 -05:00
Eric Callahan 84a8538597 build: fix pdm build regression
Use shutil.copytree to copy folders in the "scripts" path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2024-01-01 05:51:09 -05:00
Eric Callahan 54dc887254 build: bump zeroconf to 0.131.0
Add a local fallback link with a pure python wheel to
prevent build issues on systems where cython wheels are
not available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-31 11:18:25 -05:00
Eric Callahan ca595163bb server: log launch arguments:
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-29 20:13:29 -05:00
Eric Callahan 5585884d26 app: resolve soft restart issues
Clear the API cache when closing to purge stale callbacks.  In addition,
explicitly delte the server object after the eventloop stops.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-29 08:22:50 -05:00
Eric Callahan c4d15e40a8 install: speedup zeroconf install
Export SKIP_CYTHON prior to intalling Moonraker's python requirements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-28 16:37:09 -05:00
Eric Callahan 36b5b9f4dd update_manager: bump pip version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-28 16:37:00 -05:00
Eric Callahan 19422819da app_deploy: add support for pip environment vars
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-28 08:05:43 -05:00
Eric Callahan f7d5f11cf8 database: fix get_batch for older versions of lmdb
Some distros have older versions of py-lmdb installed
that do not implement "Cursor.getmulti()".  Add a  workaround for "get_batch()".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-28 06:02:09 -05:00
Eric Callahan 5c5e91cb3d database: log lmdb versions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-28 05:50:03 -05:00
Eric Callahan c226e9c1e4 docs: note history changes in changelog
Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-27 07:48:20 -05:00
Eric Callahan 09b6a33ae4 history: add check for interrupted jobs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-27 07:37:31 -05:00
Eric Callahan ee0c641b08 docs: update webcam documentation
Add tables specifying known values for the "icon"
and "service" options.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-24 19:44:16 -05:00
Eric Callahan cc5dea716b docs: note gpio and button behavior changes user_changes.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-24 07:53:00 -05:00
Eric Callahan dbbb07c68e confighelper: clean up warnings
Don't generate additional "unparsed option" warnings when
a component fails to load.  When an error is encountered,
include the original error message in the subsequent
ConfigError.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-23 15:22:23 -05:00
Eric Callahan ad1666bb2c confighelper: add getgpioevent method
Use the ConfigHelper as an intermediary to register GPIO event
pins.  This allows for parsing exceptions to be captured and
properly re-raised as Config Errors.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-23 11:42:32 -05:00
Eric Callahan e620d2dcd7 gpio: improve pin parsing
Use a regular expression to parse pins.  This simplifies flag
extraction and pin verification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-23 11:37:45 -05:00
Eric Callahan 06a3f932ba docs: update gpio documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 18:19:59 -05:00
Eric Callahan 2298f6b5a7 gpio: improve event debounce procedure
Use a traditional debouncing method, waiting for a specified
debounce period before triggering events.  Consumers may
choose to futher ignore events based on the the duration
between events.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 18:19:59 -05:00
Eric Callahan 78d7a4f560 build: remove gpiod deps, add python-periphery
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 18:19:58 -05:00
Eric Callahan 5d079d8c26 gpio: migrate from gpiod to python-periphery
The libgpiod library has breaks API compatibility with version 2.
Given that not all distributions ship gpiod and its unique nature
as a system package, replace it with a wrapper that directly
accesses the GPIO character device.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 18:19:58 -05:00
wollew 7fc571643d power: enable HTTP port option for Zigbee/Hue devices
Signed-off-by: Wolfgang Miller-Reichling <wolfgang+github@miller-reichling.de>
2023-12-22 18:19:05 -05:00
Eric Callahan 088d9ee59a docs: update power documentation
Note that currently only Gen 1 shelly devices are supported.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 16:53:52 -05:00
Eric Callahan 90e2ab6fcf docs: add JSON-RPC over HTTP documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-22 16:51:57 -05:00
Eric Callahan aa16dd671b app: add jsonrpc HTTP endpoint
Add a POST /server/jsonrpc endpoint that processes jsonrpc
requests from the body.  This allows developers familiar with
the JSON-RPC API to use it in places where a websocket is not
desiriable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:24 -05:00
Eric Callahan 6dbcdf537f app: improve endpoint registration logging
Only log registration when verbose (debug) logging is enabled.
In addition, log endpoint removal.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:23 -05:00
Eric Callahan 94989b39dc app: raise an exception on duplicate endpoint registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:23 -05:00
Eric Callahan b3b60757aa authorization: remove "permitted_paths" attribute
Track authentication requirements in the API Definition.  This
eliminates the need to look up the authentication component
to disable auth on an endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:22 -05:00
Eric Callahan eed759e111 klippy_apis: allow subscription requests from transports
The default behavior of the subscribe API shares all subscription
requests.  API Transports require their own subscription.  Add
a method to facilitate this request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:22 -05:00
Eric Callahan bfeb096f31 jsonrpc: share one instance among all transports
This change refactors the APIDefiniton into a dataclass, allowing
defs to be shared directly among HTTP and RPC requests.  In
addition, all transports now share one instance of JSONRPC,
removing duplicate registration.  API Defintiions are registered
with the RPC Dispatcher, and it validates the Transport type.
In addition tranports may perform their own validation prior
to request execution.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:21 -05:00
Eric Callahan 8b2d9b26f5 app: streamline endpoint registration
Refactor endpoint registration to reduce duplicated code.
Rename some APIDefinition attributes for clarity.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:21 -05:00
Eric Callahan 7de61eb113 klippy_connection: track connection state with an enum
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:21 -05:00
Eric Callahan b18e9cc222 all: Replace strings with RequestType flags
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:20 -05:00
Eric Callahan 6e8b720d17 job_state: combine events into a single handler
Emit a single event where the first argument contains
a "JobEvent" enumeration that describes the particular
event.  This reduces the number of callbacks registered
by JobState consumers and allows them react to multiple
state changes in the same callback.

The individual events remain for compatibility, however
they are deprecated.  Current modules should be updated
to use the "job_state:state_changed" event and new modules
must use this event.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:20 -05:00
Eric Callahan 7deb9fac4c common: add RequestType and TransportType flags
These flags replace strings as constants used to register and
identify Request Types (ie: GET, POST) and API Transport
Types.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 16:21:19 -05:00
Eric Callahan 42357891a3 docs: add "check_klipper_config_path" documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 15:31:35 -05:00
Eric Callahan 3b53d9532d file_manager: add option to opt out of klipper check
Some installations do not have Klipper's configuration
in the data path's "config" folder.  Provide a way to
opt out of this check.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-16 15:25:38 -05:00
Eric Callahan 6d8cb762ff file_manager: relax registration requirements
Use EAFP techniques to test for directory read permission
during registration.  If access fails continue with registration.
This allows users to potentially fix an issue without restarting.
Inotify failures always require a restart to resolve.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-15 10:53:09 -05:00
Eric Callahan 9ad8fed81e spoolman: register announcement feed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-02 07:44:40 -05:00
Eric Callahan cf83c9f709 announcements: implement feed registration
Allow internal components to register announcement feeds.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-12-02 07:42:50 -05:00
Eric Callahan fb15b2a3de metadata: increase read size to 1 MiB
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-19 17:56:55 -05:00
Eric Callahan be23f206ee metadata: refactor regex helper methods
Introduce placeholders for the regex capture groups.
This reduces the length of the original pattern and
makes it easy to change the pattern for a return value
if necessary.

This change modifies the float pattern to accept any
float or integer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-19 17:49:30 -05:00
Eric Callahan dddd968f82 simplyprint: unknown temperature fix
Omit temperature data for SBCs that Moonraker
cannot report.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-15 19:20:46 -05:00
Eric Callahan 7337c6f762 klippy_connection: fix error message from Klipper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-15 19:20:46 -05:00
Eric Callahan 07388f4d38 simplyprint: add support for gcode acknowledgements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-15 19:20:45 -05:00
Eric Callahan e3cf9b2aa9 docs: note changes to bound service init
When "initial_state" is configured, bound services will be
initialzed based on that state...stopped if the state is
"off", started if its "on.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-15 18:09:57 -05:00
Eric Callahan 6c6b7dcff0 power: process bound services when initial_state is set
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-15 18:09:56 -05:00
WALDNER Emmanuel 975011d190 metadata : fix extract to work with Ideamaker
Correction of the regex (Replacing the = with one: and adding the filament index for the regex to work).

Signed-off-by: Emmanuel WALDNER emmanuel.waldner@gmail.com
2023-11-07 16:12:58 -05:00
Eric Callahan d9c16380a4 docs: update readthedocs configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-07 15:09:03 -05:00
Eric Callahan 588454ffee docs: document agent remote method registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-07 14:49:19 -05:00
Eric Callahan 27dddd62ac extensions: support agent method registration
Create a websocket endpoint that allows clients identified as
agents to register remote methods with Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-07 11:27:11 -05:00
docgalaxyblock 2e27b073c9 docs: add Domoticz power device documentation
Signed-off-by: Olivier Berthomme <olivier@berthomme.fr>
2023-11-05 10:54:48 -05:00
docgalaxyblock b63ca44094 docs: updated prebuild images config path note from ~/klipper_config to ~/printer_data
MainsailOS loads the moonraker.conf from `~/printer_data/config/`
Source:
[MainsailOS moonraker](https://github.com/mainsail-crew/MainsailOS/tree/develop/src/modules/moonraker/filesystem/home/pi)
[MainsailOS klipper](https://github.com/mainsail-crew/MainsailOS/blob/develop/src/modules/klipper/config#L28)

Signed-off-by: Joshua Schlicker <potter-91@web.de>
2023-11-03 17:53:14 -04:00
Eric Callahan 40011370a3 update_manager: improve Klipper detection
If the Klipper installation is not updatable (ie not a git repo)
abort reinstantion of the deployer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-11-02 06:19:14 -04:00
Eric Callahan e03dbe3251 app: raise tornado http exceptions in upload handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-30 14:56:33 -04:00
Eric Callahan 4f32f477bd app: improve upload error handling
Use a lock to guarantee thread safety when parsing data.  If
parsing results an error, save the error and raise it.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-29 20:14:03 -04:00
Eric Callahan a71c5c159d spoolman: filter spool_id before setting it active
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-24 19:32:24 -04:00
Daisuke Sato 17ffb4455e docs: fix typos in docs
Signed-off-by: Daisuke Sato <tiryoh@gmail.com>
2023-10-24 08:17:40 -04:00
Eric Callahan 2641fc54d6 proc_stats: fix vcio ioctl logging spam
Use the low level os.open() method to open the vcio device.  This
resolves "unknown ioctl" spamming of the kernel log.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-13 18:07:03 -04:00
Eric Callahan b8ce199edd install: fix dbus provider detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-11 07:48:24 -04:00
Eric Callahan fd11c08b99 build: update python dependencies
The latest version of several dependencies has deprecated
Python 3.7.  Update Moonraker's requirements so that
the latest version is installed without breaking existing
installations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-10 18:23:26 -04:00
Eric Callahan b676773602 metadata: update deprecated pillow constant
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-10 18:23:26 -04:00
Eric Callahan 9785387867 docs: update linting guidelines
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:42:34 -04:00
Eric Callahan 4fe99e6ebb json_wrapper: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:37:42 -04:00
Eric Callahan d721ec5d9c update_manager: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:36:49 -04:00
Eric Callahan 6f6f535d6a file_manager: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:36:16 -04:00
Eric Callahan b4dfa5a4dd zeroconf: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:35:58 -04:00
Eric Callahan d25ddc954a wled: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:35:29 -04:00
Eric Callahan 0afbefc962 simplyprint: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:33:56 -04:00
Eric Callahan a28c7c3f93 power: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:33:20 -04:00
Eric Callahan bfc7ea3635 notifier: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:31:58 -04:00
Eric Callahan 0e7c759bde machine: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:31:41 -04:00
Eric Callahan 2a7594fc3b job_state: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:31:15 -04:00
Eric Callahan 7219cc45a5 button: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:30:56 -04:00
Eric Callahan 0eae069666 announcements: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:30:42 -04:00
Eric Callahan 89dbefe46d websockets: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:30:25 -04:00
Eric Callahan ddd4a02e9c server: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:30:08 -04:00
Eric Callahan 282cf1ce03 klippy_connection: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:29:57 -04:00
Eric Callahan 327441fd6b confighelper: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:29:24 -04:00
Eric Callahan 9b0aec378e common: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:29:04 -04:00
Eric Callahan 16c407e33c app: fix linter errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 10:28:45 -04:00
Eric Callahan 6f20150e6e workflows: update linter action arguments
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 08:16:27 -04:00
Eric Callahan a39dbeadac docs: update changelog
Note performance improvement for Raspberry Pi CPU
throttle detection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:40:42 -04:00
Eric Callahan 8d0c8e4033 proc_stats: improve vcgencmd request
Improve the efficiency of "vcgencmd get_throttled" by directly requesting
the status from the user space driver using ioctl.  This should reduce CPU
spikes that result from forking the current process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:40:41 -04:00
Eric Callahan 65644bab8b utils: add ioctl_macros module
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:40:41 -04:00
Eric Callahan 82dd2f3c1f docs: add speedups documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:40:40 -04:00
Eric Callahan ffbb628ce2 scripts: add support for installing speedups
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:40:40 -04:00
Eric Callahan d4c4b64cd5 loghelper: add newline to stdout header
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:14 -04:00
Eric Callahan c4aaf43662 gitignore: replace .pdm.toml with .pdm-python
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:14 -04:00
Eric Callahan e073df40b0 zeroconf: detect appropriate ip version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:13 -04:00
Eric Callahan e90691f168 build: bump zeroconf version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:13 -04:00
Eric Callahan 0c23630e87 mqtt: don't instantiate futures directly
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:12 -04:00
Eric Callahan 3026a0c7e7 pyproject: add msgspec and uvloop as optional dependencies
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-07 07:10:12 -04:00
Eric Callahan 51f4d4b888 eventloop: add support for uvloop
Signed-off-by:  Eric Callahan <arskine.code@gmail.com>
2023-10-06 18:20:28 -04:00
Eric Callahan f99e5b0bea utils: add support for msgspec with stdlib json fallback
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-10-06 18:20:28 -04:00
Eric Callahan 3ccf02c156 docs: update changelog
Note the fix for parsing inline comments.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-06 18:20:19 -04:00
Eric Callahan c50e61a25b docs: update and clarify inline comment rules
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-06 12:35:43 -04:00
Eric Callahan 4329241949 confighelper: fix inline comment parsing
Require that inline comments be separated from configuration
data by whitespace.  Unescape comment specifiers that follow
the correct escape sequence.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-06 12:25:26 -04:00
SHID 52ee49eed3 metadata: add support for Moment Slicer
Signed-off-by: Sanghun Jung / Email: sanghun.id@gmail.com
2023-10-05 08:08:22 -04:00
Eric Callahan 0c6b4e0dad file_manager: fix reserved path handling during runtime
If the user creates or moves a folder that was is reserved
reserved correctly ignore or remove watches as appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-05 07:59:23 -04:00
Eric Callahan a222ff0042 docs: update webcam API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-10-03 07:41:32 -04:00
Eric Callahan a232260713 webcam: support lookup by UID
Expose the UID assigned to webcams and allow clients to fetch, modify,
and delete items based on the UID.  New additions must not specify a
UID.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-09-28 08:08:37 -04:00
Eric Callahan ee62d07c68 zeroconf: use route prefix for zeroconf/ssdp servers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-09-22 07:55:10 -04:00
Eric Callahan d98f11b98e docs: note route_prefix option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-09-20 12:42:30 -04:00
Eric Callahan ae1d3b0393 app: implement route prefix option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-09-15 16:33:05 -04:00
Eric Callahan 3d9052d711 git_deploy: detached head verification fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-08-14 08:13:51 -04:00
Eric Callahan fe120952ee docs: note "include_monitors" arg for the temperature store
Signed-off-by:   Eric Callahan <arksine.code@gmail.com>
2023-08-03 07:57:36 -04:00
Eric Callahan 47f0f0c21e data_store: add support for temp monitors
Temperature Monitors may report null values as temperatures,
thus special handling is needed.  This commit also reworks
temperature store updates to use the subscription cache
rather than perform its own caching of "last temps".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-08-03 06:13:21 -04:00
Eric Callahan 797c62389d docs: add links to Klipper's status reference
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-31 16:44:23 -04:00
Eric Callahan 8adda52df1 docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-31 16:42:46 -04:00
Eric Callahan e433252934 paneldue: use cached subscription data
Now that all subscriptions are cached it is no longer required for
the paneldue component to cache its own printer state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-31 11:19:04 -04:00
Eric Callahan d3bab5de94 klippy_apis: support subscription callbacks
This callback will only fire after a component has requested
a subscription, preventing early updates while the component
is waiting for the subscription request to complete.  It is still
valid for components to register the "server:status_update"
event handler if this behavior is not a concern.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 16:30:00 -04:00
Eric Callahan 7e85ac97c9 klippy_connection: cache subscription data
It is possible that a subscripition request can occur between
after Klipper updates a field's status, but before it pushes
a status update to the connection.  The result is a race
condiiton where the response to the subscription request
contains the lastest state but it is not propagated to
currently connected clients.

This is resolved by caching subscripiton data, diffing it
with the response to the subscription request, and
manually pushing the diff.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 15:35:13 -04:00
Eric Callahan 8ad19e6054 web_deploy: return repo name in status response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 15:35:13 -04:00
Eric Callahan 6467cc6b89 klippy_connection: refactor KlippyRequest class
Wrap a Future instead of an Event, as we don't need to notify multiple
waiters. Additionally the future can return responses and raise exceptions
directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 15:35:13 -04:00
Eric Callahan c3697d0656 klippy_connection: apply a mutex to the subscription request
The subscripition request is reentrant in Klippy.  Sending multiple
requests from the same connection may create a race condition,
so use a lock to prevent reentry.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 15:35:12 -04:00
Eric Callahan 7c8d68c0a1 components: fix pycodestyle E721 warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-30 15:34:56 -04:00
Eric Callahan f487de77bc webcam: make sure db values are type correct
A previous bug in the webcam module could have set boolean
values as integers.  Make sure they are type correct when
reading webcams from the db.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-28 16:28:04 -04:00
Eric Callahan a22033ac49 webcam: fix boolean updates
In Python a "bool" is a subclass of int.  When introspecting
a webcam's attributes it is necessary to check for booleans
before integers.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-28 15:24:38 -04:00
Eric Callahan 937c766ded docs: add environment variable documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-26 07:29:41 -04:00
Eric Callahan 1857eecb36 install: use environment vars for service env file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-25 19:36:18 -04:00
Eric Callahan 22d1fda655 machine: use env vars for service validation
Use Moonraker's environment variables when generating the
env file for service validation updates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-25 19:35:43 -04:00
Eric Callahan a0a50442f7 server: add support for enironment variables
Allow all command line arguments to be specificed as an
environment variable.  If both the command line argument
and environment variable is present the command line argument
takes precedence.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-25 16:27:11 -04:00
Eric Callahan aebcd00f61 docs: note the anomalies field for update status
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-24 18:12:12 -04:00
Eric Callahan 5a0dde2017 update_manager: introduce anomalies field
This allows Moonraker to report anomalies detected in an updater
that won't prevent an update.  Front ends may decide to present
these to users in a more subtle fashion so they know the state of
the repo without being concerned of an issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-24 16:57:44 -04:00
Eric Callahan 871c551134 git_deploy: remove untracked file warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-24 15:30:25 -04:00
mista-funky fe52bc5b6d power: tplink smartstrip fix
Correct the procedure for setting the child id for devices that control more than one outlet.

Signed-off-by: Rick Marino <rcmarino@gmail.com>
2023-07-22 06:34:29 -04:00
Eric Callahan 821f3c5161 docs: note unixsocket commandline option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-22 06:17:57 -04:00
Eric Callahan 1fadae885e server: allow commandline unix socket configuration
Add a command line option that allows the installation to specify
the exact path to Moonraker's unix domain server socket.  The
default location remains at:

<data_path>/comms/moonraker.sock

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-22 06:17:56 -04:00
Eric Callahan fdc3e0eb0b docs: document changes to update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-21 06:11:00 -04:00
Eric Callahan 3e1919b46e git_deploy: improve pristine detection
Detect untracked source files and modified files for each
configured repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-21 06:11:00 -04:00
Eric Callahan ac876b9271 server: bump API version to 1.3.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-15 16:15:45 -04:00
Eric Callahan 9b1eed534b update_manage: move web update deployer to its own module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-14 12:43:57 -04:00
Eric Callahan f46cc32be3 update_manager: move package management to its own module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-14 12:40:18 -04:00
Eric Callahan 4f785cfca0 update_manager: clarify web client git warning
When the parent folder of a web client is a git repo note the specific
directory that contians a .git subdirectory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-14 12:40:17 -04:00
Eric Callahan db27fef6f2 git_deploy: only return tags merged in the remote branch
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 10:31:39 -04:00
Eric Callahan 0437d1623e git_deploy: improve recovery implementation
After performing a recovery attempt to reset to the commit the
repo was at prior to the repo failure.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 08:22:29 -04:00
Eric Callahan 4443bfbd41 update_manager: improve package manager logging
Assign a custom prefix for the configured provider.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 07:58:41 -04:00
Eric Callahan 01141fa10e git_deploy: validation improvements
Add a check for shallow repos and move validation logic to the
GitRepo class.  Additionally report the real number of commits behind.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 07:58:41 -04:00
Eric Callahan 51e3568aac update_manager: add git repo instance detection
Use git-config to set track the current Moonraker instance managing a
a git repo.  If multiple  instances are detected log and create a repo
warning.

Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 07:58:40 -04:00
Eric Callahan 011179ca6d git_deploy: improve submodule validation
Submodules contain a .git file that includes the path to the
actual repository folder.  Extract that path and use it for
lock file detection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 07:58:40 -04:00
Eric Callahan 270c78d8af git_deploy: refactor initialization
Use git-branch to determine current the current branch and
head state instead of git-status.  The former is a porcelain
command with guaranteed output.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-13 07:58:40 -04:00
Eric Callahan 3f1e9e397e update_manger: log remaining refresh time on init
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:27 -04:00
Eric Callahan 1c16233da0 git_deploy: rollback improvements
Streamline the rollback defaults so only one dict object
is explicitly defined in "capture_state_for_rollback()".
Validate the rollback branch on detached heads before
setting it.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:26 -04:00
Eric Callahan 9651923f8e git_deploy: fetch partial clones for hard recovery
It isn't necessary to download and decompress all blobs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:26 -04:00
Eric Callahan 3e875b583c git_deploy: add support for stable updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:25 -04:00
Eric Callahan 1a4480e74c git_deploy: use versions utility
Use the newly implemented versions utility for git version parsing.
This allows for simple access to version information and
version comparison.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:25 -04:00
Eric Callahan bdd1d93708 versions: software version parsing utility
The versions module contains classes that can parse
Python and Git versions, providing methods to access
the version details.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:25 -04:00
Eric Callahan 69710e10e0 update_manager: reset to correct commit after recovery
If a git repo not configured on the dev channel it is necessary
to move the HEAD to the commit for the correct tag.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:24 -04:00
Eric Callahan 41d945803f update_manager: replace string choices with enums
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:57:24 -04:00
Eric Callahan c903dd6af4 update_manager: implement update rollback support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-12 13:55:47 -04:00
Eric Callahan 26975e055b update_manager: fix klipper instantiation on path switch
Signed-off-by:  Eric  Callahan <arksine.code@gmail.com>
2023-07-12 13:50:47 -04:00
Eric Callahan 504a3a76f5 common: reduce jrpc exception spam
When a client repeatedly makes a request that results in an error
the log is spammed with tracebacks that don't provide significant
value.  The method name, code, and error message should be
enough for basic troubleshooting.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-09 13:48:01 -04:00
Eric Callahan d51820f48c metadata; use python's logging module
Replace calls to `log_to_stderr` with standard logging.<level> calls.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-09 12:01:27 -04:00
Eric Callahan 5691a4f162 shell_command: don't log the program name
When logging stderr in realtime omit the program name.  It often
does not provide useful context.  The program itself can provide
context through its own logging facilities.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-09 11:31:29 -04:00
Eric Callahan c3c3170451 file_manager: log metadata response in real time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-09 11:31:19 -04:00
Eric Callahan e6b32cabbe app: log incoming upload requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-09 08:19:13 -04:00
Eric Callahan 8eddec88cb dbus_manager: handle all PolKit interface errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-07-06 16:56:11 -04:00
Eric Callahan a7e154fbe4 changelog: note job_queue bugfix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-29 12:30:59 -04:00
Eric Callahan b36f5a4eee common: log method name for JSON RPC Errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-29 12:20:52 -04:00
Eric Callahan 499d9adbe0 job_queue: don't run transition gcode on start
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-29 11:28:10 -04:00
Eric Callahan 5d8422ec52 docs: correct spoolman API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-27 16:25:51 -04:00
Eric Callahan 93f473f629 spoolman: correct API registration
Internal Moonraker APIs must be registered with a top level path of
"server" or "machine".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-27 16:23:56 -04:00
Eric Callahan 2ef4dc4d8e update_manager: fix initial name parsing
This fixes an issue where a configuration name with spaces
may not match the reported name.

Signed-off-by:  Eric Callahan <arksine.code>
2023-06-27 12:26:58 -04:00
Eric Callahan 5f43536612 update_manager: update base channel config
Allow independent channel configuration for Moonraker and
Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-27 12:16:57 -04:00
Eric Callahan a1e786fd73 update_manager: fix defaults for base configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-27 12:10:19 -04:00
Eric Callahan 07544718fa docs: note the 'spoolman_set_active_spool' remote method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 18:10:33 -04:00
Eric Callahan a237ba3735 spoolman: add remote method to set active spool
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:52:13 -04:00
Eric Callahan 56499f9269 docs: note update_manager config changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:48 -04:00
Eric Callahan f6770e2865 server: improve event exception handling
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:48 -04:00
Eric Callahan 0592181f54 shell_command: propogate asyncio cancel exceptions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:47 -04:00
Eric Callahan 1d3e5564a2 git deploy: use python requirements file for updates
The package parsing only serves the purpose of performing the diff.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:47 -04:00
Eric Callahan 1cfeb853a5 update_manager: improve logging
Add a debug logging helper to the base class.  Use unique
logging prefixes for subclasses of AppDeploy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:47 -04:00
Eric Callahan 4edfbce3ce app_deploy: refactor configuration handling
Move specific configuration out of __init__ into several methods
that may be called by subclasses.   This allows child implementations
to define and share specific sets of configuration that they require
without forcing all implementations to do so.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:46 -04:00
Eric Callahan ee8f77c8c6 update_manager: disable repo binding
Remove hardcoded beta binding between Moonraker and Klipper.
This could result in a user getting stuck on a commit that requires
a future patch.

The original purpose of binding versions was to avoid a scenario
where Klipper introduces a feature incompatible with the current
Moonraker beta.  Rather than binding the  better solution is to
fix the incompatibility and tag a new beta.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:46 -04:00
Eric Callahan 357276b1d9 update_manager: remove unused reinstall functionality
This functionality was intended to allow for an automated
reinstallation between "git_repo" and "zip" types.  The
"zip" type remains unused, and attempting to automate
this would likely be unreliable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:45 -04:00
Eric Callahan b2d84bc733 update_manager: handle app entry points
If the exectuable in the virtualenv is not "python" attempt to
detect the python executable.  Use the pip entry point for the
pip command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:48:45 -04:00
Eric Callahan 5d54a10177 spoolman: minor fixes
Set the minimum value for the sync_rate to 1 second, rather
than above 1 second.  When transitioning from a null spool
to a named spool clear tracked extrusion.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:38:19 -04:00
Eric Callahan 09c29eab23 docs: minor spoolman updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-26 16:32:49 -04:00
Donkie 7172531386 docs: Fixed parmams typo
Signed-off-by: Daniel Hultgren <daniel.cf.hultgren@gmail.com>
2023-06-26 16:24:41 -04:00
Donkie e6b3b8ba48 docs: Added section for spoolman
Signed-off-by: Daniel Hultgren <daniel.cf.hultgren@gmail.com>
2023-06-26 16:24:41 -04:00
Donkie 4b9c836743 spoolman: Added basic spoolman integration
Proxies any request to the spoolman server. Records filament usage.

Signed-off-by: Daniel Hultgren <daniel.cf.hultgren@gmail.com>
2023-06-26 16:24:40 -04:00
Eric Callahan 2078287872 github: update linter action
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-25 07:44:03 -04:00
Eric Callahan 2b98792657 docs: add zeroconf changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-25 07:02:12 -04:00
Eric Callahan 1f0fd699ea zeroconf: add support for ssdp discovery
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-24 18:08:08 -04:00
Eric Callahan a55818bb1a app: allow endpoints to define Content Type
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-22 16:30:06 -04:00
Eric Callahan 95d5f045db zeroconf: add support for configurable mdns hostnames
Signed-off-by:  Eric Callahan <aksine.code@gmail.com>
2023-06-22 06:18:01 -04:00
Eric Callahan adc32379da zeroconf: improve mulit-instance handling
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-22 06:18:00 -04:00
Eric Callahan 02d66a346d server: add support for instance uuids
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-21 11:03:07 -04:00
Eric Callahan 0f4276d9b0 docs: document update_manager changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-20 11:59:42 -04:00
Eric Callahan 3b62ed4e4f dbus_manager: fix polkit warning
Only warn that polkit is unavailable when a component attempts
to use it to check a permission.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-20 11:59:41 -04:00
Eric Callahan a797dd0b50 update_manager: validate web type installations
Require that "web" installations provide release info to validate
existing installations.  For known web clients provide a fallback
that uses the manifest to validate the installation.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-06-20 11:59:41 -04:00
Eric Callahan a7b9e5783d git_deploy: relax validation requirements
Do not report invalid if the remote or branch does not match
the configured values.  In these conditions report them as
"repo_warnings" that frontends may display to the user.

Hard recovery now requires a recovery URL detected from the git
repo's "origin" remote.  This closes a potential security issue where a
malicioius repo could be cloned over an installed repo.

Signed-off-by:  Eric Callahan <arskine.code@gmail.com>
2023-06-20 11:59:40 -04:00
Eric Callahan 35396a5b2a source_info: add within_git_repo method
Check for git files and folders, including those of parents.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-20 11:59:40 -04:00
Eric Callahan 86af3a42ff build: update lmdb dependency in pyproject.toml
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-17 13:48:50 -04:00
Pedro Lamas 09f9043e9a requirements: bump lmdb to 1.4.1
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2023-06-17 13:46:24 -04:00
quarkvalk aa0f89c2a4 docs: fix JSON-RPC typo
Removed trailing comma in the JSON-RPC request example for
"Get Server Config", as that will raise an error.

Signed-off-by: Carl Rothe (carlrothe@gmail.com)
2023-06-08 07:16:28 -04:00
Eric Callahan 1a5cf56532 utils: add direct fallback to load_system_module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-07 19:45:39 -04:00
Eric Callahan d6231634db history: add modified time check for file existence
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-06-01 05:50:31 -04:00
Eric Callahan c41c5881c8 git_deploy: fix tag format specifier
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-05-26 14:51:16 -04:00
Eric Callahan adca664460 loghelper: improve header logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-05-26 11:00:16 -04:00
Eric Callahan cd4fdfb7b6 utils: report additional git repo data
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-05-26 10:49:58 -04:00
Eric Callahan c609060352 app_deploy: escape pip requirements installed via command line
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-05-26 07:57:09 -04:00
dependabot[bot] 348b7f521f build(deps): bump pymdown-extensions from 9.9.2 to 10.0 in /docs
Bumps [pymdown-extensions](https://github.com/facelessuser/pymdown-extensions) from 9.9.2 to 10.0.
- [Release notes](https://github.com/facelessuser/pymdown-extensions/releases)
- [Commits](https://github.com/facelessuser/pymdown-extensions/compare/9.9.2...10.0)

---
updated-dependencies:
- dependency-name: pymdown-extensions
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-25 16:10:24 -04:00
Chris Thornton b21f177e95 notifier: Add body_format as an option
This lets you format the messages through apprise a little nicer

Signed-off-by: Chris Thornton <cwgthornton@gmail.com>
2023-05-07 05:59:43 -04:00
Eric Callahan 6c7dfe5921 docs: add new fields to webcam documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-23 07:30:08 -04:00
Eric Callahan cf56a1cdcd webcam: add new fields
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-23 07:30:07 -04:00
Eric Callahan ac10b4a3b9 http_client: don't store client in the wrapper
This closes a securitiy vulernability where the client could
be used to download and save a file from any configured
location.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-18 08:09:55 -04:00
Eric Callahan 53d9522c06 sensors: measurement request fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-18 08:09:54 -04:00
Eric Callahan eff090170c docs: update power configuration documentation
Signed-off-by:  Eric Callaham <arksine.code@gmail.com>
2023-04-14 07:43:29 -04:00
Eric Callahan 204e7ca4ff power: add support for generic http sensors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-14 07:43:28 -04:00
Eric Callahan d393c89ae0 http_client: add a http request wrapper
This wrapper is an object that may be used to build requests
procedurally rather than submit all request parameters in
a call to "request()", "get()", etc.  This is primarily useful for
usage in a Jinja2 context.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-05 06:13:08 -04:00
Eric Callahan 31e589abde job_queue: fix erronous state after start
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-04 11:07:16 -04:00
Eric Callahan 6b73da55f8 job_queue: never transition after complete unless auto is enabled
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-04-04 11:03:12 -04:00
SoftFever 110cbd1084 metadata: Add support to extract metadata from g-code files generated by OrcaSlicer
Signed-off-by: Li Jiang <softfeverever@gmail.com>
2023-03-20 06:20:33 -04:00
Eric Callahan 80920dd872 utils: fix dist package check
Older versions of virtualenv include their own "site" module
that does not have the "getsitepackages" method.  Add
a check to verify its presence  before calling it.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-03-05 16:41:21 -05:00
Eric Callahan c40a3474f4 docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-03-05 12:30:00 -05:00
Eric Callahan 4cc0e86dc0 build: bump apprise to version 1.3.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-03-05 12:28:42 -05:00
Eric Callahan 6ef20d0a1f docs: update notifier documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-03-05 12:28:41 -05:00
Eric Callahan f29c896c4a notfiier: extend attach option
The "attach" option now accepts templates, such templates
are passed the same context received by the body and title
options.  Additionally it is possible to specify multiple
attachments by separating each attachment with a newline.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-03-05 12:28:41 -05:00
Mikkel Schmidt 40013ec270 module: add ratos-configurator to default services
Adds the RatOS configurator to the default service list in machine.py so future installs of moonraker will allow the ratos configurator service to be managed from frontends.

Signed-off-by: Mikkel Schmidt <mikkel.schmidt@gmail.com>
2023-03-05 12:27:56 -05:00
Eric Callahan 18f5ff4eed build: fix pyproject.toml
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-27 10:43:24 -05:00
Eric Callahan c8767daddf docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-27 06:35:11 -05:00
Eric Callahan 523c1ce423 docs: clarify update_manage documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-27 06:23:04 -05:00
Eric Callahan 452aa9a931 klippy_connection: save service info in database
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-26 16:52:27 -05:00
Eric Callahan ead4cc21ce update_manager: fix service restart
On machines running instances of Moonraker and Klipper without
the default service names it is necessary to look up their unit names
using systemd.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-26 16:19:38 -05:00
Eric Callahan fd5ea0c6a4 octoprint_compat: validate web_request args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:16 -05:00
Eric Callahan 6a5a5b50d3 update_manager: validate web_request args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:16 -05:00
Eric Callahan 4281c4d978 machine: validate web_request args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:15 -05:00
Eric Callahan 2d70511474 file_manager: use get_list WebRequest method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:15 -05:00
Eric Callahan 07e4b2cd7a job_queue: use get_list WebRequest method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:14 -05:00
Eric Callahan bc7e7d4548 announcements: use get_list WebRequest method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 10:26:14 -05:00
Eric Callahan 734351d9a0 common: add get_list method to WebRequest
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:48:40 -05:00
Eric Callahan 1b9f29db13 websockets: move JsonRPC and BaseSocketClient to common
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:43 -05:00
Eric Callahan 201e84cd94 database: remove stale import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:43 -05:00
Eric Callahan ad66831324 confighelper: getlists bugfix
If a valid "count" argument is received do not overwrite it
with "None" values.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:42 -05:00
Eric Callahan 834fa2e4e0 mqtt: ignore type error in paho client
The original paho client was written without considering
static type checking.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:42 -05:00
Eric Callahan 244004136c klippy_apis: handle invalid klippy responses
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:41 -05:00
Eric Callahan 6d73c60a38 moonraker: move common classes to common.py
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:08:41 -05:00
Eric Callahan 160f6d64be simplyprint: fix error on import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-24 07:00:47 -05:00
ThinkAlex 80fb97c9bc docs: fix typo in print_objects.md
Fixes a minor typo in the `gcode_move` section of `print_objects.md`.

`coorinates` becomes `coordinates`

Signed-off-by: Alexandre Haddad-Delaveau <ahaddaddelaveau@icloud.com>
2023-02-23 17:53:03 -05:00
Pedro Lamas ed569a2fdb docs: fixes minor typos
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2023-02-23 11:29:39 -05:00
Eric Callahan a06f748587 docs: update doc requirements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-23 11:11:47 -05:00
Eric Callahan 68a6eb3f2a docs: bump version in changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-23 11:01:31 -05:00
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
206 changed files with 69601 additions and 19978 deletions

No files matched your search

+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: ''
---
+68
View File
@@ -0,0 +1,68 @@
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).
All bug reports MUST include `moonraker.log` as an attachment.
- 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
- OctoApp
- 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).
--->
+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: weibullguy/python-lint-plus@v1.12.0
with:
python-root-list: "moonraker scripts"
virtual-env: "python-lint-plus"
python-version: "3.10"
use-flake8: true
flake8-version: "==6.1.0"
use-mypy: true
mypy-version: "==1.5.1"
extra-flake8-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"
+24
View File
@@ -0,0 +1,24 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
.devel
.venv
venv
start_moonraker
*.env
*.egg-info
.pdm-python
build
dist
share
.vscode
.mypy_cache
.pdm-build
.pytest_cache
# Sometimes uv lock generates the version file and places it in
# the repo. We don't want to commit this, so ignore it
moonraker/__version__.py
+13
View File
@@ -0,0 +1,13 @@
repos:
- repo: local
hooks:
- id: sync-requirements
name: sync python requirements
language: system
entry: python3 scripts/sync_dependencies.py
files: ^pyproject.toml$
- id: sync-os-packages
name: sync packages
language: system
entry: python3 scripts/sync_dependencies.py
files: ^scripts/system-dependencies.json$
+14
View File
@@ -0,0 +1,14 @@
version: 2
build:
os: ubuntu-24.04
tools:
python: "3.12"
mkdocs:
configuration: mkdocs.yml
fail_on_warning: false
python:
install:
- requirements: docs/doc-requirements.txt
+31 -12
View File
@@ -1,24 +1,43 @@
# Moonraker - API Web Server for Klipper
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with Klipper. Communcation between
client applications may use to interact with the 3D printing firmware
[Klipper](https://github.com/KevinOConnor/klipper). Communication between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
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/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
- [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
This section contains changelogs that users and developers may reference
to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](/docs/user_changes.md) - December 31st 2020
Developers:\
[api_changes.md](/docs/api_changes.md) - January 1st 2021
Please refer to the [changelog](https://moonraker.readthedocs.io/en/latest/changelog)
for a list of notable changes to Moonraker.
+19
View File
@@ -0,0 +1,19 @@
# Security Policy
## Supported Versions
Moonraker provides security updates through new releases. All versions are supported, however users
will need to update to the latest release to get the latest fixes.
## Reporting a Vulnerability
Users can report security vulnerabilites through GitHub's private vulnerablility reporting.
Once a report is received users should expect a typical response time of one to two days, one week at most.
If the report is accepted as a legitimate vulnerability a security advisory will be drafted and
a work will begin on a fix. The finder will get credit for the report and may be asked to
collaborate on a private fork, depending on the depth of the vulnerability and complexity of
the fix. Once the fix is complete and tested it will be pushed to the master branch of the
repo, a new release will be created, and the security advisory will be published. Ideally this will
occur within 1-2 weeks of the report.
If the report is declined no further action will be taken.
+145 -8
View File
@@ -1,4 +1,140 @@
This document keeps a record of all changes to Moonraker's web APIs.
##
This document keeps a record of notable changes to Moonraker's Web API.
### July 18th 2023
- Moonraker API Version 1.3.0
- Added [Spoolman](./external_api/integrations.md#spoolman) APIs.
- Added [Rollback](./external_api/update_manager.md#rollback-to-the-previous-version)
API to the `update_manager`
- The `update_manager` status response has new fields for items of the
`git_repo` and `web` types:
- `recovery_url`: Url of the repo a "hard" recovery will fetch from
- `rollback_version`: Version the extension will revert to when a rollback
is requested
- `warnings`: An array of strings containing various warnings detected
during repo init. Some warnings may explain an invalid state while
others may alert users to potential issues, such as a `git_repo` remote
url not matching the expected (ie: configured) url.
- Additionally, the `need_channel_update` field has been removed as the method
changing channels is done exclusively in the configuration.
### 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 [the documentation](./external_api/devices.md#sensor-endpoints)
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 [the documentation](./external_api/jsonrpc_notifications.md#sensor-events)
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](./external_api/server.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`). Sub-folders within these
these roots are also monitored, however hidden folders are not.
The following changes API changes have been made to accommodate
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 notifications. 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 particularly 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
@@ -18,7 +154,8 @@ This document keeps a record of all changes to Moonraker's web APIs.
core API:
- `POST /machine/services/restart`
See [web_api.md](web_api.md) for details on these new endpoints.
See [the documentation](./external_api/update_manager.md) for details
on these new endpoints.
### November 23rd 2020
- Moonraker now serves Klipper's "docs" directory. This can be access
@@ -52,7 +189,7 @@ See [web_api.md](web_api.md) for details on these new endpoints.
"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
containing device info, matching that which would be received
from a single item in `/machine/power/devices`.
### November 12th 2020
@@ -72,13 +209,13 @@ See [web_api.md](web_api.md) for details on these new endpoints.
- 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
connection will only receive 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
Currently 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
@@ -163,8 +300,8 @@ See [web_api.md](web_api.md) for details on these new endpoints.
- `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.
- A new notification has been added: `notify_metadata_update`. This
notification is sent when Moonraker parses metadata 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:
@@ -264,7 +401,7 @@ See [web_api.md](web_api.md) for details on these new endpoints.
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
- Subscriptions are now pushed as "diffs". Clients will only receive updates
for subscribed items when that data changes. This requires that clients
initialize their local state with the data returned from the subscription
request.
+339
View File
@@ -0,0 +1,339 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog].
## [Unreleased]
### Changed
- **machine**: Support standard reboot and shutdown commands
### Added
- **metadata**: Auto-detect forks of PrusaSlicer.
- **metadata**: Add `printer_vendor`, `printer_model`, `printer_variant`,
and `profile_version` parsing for PrusaSlicer derivatives.
## [0.10.0] - 2026-01-21
### Changed
- **data_store**: Store multi-line gcode commands in a single entry.
- **dbus_manager**: Replace unmaintained `dbus-next` requirement with
`dbus-fast`.
- **pip_utils**: Use the "upgrade" option when installing python packages.
This will force upgrades to the latest version available as resolved by
the requirement specifier.
- **python_deploy**: Use the "eager" dependency update strategy.
- **wled**: Use the `async_serial` utility for serial comms.
- **paneldue**: Use the `async_serial` utility for serial comms.
- **scripts**: Update `fetch-apikey.sh` to query the SQL database
- **update_manager**: The following endpoints have been deprecated
as of API version 1.5.0:
- `/machine/update/full`
- `/machine/update/client`
- `/machine/update/moonraker`
- `/machine/update/klipper`
- `/machine/update/system`
The new `/machine/update/upgrade` endpoint replaces the functionality
of all of the above. The deprecated endpoints will NOT be removed,
so existing software does not need to be changed. New software
should use the new endpoint, however it may be desirable to also
support the deprecated `full` and `client` endpoints for compatibility
with older API versions.
- **simplyprint**: Improve job progress calculation.
- **build**: Bump PDM-Backend to 2.4.4.
- **build**: Bump Apprise to 1.9.6
- **build**: Bump Tornado to 6.5.4
- **build**: Bump Streaming-form-data to 1.19.1
- **build**: Bump Jinja2 to 3.1.6
- **build**: Bump dbus-fast to 3.1.2
- **build**: Bump pillow to 12.1.0
- **build**: Bump inotify-simple to 2.0.1
- **build**: Bump paho-mqtt to 2.1.0
- **build**: Bump zeroconf to 0.148.0
- **build**: bump importlib_metadata to 8.7.1
- **metadata**: Export `filament_name` and `filament_type` values as arrays
when more than one value is present.
### Fixed
- **python_deploy**: Fix "dev" channel updates for GitHub sources.
- **python_deploy**: Fix release rollbacks.
- **python_deploy**: Fix support for PyPI beta updates.
- **mqtt**: Publish the result of the Klipper status subscription request.
This fixes issues with MQTT clients missing the initial status updates
after Klippy restarts.
- **eventloop**: Fixed a condition where the garbage collector may
prematurely cancel background tasks.
- **spoolman**: Use the default websocket ping timeout. Disable pinging for
versions of Tornado prior to 6.5.0.
- **application**: Disable pinging for versions of Tornado prior to 6.5.0.
- **system_deploy**: Handle the "package_severity" bits for Info Enum objects.
- **spoolman**: Fix filament tracking for MMU devices.
- **ldap**: Fix filter injection vulnerability.
### Added
- **application**: Verify that a filename is present when parsing the
multipart/form-data for uploads.
- **application**: Log all failed HTTP API requests when verbose logging
is enabled.
- **install**: Support "requirement specifiers" for system packages.
Initially this is limited to restricting packages to a specific
distro version.
- **async_serial**: Basic asyncio wrapper around pyserial.
- **wled**: Add initial support for receiving responses.
- **scripts**: Add a `-g` option to `fetch-apikey.sh`. When specified
a new API Key will be generated and stored in the database. After
running this script it is necessary to restart Moonraker.
- **update_manager**: Report `name` and `configured_type` for all status
response types. This adds consistency and allows front-end devs to
simply iterate over the values of the `version_info` object.
- **python_deploy**: Add support for updating python packages with
"extras" installed.
- **update_manager**: Add support for updating `executable` binaries.
- **update_manager**: Added a `report_anomalies` option for git, web, and zip
types.
- **git_deploy**: Add support for relative `gitdir` file paths.
- **analysis**: Initial support for gcode file time analysis using
[Klipper Estimator](https://github.com/Annex-Engineering/klipper_estimator).
- **power**: Added the ability to discard unwanted responses for MQTT
power devices.
- **power**: Added `poll_interval` option for HTTP (and all derivatives),
TPLink Smartplug, and uhubctl devices. When set Moonraker will poll device
status.
- **power**: Added `restrict_action_processing` option. When set to `False`,
post toggle actions such as restarting Klippy and controlling bound services
are run when an external power event is detected.
- **simplyprint**: Forward `exclude_object` status data from Klipper.
- **td1**: Add support for interfacing with [TD-1](https://ajax-3d.com/) devices.
- **metadata**: Add generic support for most PrusaSlicer forks.
- **proc_stats**: Add support for x86-64 (Intel and AMD) temperature sensors.
- **ldap**: Add support for servers such as OpenDJ that use the `isMemberOf`
virtual attribute to report group membership.
- **ldap**: Add `check_dn_case` option to disable case-sensitive group DN
comparisons if desired.
## [0.9.3] - 2024-09-05
### Changed
- **server**: Use `asyncio.run` to launch the server as recommended by the
official Python documentation.
- **announcements**: Look for xml files at `<data_path>/development/announcements`
when `dev_mode` is set to True.
- **build**: Move scripts from the "data" directory into a folder inside the
moonraker package.
### Fixed
- **confighelper**: Don't resolve symbolic links to the main configuration file.
- **power**: Allow special characters in the user/pass options for backends that
support Basic Authentication.
## [0.9.2] - 2024-07-30
### Added
- **install**: Add support for installing Moonraker's python package via pip.
- **scripts**: Add script to sync python and system dependencies from
`pyproject.toml` and `system-dependencies.json` respectively.
- **dev**: Add pre-commit hook to call `sync_dependencies.py`.
### Fixed
- **build**: Build from sdist now correctly includes share data.
- **build**: Remove stray `.gitignore` from Python Wheel.
### Changed
- **install**: The `MOONRAKER_FORCE_DEFAULTS` environment variable has changed
to `MOONRAKER_FORCE_SYSTEM_INSTALL`.
## [0.9.1] - 2024-07-25
### Fixed
- **source_info**: Fixed `importlib.metadata` compatibility issues with python
versions 3.9 or older.
## [0.9.0] - 2024-07-25
### Added
- **notifier**: The `attach` option now supports Jinja2 templates.
- **notifier**: The `attach` option may now contain multiple attachments,
each separated by a newline.
- **notifier**: Added support for a configurable `body_format`
- **power**: Added support for generic `http` type switches.
- **metadata**: Added support for OrcaSlicer
- **zeroconf**: Added support for a configurable mDNS hostname.
- **zeroconf**: Added support for UPnP/SSDP Discovery.
- **spoolman**: Added integration to the
[Spoolman](https://github.com/Donkie/Spoolman) filament manager.
- **update_manager**: Added support for update rollbacks
- **update_manager**: Added support for stable `git_repo` updates
- **server**: Added a `--unixsocket` command line option
- **server**: Command line options may also be specified as env variables
- **server**: Added a `route_prefix` option
- **webcam**: Webcam APIs can now specify cameras by `uid` or `name`
- **deps**: Added support for optional `msgspec` and `uvloop` packages
- **extensions**: Agents may now register remote methods with Klipper
- **file_manager**: Add `check_klipper_config_path` option
- **button**: Added `debounce_period` option
- **history**: Added a check for previous jobs not finished (ie: when power is
lost during a print). These jobs will report their status as `interrupted`.
- **build**: Added support for optional speedup dependencies `uvloop` and `msgspec`
- **update_manager**: Added support for "zipped" application updates
- **file_manager**: Added `enable_config_write_access` option
- **machine**: Add support for system peripheral queries
- **mqtt**: Added the `status_interval` option to support rate limiting
- **mqtt**: Added the `enable_tls` option to support ssl/tls connections
- **mqtt**: Added support for a configurable `client_id`
- **history**: Added `user` field to job history data
- **history**: Added support for auxiliary history fields
- **spoolman**: Report spool ids set during a print in history auxiliary data
- **sensor**: Added support for history fields reported in auxiliary data
- **power**: Added support for `uhubctl` devices
- **update_manager**: Add support for pinned git commits
- **update_manager**: Added support for updating pip managed python apps
### Fixed
- **simplyprint**: Fixed import error preventing the component from loading.
- **update_manager**: Moonraker will now restart the correct "moonraker" and
"klipper" services if they are not the default values.
- **job_queue**: Fixed transition when auto is disabled
- **history**: Added modification time to file existence checks.
- **dbus_manager**: Fixed PolKit warning when PolKit features are not used.
- **job_queue**: Fixed a bug where the `job_transition_gcode` runs when the
queue is started. It will now only run between jobs during automatic
transition.
- **klippy_connection**: Fixed a race condition that can result in
skipped subscription updates.
- **configheler**: Fixed inline comment parsing.
- **authorization**: Fixed blocking call to `socket.getfqdn()`
- **power**: Fixed "on_when_job_queued" behavior when the internal device
state is stale.
### Changed
- **build**: Bumped apprise to version `1.8.0`.
- **build**: Bumped lmdb to version `1.4.1`
- **build**: Bumped tornado to version `6.4.0`
- **build**: Bumped jinja2 to version `3.1.4`
- **build**: Bumped zeroconf to version `0.131.0`
- **build**: Bumped libnacl to version `2.1.0`
- **build**: Bumped distro to version `1.9.0`
- **build**: Bumped pillow to version `10.3.0`
- **build**: Bumped streaming-form-data to version `1.15.0`
- **machine**: Added `ratos-configurator` to list of default allowed services
- **update_manager**: It is now required that an application be "allowed"
for Moonraker to restart it after an update.
- **update_manager**: Git repo validation no longer requires a match for the
remote URL and/or branch.
- **update_manager**: Fixed potential security vulnerabilities in `web` type updates.
This change adds a validation step to the install, front-end developers may refer to
the [configuration documentation](./configuration.md#web-type-front-end-configuration)
for details.
- **update_manager**: The `env` option for the `git_repo` type has been deprecated, new
configurations should use the `virtualenv` option.
- **update_manager**: The `install_script` option for the `git_repo` has been
deprecated, new configurations should use the `system_dependencies` option.
- **update_manager**: APIs that return status report additional fields.
See the [API Documentation](./external_api/update_manager.md#get-update-status)
for details.
- **proc_stats**: Improved performance of Raspberry Pi CPU throttle detection.
- **power**: Bound services are now processed during initialization when
`initial_state` is configured.
- **gpio**: Migrate from libgpiod to python-periphery
- **authorization**: The authorization module is now loaded as part of Moonraker's
core.
- **database**: Migrated the underlying database from LMDB to Sqlite.
- **history**: Use dedicated SQL tables to store job history and job totals.
- **authorization**: Use a dedicated SQL table to store user data.
### REMOVED
- **simplyprint**: Removed defunct "AI" functionality
## [0.8.0] - 2023-02-23
!!! Note
This is the first tagged release since a changelog was introduced. The list
below contains notable changes introduced beginning in February 2023. Prior
notable changes were kept in [user_changes.md] and [api_changes.md].
### 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](./external_api/devices.md#sensor-endpoints)
- [Websocket Notification Docs](./external_api/jsonrpc_notifications.md#sensor-events)
- **file_manager**: Added new [scan metadata](./external_api/file_manager.md#scan-gcode-metadata) endpoint.
- **file_manager**: Added new [thumbnails](./external_api/file_manager.md#get-gcode-thumbnail-details) 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](./external_api/introduction.md#bridge-websocket)
connections.
- **update_manager**: Added new [refresh](./external_api/update_manager.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.10.0...HEAD
[0.10.0]: https://github.com/Arksine/moonraker/compare/v0.9.3...v0.10.0
[0.9.3]: https://github.com/Arksine/moonraker/compare/v0.9.2...v0.9.3
[0.9.2]: https://github.com/Arksine/moonraker/compare/v0.9.1...v0.9.2
[0.9.1]: https://github.com/Arksine/moonraker/compare/v0.9.0...v0.9.1
[0.9.0]: https://github.com/Arksine/moonraker/compare/v0.8.0...v0.9.0
[0.8.0]: https://github.com/Arksine/moonraker/compare/v0.7.1...v0.8.0
[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_request_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 retrieve 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 notification 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="k_connected"`
were specified when registering the `server:klippy_connected` event, the
websocket would emit a `notify_k_connected` 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-transportshttp-websocket-mqtt-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 synonymous 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 specified
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 specified.
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)*
Subscribes 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.
#### *MQTTClient.unsubscribe(hdl)*
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
exist for the topic then the topic is unsubscribed from the broker.
+3603 -119
View File
File diff suppressed because it is too large. Load diff
+140 -26
View File
@@ -1,31 +1,145 @@
# Contributing to Moonraker
While Moonraker exists as a service independently from Klipper, it relies
on Klipper to be useful. Thus, the tentative plan is to eventually merge
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:
Prior to submitting a pull request prospective contributors must read this
entire document. Care should be taken to [format git commits](#git-commit-format)
correctly. This eases the review process and provides the reviewer with
confidence that the submission will be of sufficient quality.
- 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
Prospective contributors should consider the following:
More detailed explanation if necessary.
- Does the contribution have significant impact? Bug fixes to existing
functionality and new features requested by 100+ users qualify as
items of significant impact.
- Has the submission been well tested? Submissions with substantial code
change must include details about the testing procedure and results.
- Does the submission include blocking code? Moonraker is an asynchronous
application, thus blocking code must be avoided.
- If any dependencies are included, are they pure python? Many low-powered SBCs
running Armbian do not have prebuilt wheels and are not capable of building wheels
themselves, thus breaking updates on these systems.
- Does the submission change the API? If so, could the change potentially break
frontends using the API?
- Does the submission include updates to the documentation?
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.
When performing reviews these are the questions that will be asked during the
initial stages.
#### New Module Contributions
All source files should begin with a copyright notice in the following format:
```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](https://developercertificate.org/)
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 `mypy` version 1.5.1 for static
type checking with the following options:
- `--ignore-missing-imports`
- `--follow-imports=silent`
No line in the source code should exceed 88 characters. Be sure there is no
trailing whitespace. To validate code before submission one may use
`flake8` version 6.1.0 with the following options:
- `--ignore=E226,E301,E302,E303,W503,W504`
- `--max-line-length=88`
- `--max-doc-length=88`
Generally speaking, each line in submitted documentation should also be no
longer than 88 characters, however there are situations where this isn't
possible, such as long hyperlinks or example return values.
Avoid peeking into the member variables of another class. Use getters or
properties to access object state.
+13 -13
View File
@@ -70,7 +70,7 @@
- Added thumbnail extraction from SuperSlicer and PrusaSlicer gcode files
- For status requests, `virtual_sdcard.current_file` has been renamed to
`virtual_sdcard.filename`
- Clients should not send `M112` via gcode to execute an emegency shutdown.
- Clients should not send `M112` via gcode to execute an emergency shutdown.
They should instead use the new API which exposes this functionality.
- New APIs:
- `POST /printer/emergency_stop` - `post_printer_emergency_stop`
@@ -108,7 +108,7 @@
remote_api.py module that handles server configuration.
- webhooks.py has been changed to handle communications with the server
- klippy.py has been changed to pass itself to webhooks
- file_manager.py has been changed to specifiy the correct status code
- file_manager.py has been changed to specify the correct status code
when an error is generated attempting to upload or delete a file
- The nginx configuration will need the following additional section:
```
@@ -149,8 +149,8 @@
This allows the client limited access to Klippy in the event of a startup
error, assuming the config file was successfully parsed and the
`remote_api` configuration section is valid. Note that when the server is
initally launched not all endpoints will be available. The following
endponts are guaranteed when the server is launched:
initially launched not all endpoints will be available. The following
endpoints are guaranteed when the server is launched:
- `/websocket`
- `/printer/info`
- `/printer/restart`
@@ -159,7 +159,7 @@
- `/printer/gcode`
- `/access/api_key`
- `/access/oneshot_token`
The following startup sequence is recommened for clients which make use of
The following startup sequence is recommended for clients which make use of
the websocket:
- Attempt to connect to `/websocket` until successful
- Once connected, query `/printer/info` for the ready status. If not ready
@@ -181,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
@@ -199,7 +199,7 @@
- Fix bug in CORS where DELETE requests raised an exception
- Disable the server when running Klippy in batch mode
- The the `/printer/cancel`, `/printer/pause` and `/printer/resume` gcodes
are now registed by the pause_resume module. This results in the following
are now registered by the pause_resume module. This results in the following
changes:
- The `cancel_gcode`, `pause_gcode`, and `resume_gcode` options have
been removed from the [web_server] section.
@@ -275,17 +275,17 @@
websocket data from a Blob into a String.
- The endpoint for querying endstops has changed from `GET
/printer/extras/endstops` to `GET /printer/endstops`
- Serveral API changes have been made to accomodate the addition of webhooks:
- Several API changes have been made to accommodate 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
- `GET /printer/objects` is no longer used to accommodate multiple request
types by modifying the "Accept" headers. Each request has been broken
down in their their own endpoints:
- `GET /printer/objects` returns all available printer objects that may
be queried
- `GET /printer/status?gcode=gcode_position,speed&toolhead` returns the
status of the printer objects and attribtues
status of the printer objects and attributes
- `GET /printer/subscriptions` returns all printer objects that are current
being subscribed to along with their poll times
- `POST /printer/subscriptions?gcode&toolhead` requests that the printer
@@ -297,7 +297,7 @@
- `POST /printer/gcode/<gcode>` is now `POST /printer/gcode?script=<gcode>`
- `POST printer/print/start/<filename>` is now
`POST /printer/print/start?filename=<filename>`
- The websocket API also required changes to accomodate dynamically registered
- The websocket API also required changes to accommodate dynamically registered
endpoints. Each method name is now generated from its comparable HTTP
request. The new method names are listed below:
| new method | old method |
@@ -317,7 +317,7 @@
| post_printer_firmware_restart | firmware_restart |
| get_printer_endstops | get_endstops |
- As with the http API, a change was necessary to the way arguments are send
along with the request. Webocket requests should now send "keyword
along with the request. Websocket requests should now send "keyword
arguments" rather than "variable arguments". The test client has been
updated to reflect these changes, see main.js and json-rpc.js, specifically
the new method `call_method_with_kwargs`. For status requests this simply
+168
View File
@@ -0,0 +1,168 @@
adxl
apikey
apirequest
apiresponse
argone
argtwo
arksine
armv
asvc
asyncio
atmega
Benchy
bigtreetech
binutils
calicat
camerastreamer
canbus
cansocket
cmnd
comms
compat
configfile
configheler
confighelper
configurator
Connor
crowsnest
Cura
datapath
datasheet
dbus
devel
distro
distros
Domoticz
Donkie
eeprom
endstop
endstops
EPCOS
eventtime
extr
feedrate
filelist
fileobj
firemon
Fluidd
fourcc
fromjson
frontends
ftdi
gcode
gcodes
getboolean
getfloat
getfqdn
getint
getitem
getsection
gpio
gpiochip
hexeditor
highspeed
hlsstream
homeassistant
homeseer
httpx
inotify
ipstream
jmuxer
journalctl
Kasa
katapult
klipper
klippy
klippysocket
kwargs
libcamera
libgpiod
libnacl
lmdb
logind
Loxone
loxonev
mediamtx
metascan
microsteps
mjpeg
mjpegstreamer
MJPG
Mobileraker
moko
moonagent
moontest
msgspec
Muxer
mypassword
mypy
neopixel
neopixels
Obico
octoeverywhere
octoprint
oneshot
packagekit
packagename
paneldue
piezo
PKGLIST
poweroff
Prusa
pstats
pullup
pyapp
Pycurl
pyproject
pyserial
raspberrypi
ratos
rawparams
readwrite
sdcard
sdcardinfo
sdist
Semitec
setitem
sgbrg
simplyprint
smartplug
smartthings
spoolman
SSDP
stallguard
subdir
supervisord
sysfs
sysinfo
tasmota
telegam
testcam
testdir
testuser
TESTZ
tojson
tplink
trapq
uart
ububctl
uhubctl
unicam
unixsocket
userpass
uvcvideo
uvloop
vcgencmd
venv
virt
virtualenv
volted
webcamd
webrtc
websockets
wlan
WLED
worktrees
yuyv
zeroconf
Zigbee
+4
View File
@@ -0,0 +1,4 @@
mkdocs-material==9.7.5
pymdown-extensions~=10.21.0
compact_tables@git+https://github.com/Arksine/markdown-compact-tables@v1.1.0
./docs/pymdown-extras
+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") }}
+73 -14
View File
@@ -1,5 +1,5 @@
# Example Home Assistant configuration file for a Voron V0.
# Credit to GitHub user @Kruppes
# Credit to GitHub users @Kruppes and @pedrolamas
#
sensor:
- platform: rest
@@ -13,40 +13,99 @@ sensor:
- toolhead
- display_status
- virtual_sdcard
value_template: 'OK'
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'
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
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:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
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:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
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:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
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:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["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"]}}'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['filename'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_current_progress:
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
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:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
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:
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)}}'
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:
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)}}'
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:
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}}'
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:
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}}'
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
+692
View File
@@ -0,0 +1,692 @@
# Announcements
The following endpoints are available to manage announcements.
Moonraker announcements are effectively push notifications that
can be used to notify users of important information related the
development and status of software in the Klipper ecosystem.
See [the appendix](#appendix) for details on how announcements
work and recommendations for your implementation.
## List announcements
Retrieves a list of current announcements.
```{.http .apirequest title="HTTP Request"}
GET /server/announcements/list?include_dismissed=false
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.list",
"params": {
"include_dismissed": false
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------------------- | :--: | ------- | ----------------------------------- |
| `include_dismissed` | bool | true | When set to false dismissed entries |
| | | | will be excluded from the returned |^
| | | | list of current announcements. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"entries": [
{
"entry_id": "arksine/moonlight/issue/3",
"url": "https://github.com/Arksine/moonlight/issues/3",
"title": "Test announcement 3",
"description": "Test Description [with a link](https://moonraker.readthedocs.io).",
"priority": "normal",
"date": 1647459219,
"dismissed": false,
"date_dismissed": null,
"dismiss_wake": null,
"source": "moonlight",
"feed": "moonlight"
},
{
"entry_id": "arksine/moonlight/issue/2",
"url": "https://github.com/Arksine/moonlight/issues/2",
"title": "Announcement Test Two",
"description": "This is a high priority announcement. This line is included in the description.",
"priority": "high",
"date": 1646855579,
"dismissed": false,
"date_dismissed": null,
"dismiss_wake": null,
"source": "moonlight",
"feed": "moonlight"
},
{
"entry_id": "arksine/moonlight/issue/1",
"url": "https://github.com/Arksine/moonlight/issues/1",
"title": "Announcement Test One",
"description": "This is the description. Anything here should appear in the announcement, up to 512 characters.",
"priority": "normal",
"date": 1646854678,
"dismissed": false,
"date_dismissed": null,
"dismiss_wake": null,
"source": "moonlight",
"feed": "moonlight"
},
{
"entry_id": "arksine/moonraker/issue/349",
"url": "https://github.com/Arksine/moonraker/issues/349",
"title": "PolicyKit warnings; unable to manage services, restart system, or update packages",
"description": "This announcement is an effort to get ahead of a coming change that will certainly result in issues. PR #346 has been merged, and with it are some changes to Moonraker's default behavior.",
"priority": "normal",
"date": 1643392406,
"dismissed": false,
"dismiss_wake": null,
"source": "moonlight",
"feed": "Moonraker"
}
],
"feeds": [
"moonraker",
"klipper",
"moonlight"
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------- | :------: | ---------------------------------------------------------- |
| `entries` | [object] | An array of [announcement entry](#announcement-entry-spec) |
| | | objects. The array is sorted by date in descending order |^
| | | (newest to oldest). |^
| `feeds` | [string] | An array of RSS announcement feeds Moonraker is |
| | | currently subscribed to. |^
{ #list-announcements-spec }
| Field | Type | Description |
| ---------------- | :-----------: | ------------------------------------------------------------ |
| `entry_id` | string | A unique identifier for the announcement entry. |
| `url` | string | A url associated with the announcement. This will link to |
| | | a GitHub issue for announcements sourced from `moonlight`. |^
| `title` | string | The title of the announcement. |
| `description` | string | A brief description of the announcement. For announcement's |
| | | sourced from `moonlight` this will be the first paragraph |^
| | | of the associated GitHub issue. Moonlight will truncate |^
| | | truncate descriptions over 512 characters. |^
| `priority` | string | The [priority](#announcement-priority-desc) of the |
| | | announcement. |^
| `date` | int \| float | The announcement creation date in unix time. |
| `dismissed` | bool | Set to `true` if the announcement has been dismissed. |
| `date_dismissed` | float \| null | The date, in unix time, the announcement was last dismissed. |
| | | Will be `null` if the announcement has not been dismissed. |^
| `dismiss_wake` | float \| null | The amount of time remaining, in seconds, before the entry's |
| | | `dismissed` flag reverts to `true`. Will be `null` if the |^
| | | announcement has not been dismissed or if the announcement |^
| | | was dismissed indefinitely. |^
| `source` | string | The [source](#announcement-source-desc) of the announcement. |
| `feed` | string | The registered RSS feed the announcement belongs to. For |
| | | announcements sourced internally this will typically be |^
| | | the name of the component that generated the announcement. |^
{ #announcement-entry-spec } Announcement Entry
| Priority | Description |
| -------- | ----------------------------------------------------------------- |
| `normal` | Standard priority. Front-end devs should use their own discretion |
| | on how to present announcements with normal priority to users. |^
| `high` | High priority. It is recommended that front-ends alert the user |
| | when a high priority announcement is received. |^
{ #announcement-priority-desc } Announcement Priority
| Source | Description |
| ----------- | -------------------------------------------------------------------- |
| `moonlight` | The announcement was received from the |
| | [moonlight](https://github.com/Arksine/moonlight) GitHub repo. |^
| | Announcements received from local XML files when the `announcements` |^
| | module is configured in `dev_mode` will also report the source as |^
| | `moonlight`. |^
| `internal` | The announcement was generated by Moonraker itself. This could |
| | be a component, such as `simplyprint`. |^
{ #announcement-source-desc } Announcement Source
///
## Update announcements
Requests that Moonraker check for announcement updates. This is generally
not required in production, as Moonraker will automatically check for
updates every 30 minutes. However, during development this endpoint is
useful to force an update when it is necessary to perform integration
tests.
```{.http .apirequest title="HTTP Request"}
POST /server/announcements/update
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.update",
"id": 4654
}
```
Returns:
The current list of announcements, in descending order (newest to oldest)
sorted by `date`, and a `modified` field that contains a boolean value
indicating if the update resulted in a change:
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"entries": [
{
"entry_id": "arksine/moonraker/issue/349",
"url": "https://github.com/Arksine/moonraker/issues/349",
"title": "PolicyKit warnings; unable to manage services, restart system, or update packages",
"description": "This announcement is an effort to get ahead of a coming change that will certainly result in issues. PR #346 has been merged, and with it are some changes to Moonraker's default behavior.",
"priority": "normal",
"date": 1643392406,
"dismissed": false,
"source": "moonlight",
"feed": "Moonraker"
},
{
"entry_id": "arksine/moonlight/issue/1",
"url": "https://github.com/Arksine/moonlight/issues/1",
"title": "Announcement Test One",
"description": "This is the description. Anything here should appear in the announcement, up to 512 characters.",
"priority": "normal",
"date": 1646854678,
"dismissed": true,
"source": "moonlight",
"feed": "Moonlight"
},
{
"entry_id": "arksine/moonlight/issue/2",
"url": "https://github.com/Arksine/moonlight/issues/2",
"title": "Announcement Test Two",
"description": "This is a high priority announcement. This line is included in the description.",
"priority": "high",
"date": 1646855579,
"dismissed": false,
"source": "moonlight",
"feed": "Moonlight"
},
{
"entry_id": "arksine/moonlight/issue/3",
"url": "https://github.com/Arksine/moonlight/issues/3",
"title": "Test announcement 3",
"description": "Test Description [with a link](https://moonraker.readthedocs.io).",
"priority": "normal",
"date": 1647459219,
"dismissed": false,
"source": "moonlight",
"feed": "Moonlight"
}
],
"modified": false
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :------: | ---------------------------------------------------------- |
| `entries` | [object] | An array of [Announcement Entry](#announcement-entry-spec) |
| | | objects. |^
| `modified` | bool | A value of `true` indicates that announcement entries |
| | | were changed after the update operation. |^
///
## Dismiss an announcement
Sets the dismiss flag of an announcement to `true`.
```{.http .apirequest title="HTTP Request"}
POST /server/announcements/dismiss
Content-Type: application/json
{
"entry_id": "arksine/moonlight/issue/1",
"wake_time": 600
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.dismiss",
"params": {
"entry_id": "arksine/moonlight/issue/1",
"wake_time": 600
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :-----------: | ------------ | -------------------------------------------- |
| `entry_id` | string | **REQUIRED** | The entry ID of the announcement to dismiss. |
| `wake_time` | float \| null | null | A time, in seconds, after which the entry's |
| | | | `dismiss` flag will revert to `true`. When |^
| | | | set to `null` the flag will remain `false` |^
| | | | indefinitely. |^
//// tip
The `entry_id` typically contains forward slashes. Remember to escape this value
if including it in the query string of an HTTP request.
////
///
```{.json .apiresponse title="Example Response"}
{
"entry_id": "arksine/moonlight/issue/1"
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ------------------------------------------------- |
| `entry_id` | string | The entry ID of the dismissed announcement entry. |
///
## List announcement feeds
```{.http .apirequest title="HTTP Request"}
GET /server/announcements/feeds
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.feeds",
"id": 4654
}
```
```{.json .apiresponse title="Example Response"}
{
"feeds": [
"moonraker",
"klipper"
]
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| ------- | :------: | ----------------------------------------------------- |
| `feeds` | [string] | An array of announcement feeds Moonraker is currently |
| | | subscribed to. |^
///
## Subscribe to an announcement feed
Subscribes Moonraker to the announcement feed specified in the request.
```{.http .apirequest title="HTTP Request"}
POST /server/announcements/feed
Content-Type: application/json
{
"name": "my_feed"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.post_feed",
"params": {
"name": "my_feed"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------------ | -------------------------------------------------- |
| `name` | string | **REQUIRED** | The name of the announcement feed to subscribe to. |
///
```{.json .apiresponse title="Example Response"}
{
"feed": "my_feed",
"action": "added"
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :----: | -------------------------------------------------------- |
| `feed` | string | The name of the announcement feed subscribed to. |
| `action` | string | The [subscription action](#feed-subscribed-action-desc ) |
| | | taken by Moonraker after the request has been processed. |^
| Action | Description |
| --------- | ------------------------------------------------------- |
| `added` | The requested announcement feed has been subscribed to. |
| `skipped` | Moonraker was already subscribed to the requested feed. |
{ #feed-subscribed-action-desc } Subscription Action
///
## Remove an announcement feed
Removes a subscribed feed. Only feeds previously subscribed to using
the [subscribe feed](#subscribe-to-an-announcement-feed) endpoint may be
removed. Feeds configured in `moonraker.conf` may not be removed.
```{.http .apirequest title="HTTP Request"}
DELETE /server/announcements/feed?name=my_feed
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.announcements.delete_feed",
"params": {
"name": "my_feed"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------------ | -------------------------------------------- |
| `name` | string | **REQUIRED** | The name of the announcement feed to remove. |
///
Parameters:
- `name`: The name of the new feed to remove. This parameter is required.
Returns:
The name of the new feed and the action taken. The `action` will be
`removed` if the operation was successful.
```{.json .apiresponse title="Example Response"}
{
"feed": "my_feed",
"action": "removed"
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :----: | ------------------------------------------------------ |
| `feed` | string | The name of the announcement feed removed. |
| `action` | string | The action taken after the request. Will be `removed` |
| | | upon successful removal. |^
//// tip
Unlike the [feed subscription request](#subscribe-to-an-announcement-feed) an
error will be returned if either the feed does not exist or the feed is
configured in `moonraker.conf`.
////
///
## Appendix
This section will provide an overview of how the announcement system
in Moonraker works, how to set up a dev environment, and provide
recommendations on front-end implementation.
### How announcements work
Moonraker announcements are GitHub issues tagged with the `announcement`
label. GitHub repos may registered with
[moonlight](https://github.com/arksine/moonlight), which is responsible
for generating RSS feeds from GitHub issues using GitHub's REST API. These
RSS feeds are hosted on GitHub Pages, for example Moonraker's feed may be found
[here](https://arksine.github.io/moonlight/assets/moonraker.xml). By
centralizing GitHub API queries in `moonlight` we are able to poll multiple
repos without running into API rate limit issues. Moonlight has has a workflow
that checks all registered repos for new announcements every 30 minutes. In
theory it would be able to check for announcements in up to 500 repos before
exceeding GitHub's API rate limit.
Moonraker's `[announcements]` component will always check the `klipper` and
`moonraker` RSS feeds. It is possible to configure additional RSS feeds by
adding them to the `subscriptions` option. The component will poll configured
feeds every 30 minutes, resulting in maximum of 1 hour for new announcements
to reach all users.
When new issues are tagged with `announcement` these entries will be parsed
and added to the RSS feeds. When the issue is closed they will be removed from
the corresponding feed. Moonlight will fetch up to 20 announcements for each
feed, if a repo goes over this limit older announcements will be removed.
/// Note
It is also possible for Moonraker to generate announcements itself. For
example, if a Moonraker component needs user feedback it may generate an
announcement and notify all connected clients. From a front-end's
perspective there is no need to treat these announcements differently than
any other announcement.
///
### Setting up the dev environment
Moonraker provides configuration to parse announcements from a local folder
so that it is possible to manually add and remove entries, allowing front-end
developers to perform integration tests:
```ini
# moonraker.conf
[announcements]
dev_mode: True
```
With `dev_mode` enabled, Moonraker will look for`moonraker.xml` and
`klipper.xml` in the following folder:
```shell
~/moonraker/.devel/announcement_xml
```
If moonraker is not installed in the home folder then substitute `~`
for the parent folder location. This folder is in a hardcoded location
to so as not to expose users to vulnerabilities associated with parsing XML.
It is possible to configure Moonraker to search for your own feeds:
```ini
# moonraker.conf
[announcements]
subscription:
my_project
dev_mode: True
```
The above configuration would look for `my_project.xml` in addition to
`klipper.xml` and `moonraker.xml`. The developer may manually create
the xml feeds or they may clone `moonlight` and leverage its script
to generate a feed from issues created on their test repo. When local
feeds have been modified one may call the [update announcements API](#update-announcements)
to have Moonraker fetch the updates and add/remove entries.
### RSS file structure
Moonlight generates RSS feeds in XML format. Below is an example generated
from moonlight's own issue tracker:
```xml
<?xml version='1.0' encoding='utf-8'?>
<rss version="2.0" xmlns:moonlight="https://arksine.github.io/moonlight">
<channel>
<title>arksine/moonlight</title>
<link>https://github.com/Arksine/moonlight</link>
<description>RSS Announcements for Moonraker</description>
<pubDate>Tue, 22 Mar 2022 23:19:04 GMT</pubDate>
<moonlight:configHash>f2912192bf0d09cf18d8b8af22b2d3501627043e5afa3ebff0e45e4794937901</moonlight:configHash>
<item>
<title>Test announcement 3</title>
<link>https://github.com/Arksine/moonlight/issues/3</link>
<description>Test Description [with a link](https://moonraker.readthedocs.io).</description>
<pubDate>Wed, 16 Mar 2022 19:33:39 GMT</pubDate>
<category>normal</category>
<guid>arksine/moonlight/issue/3</guid>
</item>
<item>
<title>Announcement Test Two</title>
<link>https://github.com/Arksine/moonlight/issues/2</link>
<description>This is a high priority announcement. This line is included in the description.</description>
<pubDate>Wed, 09 Mar 2022 19:52:59 GMT</pubDate>
<category>high</category>
<guid>arksine/moonlight/issue/2</guid>
</item>
<item>
<title>Announcement Test One</title>
<link>https://github.com/Arksine/moonlight/issues/1</link>
<description>This is the description. Anything here should appear in the announcement, up to 512 characters.</description>
<pubDate>Wed, 09 Mar 2022 19:37:58 GMT</pubDate>
<category>normal</category>
<guid>arksine/moonlight/issue/1</guid>
</item>
</channel>
</rss>
```
Each xml file may contain only one `<rss>` element, and each `<rss>` element
may contain only one channel. All items must be present aside from
`moonlight:configHash`, which is used by the workflow to detect changes to
moonlight's configuration. Most elements are self explanatory, developers will
be most interested in adding and removing `<item>` elements, as these are
the basis for entries in Moonraker's announcement database.
### Generating announcements from your own repo
As mentioned previously, its possible to clone moonlight and use its rss
script to generate announcements from issues in your repo:
```shell
cd ~
git clone https://github.com/arksine/moonlight
cd moonlight
virtualenv -p /usr/bin/python3 .venv
source .venv/bin/activate
pip install httpx[http2]
deactivate
```
To add your repo edit `~/moonlight/src/config.json`:
```json
{
"moonraker": {
"repo_owner": "Arksine",
"repo_name": "moonraker",
"description": "API Host For Klipper",
"authorized_creators": ["Arksine"]
},
"klipper": {
"repo_owner": "Klipper3d",
"repo_name": "klipper",
"description": "A 3D Printer Firmware",
"authorized_creators": ["KevinOConnor"]
},
// Add your test repo info here. It should contain
// fields matching those in "moonraker" and "klipper"
// shown above.
}
```
Once your repo is added, create one or more issues on your GitHub
repo tagged with the `announcement` label. Add the `critical` label to
one if you wish to test high priority announcements. You may need to
create these labels in your repo before they can be added.
Now we can use moonlight to generate the xml files:
```shell
cd ~/moonlight
source .venv/bin/activate
src/update_rss.py
deactivate
```
After the script has run it will generate the configured RSS feeds
and store them in `~/moonlight/assets`. If using this method it may
be useful to create a symbolic link to it in Moonraker's devel folder:
```shell
cd ~/moonraker
mkdir .devel
cd .devel
ln -s ~/moonlight/assets announcement_xml
```
If you haven't done so, configure Moonraker to subscribe to your feed
and restart the Moonraker service. Otherwise you may call the
[announcement update](#update-announcements) API to have Moonraker
parse the announcements from your test feed.
### Implementation details and recommendations
When a front-end first connects to Moonraker it is recommended that the
[list announcements](#list-announcements) API is called to retrieve
the current list of [announcement entries](#announcement-entry-spec).
If the front-end is connected via websocket it may watch for the
[announcement update](./jsonrpc_notifications.md#announcement-update-event) and
[announcement dismissed](./jsonrpc_notifications.md#announcement-dismissed-event)
JSON-RPC notifications and update its UI accordingly.
Front-end devs should decide how they want to present announcements to users.
They could be treated as any other notification, for example a front-end
may have a notification icon that shows the current number of unread
announcements. Front-ends can mark an announcement as `read` by calling
the [dismiss announcement](#dismiss-an-announcement) endpoint. Any
announcement entry with `dismissed == true` should be considered read.
When a `high priority` announcement is detected it is recommended that
clients present the announcement in a format that is immediately visible
to the user. That said, it may be wise to allow users to opt out of
this behavior via configuration.
/// note
If an announcement is dismissed, closed on GitHub, then reopened,
the `dismissed` flag will reset to false. This is expected behavior
as announcements are pruned from the database when they are no
longer present in feeds. It isn't valid for repo maintainers
to re-open a closed announcement. That said, its fine to close
and re-open issues during development and testing using repos
that are not yet registered with moonlight.
///
+635
View File
@@ -0,0 +1,635 @@
# Authorization and Authentication
The Authorization endpoints provide access to the various methods
used to authorize connections to Moonraker. This includes user
authentication, API Key authentication, Temporary access via
"oneshot tokens", and IP and/or domain based authentication
("ie: trusted clients).
Untrusted clients must use either a JSON Web Token or an API key to access
Moonraker's HTTP APIs. JWTs should be included in the `Authorization`
header as a `Bearer` type for each HTTP request. If using an API Key it
should be included in the `X-Api-Key` header for each HTTP Request.
Websocket authentication can be achieved via the request itself or
post connection. Unlike HTTP requests it is not necessary to pass a
token and/or API Key to each request. The
[identify connection](./server.md#identify-connection) endpoint takes optional
`access_token` and `api_key` parameters that may be used to authenticate
a user already logged in, otherwise the `login` API may be used for
authentication. Websocket connections will stay authenticated until
the connection is closed or the user logs out.
User authentication can be performed using a choice sources. Moonraker
currently supports the following authentication sources:
| Source Name | Description |
| ----------- | -------------------------------------------------------------- |
| `moonraker` | Authentication is performed using credentials stored in |
| | Moonraker's database. |^
| `ldap` | Authentication is performed through a connected LDAP provider. |
| | Requires a valid `[LDAP]` configuration. |^
{ #auth-source-desc } Authentication Source
/// note
ECMAScript imposes limitations on certain requests that prohibit the
developer from modifying the HTTP headers (ie: Requests to open a
websocket, "download" requests that open a user dialog). In these cases
it is recommended for the developer to request a `oneshot_token`, then
send the result via the `token` query string argument in the desired
request.
///
/// warning
It is strongly recommended that arguments for the below APIs are
passed in the request's body.
///
## Login User
```{.http .apirequest title="HTTP Request"}
POST /access/login
Content-Type: application/json
{
"username": "my_user",
"password": "my_password",
"source": "moonraker"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.login",
"params": {
"username": "my_user",
"password": "my_password",
"source": "moonraker"
},
"id": 1323
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :----: | -------------------- | --------------------------------------------------- |
| `username` | string | **REQUIRED** | The user login name. |
| `password` | string | **REQUIRED** | The user password. |
| `source` | string | Set by configuration | A valid [authentication source](#auth-source-desc). |
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNjU1LCAiZXhwIjogMTYxODg4MDQwMC40ODE2NTUsICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.QdieeEskrU0FrH7rXKuPDSZxscM54kV_vH60uJqdU9g",
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNzUxNCwgImV4cCI6IDE2MjY2NTI4MDAuNDgxNzUxNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.btJF0LJfymInhGJQ2xvPwkp2dFUqwgcw4OA_wE-EcCM",
"action": "user_logged_in",
"source": "moonraker"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------------- | :----: | -------------------------------------------------------------------- |
| `username` | string | The name of the logged in user. |
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
| | | referred to as an `access token`. HTTP requests should include this |^
| | | token in the `Authorization` header as a `Bearer` type. This token |^
| | | expires after 1 hour. |^
| `refresh_token` | string | A JWT that should be used to generate new access tokens after they |
| | | expire. See the [refresh token section](#refresh-json-web-token) |^
| | | for details. |^
| `action` | string | The action taken by the auth manager. Will always be |
| | | "user_logged_in". |^
| `source` | string | The [authentication source](#auth-source-desc) used. |
///
/// note
This endpoint may be accessed without prior authentication. A 401 will
only be returned if the authentication fails.
///
## Logout Current User
```{.http .apirequest title="HTTP Request"}
POST /access/logout
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.logout",
"id": 1323
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"action": "user_logged_out"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ----------------------------------------------------- |
| `username` | string | The name of the logged out user. |
| `action` | string | The action taken by the auth manager. Will always be |
| | | "user_logged_out". |^
///
## Get Current User
```{.http .apirequest title="HTTP Request"}
GET /access/user
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.get_user",
"id": 1323
}
```
Returns: An object containing the currently logged in user name, the source and
the date on which the user was created (in unix time).
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"source": "moonraker",
"created_on": 1618876783.8896716
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------ | :----: | ---------------------------------------------------- |
| `username` | string | The name of the logged in user. |
| `source` | string | The [source](#auth-source-desc) used to authenticate |
| | | the user. |^
| `created_on` | float | The date, in unix time, the user entry was created. |
///
## Create User
Creates a new local user and logs them in.
```{.http .apirequest title="HTTP Request"}
POST /access/user
Content-Type: application/json
{
"username": "my_user",
"password": "my_password"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.post_user",
"params": {
"username": "my_user",
"password": "my_password"
},
"id": 1323
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :----: | ------------ | -------------------- |
| `username` | string | **REQUIRED** | The user login name. |
| `password` | string | **REQUIRED** | The user password. |
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNjE5LCAiZXhwIjogMTYxODg4MDM4My44OTE2MTksICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.oH0IShTL7mdlVs4kcx3BIs_-1j0Oe-qXezJKjo-9Xgo",
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNzAyNCwgImV4cCI6IDE2MjY2NTI3ODMuODkxNzAyNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.a6ZeRjk8RQQJDDH0JV-qGY_d_HIgfI3XpsqUlUaFT7c",
"source": "moonraker",
"action": "user_created"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------------- | :----: | --------------------------------------------------------------------- |
| `username` | string | The name of the created user. |
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
| | | referred to as an `access token`. HTTP requests should include this |^
| | | token in the `Authorization` header as a `Bearer` type. This token |^
| | | expires after 1 hour. |^
| `refresh_token` | string | A JWT that should be used to generate new access tokens after they |
| | | expire. See the [refresh token section](#refresh-json-web-token) |^
| | | for details. |^
| `action` | string | The action taken by the auth manager. Will always be "user_created". |
| `source` | string | The [authentication source](#auth-source-desc) used. |
///
/// note
Unlike `/access/login`, `/access/user` is a protected endpoint. To
create a new user a client must either be trusted, use the API Key,
or be logged in as another user.
///
## Delete User
/// note
A request to delete a user MUST come from an authorized login
other than the account to be deleted. This can be a "trusted user",
the "api key user", or any other user account.
///
```{.http .apirequest title="HTTP Request"}
DELETE /access/user
Content-Type: application/json
{
"username": "my_username"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.delete_user",
"params": {
"username": "my_username"
},
"id": 1323
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :--: | ------------ | ------------------------------------ |
| `username` | str | **REQUIRED** | The username of the entry to delete. |
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"action": "user_deleted"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ------------------------------------------------- |
| `username` | string | The username of the deleted entry. |
| `action` | string | The action taken by the auth manager. Will always |
| | | be "user_deleted". |^
///
## List Available Users
```{.http .apirequest title="HTTP Request"}
GET /access/users/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.users.list",
"id": 1323
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"users": [
{
"username": "testuser",
"source": "moonraker",
"created_on": 1618771331.1685035
},
{
"username": "testuser2",
"source": "ldap",
"created_on": 1620943153.0191233
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------- | :------: | -------------------------------- |
| `users` | [object] | An array of `User Info` objects. |
| | | #user-info-spec |+
| Field | Type | Description |
| ------------ | :----: | ---------------------------------------------------- |
| `username` | string | The username of the entry. |
| `source` | string | The [source](#auth-source-desc) that must be used to |
| | | authenticate the user. |^
| `created_on` | float | The date, in unix time, the user entry was created. |
{ #user-info-spec } User Info
///
## Reset User Password
```{.http .apirequest title="HTTP Request"}
POST /access/user/password
Content-Type: application/json
{
"password": "my_current_password",
"new_password": "my_new_pass"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.user.password",
"params": {
"password": "my_current_password",
"new_password": "my_new_pass"
},
"id": 1323
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| -------------- | :----: | ------------ | ---------------------------- |
| `password` | string | **REQUIRED** | The user's current password. |
| `new_password` | string | **REQUIRED** | The user's new password. |
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"action": "user_password_reset"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | --------------------------------------------------- |
| `username` | string | The username of the entry whose password was reset. |
| `action` | string | Action taken by the Auth manager. Will always be |
| | | "user_password_reset". |^
///
## Refresh JSON Web Token
This endpoint can be used to refresh an expired access token. If this
request returns an error then the refresh token is no longer valid and
the user must login with their credentials.
```{.http .apirequest title="HTTP Request"}
POST /access/refresh_jwt
Content-Type: application/json
{
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4Nzc0ODUuNzcyMjg5OCwgImV4cCI6IDE2MjY2NTM0ODUuNzcyMjg5OCwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAicmVmcmVzaCJ9.Y5YxGuYSzwJN2WlunxlR7XNa2Y3GWK-2kt-MzHvLbP8"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.refresh_jwt",
"params": {
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4Nzc0ODUuNzcyMjg5OCwgImV4cCI6IDE2MjY2NTM0ODUuNzcyMjg5OCwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAicmVmcmVzaCJ9.Y5YxGuYSzwJN2WlunxlR7XNa2Y3GWK-2kt-MzHvLbP8"
},
"id": 1323
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| --------------- | :----: | ------------ | ------------------------------------- |
| `refresh_token` | string | **REQUIRED** | A valid `refresh_token` for the user. |
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"username": "my_user",
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzgyNDMuNTE2Nzc5MiwgImV4cCI6IDE2MTg4ODE4NDMuNTE2Nzc5MiwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.Ia_X_pf20RR4RAEXcxalZIOzOBOs2OwearWHfRnTSGU",
"source": "moonraker",
"action": "user_jwt_refresh"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | -------------------------------------------------------------------- |
| `username` | string | The username of the entry whose access token ws refreshed. |
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
| | | referred to as an `access token`. HTTP requests should include this |^
| | | token in the `Authorization` header as a `Bearer` type. This token |^
| | | expires after 1 hour. |^
| `source` | string | The [authentication source](#auth-source-desc) of the user entry. |
| `action` | string | The action taken by the Auth Manager. Will always be |
| | | "user_jwt_refresh". |^
///
/// note
This endpoint may be accessed by unauthorized clients. A 401 will
only be returned if the refresh token is invalid.
///
## Generate a Oneshot Token
Javascript is not capable of modifying the headers for some HTTP requests
(for example, the `websocket`), which is a requirement to apply JWT or API Key
authorization. To work around this clients may request a Oneshot Token and
pass it via the query string for these requests. Tokens expire in 5 seconds
and may only be used once, making them relatively safe for inclusion in the
query string.
```{.http .apirequest title="HTTP Request"}
GET /access/oneshot_token
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.oneshot_token",
"id": 1323
}
```
```{.json .apiresponse title="Example Response"}
"APDBEGHUTBUD6SOAYBPF3KE5BRMO7YSL"
```
/// api-response-spec
open: True
The response is a string value containing the oneshot token. It may
added to a request's query string for access to any API endpoint. The query
string should be added in the form of:
```
?token={base32_random_token}
```
///
## Get authorization module info
```{.http .apirequest title="HTTP Request"}
GET /access/info
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.info",
"id": 1323
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"default_source": "moonraker",
"available_sources": [
"moonraker",
"ldap"
],
"login_required": false,
"trusted": true
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------------- | :------: | ---------------------------------------------------- |
| `default_source` | string | The configured default |
| | | [authentication source](#auth-source-desc). |^
| `available_sources` | [string] | An array of available authentication sources. |
| `login_required` | bool | Set to `true` when `force_logins` is enabled via the |
| | | configuration at least one user has been created. |^
| `trusted` | bool | Set to `true` when the connection making the info |
| | | request is a trusted connection. |^
///
/// note
This endpoint may be accessed by unauthorized clients.
///
## Get the Current API Key
```{.http .apirequest title="HTTP Request"}
GET /access/api_key
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.get_api_key",
"id": 1323
}
```
```{.json .apiresponse title="Example Response"}
e514851f37b94c779d955212b6906f95
```
/// api-response-spec
open: True
The response string value containing the current API key.
///
## Generate a New API Key
```{.http .apirequest title="HTTP Request"}
POST /access/api_key
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "access.post_api_key",
"id": 1323
}
```
```{.json .apiresponse title="Example Response"}
e514851f37b94c779d955212b6906f95
```
/// api-response-spec
open: True
The response string value containing the new API key.
///
/// note
After this request executes the API key change is applied immediately.
All subsequent HTTP requests from untrusted clients must use the new key.
Changing the API Key will not affect open websockets authenticated using
the previous API Key.
///
+773
View File
@@ -0,0 +1,773 @@
# Database Management
The following endpoints provide access to Moonraker's internal sqlite database.
The primary table exposed to clients is divided into `namespaces`. Each client
may define its own namespace to store information. From the client's point of
view, a namespace is an `object`. Items in the database are accessed by providing
a namespace and a key. A key may be specified as string, where a "." is a
delimiter to access nested fields. Alternatively the key may be specified
as an array of strings, where each string references a nested field.
This is useful for scenarios where a namespace contains fields that include
a "." character, such as a file name.
/// note
Moonraker reserves several namespaces for internal use. Clients may read from
these namespaces but they may not modify them.
///
For example, assume the following object is stored in the "superclient"
namespace:
```json
{
"settings": {
"console": {
"enable_autocomplete": true
}
},
"theme": {
"background_color": "black"
}
}
```
One may access the `enable_autocomplete` field by supplying `superclient` as
the `namespace` argument and `settings.console.enable_autocomplete` or
`["settings", "console", "enable_autocomplete"]` as the `key` argument for
the request. The entire settings object could be accessed by providing
`settings` or `["settings"]` as the `key` argument. The entire namespace
may be read by omitting the `key` argument, however as explained below it
is not possible to modify a namespace without specifying a key.
## List Database Info
Lists all namespaces with read and/or write access. Also lists database
backup files.
```{.http .apirequest title="HTTP Request"}
GET /server/database/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.list",
"id": 8694
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"namespaces": [
"gcode_metadata",
"webcams",
"update_manager",
"announcements",
"database",
"moonraker"
],
"backups": [
"sqldb-backup-20240513-134542.db",
"testbackup.db",
"testbackup2.db"
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------ | :------: | ---------------------------------------------------- |
| `namespaces` | [string] | An array of namespaces registered with the database |
| | | that may be read by clients. |^
| `backups` | [string] | An array of database backup filenames that have been |
| | | created. |^
///
## Get Database Item
Retrieves an item from a specified namespace. The `key` argument may be
omitted, in which case an object representing the entire namespace will
be returned in the `value` field. If the `key` is provided and does not
exist in the database an error will be returned.
```{.http .apirequest title="HTTP Request"}
GET /server/database/item?namespace={namespace}&key={key}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.get_item",
"params": {
"namespace": "{namespace}",
"key": "{key}"
},
"id": 5644
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :----------------: | ------------ | ------------------------------------------ |
| `namespace` | string | **REQUIRED** | The namespace of the item to retrieve. |
| `key` | string \| [string] | null | The key indicating the field or fields |
| | \| null | | within the namespace to retrieve. May |^
| | | | be a string, where nested fields are |^
| | | | separated by a ".", or a list of strings. |^
| | | | If the key is omitted the entire namespace |^
| | | | will be returned. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"namespace": "moonraker",
"key": "file_manager.metadata_version",
"value": 2
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ----------- | :----------------: | ------------------------------------------------- |
| `namespace` | string | The namespace of the returned item. |
| `key` | string \| [string] | The key indicating the requested field(s). |
| | \| null | |^
| `value` | any | The value of the requested item. This can be any |
| | | valid JSON type. |^
///
## Add Database Item
Inserts an item into the database. If the `namespace` does not exist
it will be created. If the `key` specifies a nested field, all parents
will be created if they do not exist. If the key exists it will be
overwritten with the provided `value`. The `key` parameter must be provided,
as it is not possible to assign a value directly to a namespace.
/// note
If the request parameters are placed in the query string and the `value`
is not a string type, then `value` argument must provide a
[type hint](./introduction.md#query-string-type-hints). It is strongly
recommended to put parameters in the body of the request wrapped in a
JSON object.
///
```{.http .apirequest title="HTTP Request"}
POST /server/database/item
Content-Type: application/json
{
"namespace": "my_client",
"key": "settings.some_count",
"value": 100
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :----------------: | ------------ | ----------------------------------------- |
| `namespace` | string | **REQUIRED** | The namespace where the value |
| | | | should be inserted. |^
| `key` | string \| [string] | **REQUIRED** | The key indicating the field or fields |
| | | | where the value should be inserted. |^
| `value` | any | **REQUIRED** | The value to insert in the database. May |
| | | | be any valid JSON type. |^
///
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.post_item",
"params": {
"namespace": "{namespace}",
"key": "{key}",
"value": 100
},
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"namespace": "test",
"key": "settings.some_count",
"value": 9001
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ----------- | :----------------: | ------------------------------------------- |
| `namespace` | string | The namespace where the value was inserted. |
| `key` | string \| [string] | The key indicating the field or fields |
| | | where the value was inserted. |^
| `value` | any | The value inserted into the database. May |
| | | be any valid JSON type. |^
///
## Delete Database Item
Deletes an item from a `namespace` at the specified `key`. If the key does not
exist in the namespace an error will be returned. If the deleted item results
in an empty namespace, the namespace will be removed from the database.
```{.http .apirequest title="HTTP Request"}
DELETE /server/database/item?namespace={namespace}&key={key}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.delete_item",
"params": {
"namespace": "{namespace}",
"key": "{key}"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :----------------: | ------------ | -------------------------------------- |
| `namespace` | string | **REQUIRED** | The namespace where the item should be |
| | | | should be removed. |^
| `key` | string \| [string] | **REQUIRED** | The key indicating the field or fields |
| | | | where the item should be removed. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"namespace": "test",
"key": "settings.some_count",
"value": 9001
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ----------- | :----------------: | ------------------------------------------ |
| `namespace` | string | The namespace containing the item removed. |
| `key` | string \| [string] | The key indicating the field or fields |
| | | where the item was removed. |^
| `value` | any | The of the item at the removed field. May |
| | | be any valid JSON type. |^
///
## Compact Database
Compacts and defragments the the sqlite database using the `VACUUM` command.
This endpoint cannot be requested when Klipper is printing.
```{.http .apirequest title="HTTP Request"}
POST /server/database/compact
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.compact",
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"previous_size": 139264,
"new_size": 122880
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------------- | :--: | -------------------------------------------------- |
| `previous_size` | int | Size in bytes of the database prior to compaction. |
| `new_size` | int | Size in bytes of the database after compaction. |
///
## Backup Database
Creates a backup of the current database. The backup will be
created in the `<data_path>/backup/database/<filename>`.
This API cannot be requested when Klipper is printing.
```{.http .apirequest title="HTTP Request"}
POST /server/database/backup
Content-Type: application/json
{
"filename": "sql-db-backup.db"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.post_backup",
"params": {
"filename": "sql-db-backup.db"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :----: | -------------------------- | -------------------------- |
| `filename` | string | sqldb-backup-{timespec}.db | The file name of the saved |
| | | | backup file. |^
//// note
The `{timespec}` of the default `filename` is in the following format:
`<year><month><day>-<hour><minute><second>`
////
///
```{.json .apiresponse title="Example Response"}
{
"backup_path": "/home/test/printer_data/backup/database/sql-db-backup.db"
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| ------------- | :----: | ------------------------------------------------------ |
| `backup_path` | string | The complete absolute path where the backup was saved. |
///
## Delete a backup
Deletes a previously backed up database.
```{.http .apirequest title="HTTP Request"}
DELETE /server/database/backup?filename=sql-db-backup.db
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.delete_backup",
"params": {
"filename": "sql-db-backup.db"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :----: | ------------ | ---------------------------------------------- |
| `filename` | string | **REQUIRED** | The name of the backup file to delete. Must be |
| | | | a valid filename reported by the |^
| | | | [database list endpoint](#list-database-info). |^
///
```{.json .apiresponse title="Example Response"}
{
"backup_path": "/home/test/printer_data/backup/database/sql-db-backup.db"
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| ------------- | :----: | -------------------------------------------------------- |
| `backup_path` | string | The complete absolute path where the backup was removed. |
///
## Restore Database
Restores a previously backed up sqlite database file. The backup
must be located at `<data_path>/backup/database/<filename>`. The
`<filename>` must be a valid filename reported in by the
[database list](#list-database-info) API.
This API cannot be requested when Klipper is printing.
/// Note
Moonraker will restart immediately after this request is processed.
///
```{.http .apirequest title="HTTP Request"}
POST /server/database/restore
Content-Type: application/json
{
"filename": "sql-db-backup.db"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.database.restore",
"params": {
"filename": "sql-db-backup.db"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ---------- | :----: | ------------ | ----------------------------------------------- |
| `filename` | string | **REQUIRED** | The name of the backup file to restore. Must be |
| | | | a valid filename reported by the |^
| | | | [database list endpoint](#list-database-info). |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"restored_tables": [
"table_registry",
"namespace_store",
"authorized_users",
"job_history",
"job_totals"
],
"restored_namespaces": [
"database",
"fluidd",
"gcode_metadata",
"mainsail",
"moonraker",
"update_manager",
"webcams"
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------------------- | :------: | ------------------------------------------- |
| `restored_tables` | [string] | An array of table names that were recovered |
| | | after the restore operation. |^
| `restored_namespaces` | [string] | An array of namespaces that were recovered |
| | | after the restore operation. |^
///
## Debug endpoints
Below are a number of debug endpoints available when Moonraker has been
launched with [debug features enabled](../installation.md#command-line-usage).
Front ends should not rely on these endpoints in production releases, however
they may be useful during development. Developers writing extensions and/or
additions to Moonraker may also find these endpoints useful.
/// Warning
Debug endpoints may expose security vulnerabilities. They should only be
enabled by developers on secured machines.
///
### List Database Info (debug)
Debug version of the [List Database Info](#list-database-info) endpoint.
Returns all namespaces, including those exclusively reserved for Moonraker.
In addition all registered SQL tables are reported.
```{.http .apirequest title="HTTP Request"}
GET /debug/database/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "debug.database.list",
"id": 8694
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"namespaces": [
"gcode_metadata",
"webcams",
"update_manager",
"announcements",
"database",
"moonraker"
],
"backups": [
"sqldb-backup-20240513-134542.db",
"testbackup.db",
"testbackup2.db"
],
"tables": [
"job_history",
"job_totals",
"namespace_store",
"table_registry",
"authorized_users"
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------ | :------: | -------------------------------------------------------- |
| `namespaces` | [string] | An array of all namespaces registered with the database. |
| `backups` | [string] | An array of database backup filenames that have been |
| | | created. |^
| `tables` | [string] | An array of tables created within the database. |
///
### Get Database Item (debug)
Debug version of the [Get Database Item](#get-database-item) endpoint.
Keys within protected and forbidden namespaces may be read.
```http title="HTTP Request"
GET /debug/database/item?namespace={namespace}&key={key}
```
```json title="JSON-RPC Request"
{
"jsonrpc": "2.0",
"method": "debug.database.get_item",
"params": {
"namespace": "{namespace}",
"key": "{key}"
},
"id": 5644
}
```
See the [Get Database Item](#get-database-item) endpoint for the
`Parameter Specification`, `Example Response`, and `Response Specification`.
### Add Database Item (debug)
Debug version of the [Add Database Item](#add-database-item) endpoint.
Keys within protected and forbidden namespaces may be inserted.
/// Warning
Modifying protected namespaces outside of Moonraker can result in
broken functionality and is not supported for production environments.
Issues opened with reports/queries related to this endpoint will be
redirected to this documentation and closed.
///
```{.http .apirequest title="HTTP Request"}
POST /debug/database/item
Content-Type: application/json
{
"namespace": "my_client",
"key": "settings.some_count",
"value": 100
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "debug.database.post_item",
"params": {
"namespace": "{namespace}",
"key": "{key}",
"value": 100
},
"id": 4654
}
```
See the [Add Database Item](#add-database-item) endpoint for the
`Parameter Specification`, `Example Response`, and `Response Specification`.
### Delete Database Item (debug)
Debug version of [Delete Database Item](#delete-database-item). Keys within
protected and forbidden namespaces may be removed.
/// Warning
Modifying protected namespaces outside of Moonraker can result in
broken functionality and is not supported for production environments.
Issues opened with reports/queries related to this endpoint will be
redirected to this documentation and closed.
///
```{.http .apirequest title="HTTP Request"}
DELETE /debug/database/item?namespace={namespace}&key={key}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "debug.database.delete_item",
"params": {
"namespace": "{namespace}",
"key": "{key}"
},
"id": 4654
}
```
See the [Delete Database Item](#delete-database-item) endpoint for the
`Parameter Specification`, `Example Response`, and `Response Specification`.
### Get Database Table
Requests all the contents of a specified table.
```{.http .apirequest title="HTTP Request"}
GET /debug/database/table?table=job_history
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "debug.database.table",
"params": {
"table": "job_history"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------- | :----: | ------------ | --------------------------------- |
| `table` | string | **REQUIRED** | The name of the table to request. |
///
Returns:
An object with the table's name and a list of all rows contained
within the table. The `rowid` will always be included for each
row, however it may be represented by an alias. In the example
below the alias for `rowid` is `job_id`.
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"table_name": "job_history",
"rows": [
{
"job_id": 1,
"user": "No User",
"filename": "active_test.gcode",
"status": "completed",
"start_time": 1690749153.2661753,
"end_time": 1690749173.076986,
"print_duration": 0.0,
"total_duration": 19.975574419135228,
"filament_used": 0.0,
"metadata": {
"size": 211,
"modified": 1635771217.0,
"uuid": "627371e0-faa5-4ced-8bb4-7017d29226fa",
"slicer": "Unknown",
"gcode_start_byte": 8,
"gcode_end_byte": 211
},
"auxiliary_data": [],
"instance_id": "default"
},
{
"job_id": 2,
"user": "No User",
"filename": "active_test.gcode",
"status": "completed",
"start_time": 1701262034.9242446,
"end_time": 1701262054.7332363,
"print_duration": 0.0,
"total_duration": 19.990913168992847,
"filament_used": 0.0,
"metadata": {
"size": 211,
"modified": 1635771217.0,
"uuid": "627371e0-faa5-4ced-8bb4-7017d29226fa",
"slicer": "Unknown",
"gcode_start_byte": 8,
"gcode_end_byte": 211
},
"auxiliary_data": {
"spool_ids": [
2
]
},
"instance_id": "default"
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------ | :------: | -------------------------------------------------- |
| `table_name` | string | The name of the table requested. |
| `rows` | [object] | An array of row objects. The fields for each |
| | | object are columns defined by the table schema. |^
| | | The `rowid` will always be included for each row, |^
| | | however it may be represented by an alias. In the |^
| | | example above, `job_id` is an alias for `rowid`. |^
///
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
# Extensions
Moonraker has limited support for 3rd party extensions through the
use of its API. Extensions must establish a Websocket or Unix Socket
connection and [identify](./server.md#identify-connection) themselves
as an `agent`.
The endpoints in this section can be broken down into two categories:
- Endpoints used by Front Ends and other clients to manage and manipulate
extensions.
- Endpoints specific to agents that provide functional enhancements not
available to other client types.
## Extension Management
### List Extensions
Returns a list of all available extensions. Currently Moonraker can only
be officially extended through connected `agents`.
```{.http .apirequest title="HTTP Request"}
GET /server/extensions/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.extensions.list",
"id": 4564
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"agents": [
{
"name": "moonagent",
"version": "0.0.1",
"type": "agent",
"url": "https://github.com/arksine/moontest"
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :------: | --------------------------------------------------- |
| `agents` | [object] | An array of [Agent Info](#agent-info-spec) objects. |
| Field | Type | Description |
| --------- | :----: | -------------------------------------------------- |
| `name` | string | The name provided by the registered agent. |
| `version` | string | The version of the software reported by the agent. |
| `type` | string | The client type. Will always be `agent`. |
| `url` | string | A url to the agent software's webpage. |
{ #agent-info-spec } Agent Info
///
### Call an extension method
This endpoint may be used to call a method on a connected agent.
The request effectively relays a JSON-RPC request from a front end
or other client to the agent. Agents should document their
available methods so Moonraker client developers can interact
with them.
```{.http .apirequest title="HTTP Request"}
POST /server/extensions/request
Content-Type: application/json
{
"agent": "moonagent",
"method": "moontest.hello_world",
"arguments": {"argone": true, "argtwo": 9000}
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.extensions.request",
"params":{
"agent": "moonagent",
"method": "moontest.hello_world",
"arguments": {"argone": true, "argtwo": 9000}
},
"id": 4564
}
```
Parameters:
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :-------------: | ------------ | -------------------------------- |
| `agent` | string | **REQUIRED** | The name of the registered agent |
| | | | hosting the requested method. |^
| `method` | string | **REQUIRED** | The name of the method to call. |
| `arguments` | array \| object | null | The arguments to send with the |
| | | | method. This may be an array |^
| | | | containing positional arguments |^
| | | | or an object containing keyword |^
| | | | arguments. A value of `null` |^
| | | | will omit arguments from the |^
| | | | request. |^
///
/// api-response-spec
open: True
The result received from the agent will be returned directly. See
the agent's documentation for response specifications
///
## Agent specific endpoints
/// Note
These endpoints are only available to connections that have
identified themselves as an `agent` type.
///
### Send an agent event
Sends a [JSON-RPC notification](./jsonrpc_notifications.md#agent-events)
containing the supplied event info to all of Moonraker's persistent
connections.
```{.http .apirequest title="HTTP Request"}
Not Available
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "connection.send_event",
"params":{
"event": "my_event",
"data": {"my_arg": "optional data"}
}
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------- | :----: | ------------ | -------------------------------------------- |
| `event` | string | **REQUIRED** | The name of the event. This may be any |
| | | | name other than those reserved by Moonraker. |^
| `data` | any | undefined | The data to send with the event. This can be |
| | | | any valid JSON decodable value. If omitted |^
| | | | no data is sent with the event. |^
//// Note
The `connected` and `disconnected` events are reserved for use
by Moonraker and may not be sent from agents.
////
///
```{.apiresponse title="Response when JSON-RPC 'id' present"}
ok
```
/// note
An agent may send an event without specifying the JSON-RPC `id` field.
In this case Moonraker will not return a response.
///
### Register a method with Klipper
Registers a "remote method" with Klipper that can be called
from GCode Macros.
```{.http .apirequest title="HTTP Request"}
Not Available
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "connection.register_remote_method",
"params": {
"method_name": "firemon_alert_heated"
}
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------------- | :----: | ------------ | --------------------------------------------- |
| `method_name` | string | **REQUIRED** | The name of the remote method to register |
| | | | with Klipper. It is recommended for agents |^
| | | | to use a unique identifier, such as a prefix, |^
| | | | to prevent collisions with other remote |^
| | | | methods registered with Klipper. |^
///
```{.apiresponse title= Response"}
ok
```
/// Note
Methods registered by agents will persist until the agent disconnects.
Upon connection it is only necessary that they register their desired
methods once.
///
#### Remote Method Example
Presume an application named `firemon` has connected to Moonraker's websocket
and identified itself as an `agent`. After identification it registers a
remote method named `firemon_alert_heated` using the JSON-RPC request
example above.
In addition, the user has following `gcode_macro` configured in `printer.cfg`:
```ini
# printer.cfg
[gcode_macro ALERT_HEATED]
gcode:
{% if not params %}
{action_call_remote_method("firemon_alert_heated")}
{% else %}
{% set htr = params.HEATER|default("unknown") %}
{% set tmp = params.TEMP|default(0)|float %}
{action_call_remote_method(
"firemon_alert_heated", heater=htr, temp=tmp)}
{% endif %}
```
When the `ALERT_HEATED HEATER=extruder TEMP=200` gcode is executed by Klipper,
the agent will receive the following JSON-RPC request from Moonraker:
```{.json .apiresponse title="Remote Method Call"}
{
"jsonrpc": "2.0",
"method": "firemon_alert_heated",
"params": {
"heater": "extruder",
"temp": 200
}
}
```
When the `ALERT_HEATED` gcode is executed with no parameters, the agent will
receive the following JSON-RPC request from Moonraker:
```{.json .apiresponse title="Remote Method Call"}
{
"jsonrpc": "2.0",
"method": "monitor_alert_heated"
}
```
/// Note
Remote methods called from Klipper never contain the JSON-RPC "id" field,
as Klipper does not accept return values to remote methods.
///
File diff suppressed because it is too large. Load diff
+452
View File
@@ -0,0 +1,452 @@
# Job History
Moonraker's `history` component tracks print job completion data.
The following endpoints are available to manage Moonraker's job
history data.
## Get job list
```{.http .apirequest title="HTTP Request"}
GET /server/history/list?limit=50&start=50&since=1&before=5&order=asc
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.history.list",
"params":{
"limit": 50,
"start": 10,
"since": 464.54,
"before": 1322.54,
"order": "asc"
},
"id": 5656
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| -------- | :----: | --------- | ----------------------------------------------- |
| `limit` | int | 50 | Maximum number of job entries to return. |
| `start` | int | 0 | The record number indicating the first entry |
| | | | of the returned list. |^
| `before` | float | undefined | A timestamp in unix time. When specified, the |
| | | | returned list will only contain entries created |^
| | | | before this date. |^
| `since` | float | undefined | A timestamp in unix time. When specified, the |
| | | | returned list will only contain entries created |^
| | | | after this date. |^
| `order` | string | "desc" | The order of the list returned. May be `asc` |
| | | | (ascending) or `desc` (descending). |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"count": 1,
"jobs": [
{
"job_id": "000001",
"exists": true,
"end_time": 1615764265.6493807,
"filament_used": 7.83,
"filename": "test/history_test.gcode",
"metadata": {
// Object containing metadata at time of job
},
"print_duration": 18.37201827496756,
"status": "completed",
"start_time": 1615764496.622146,
"total_duration": 18.37201827496756,
"user": "testuser",
"auxiliary_data": [
{
"provider": "sensor hist_test",
"name": "power_consumption",
"value": 4.119977,
"description": "Printer Power Consumption",
"units": "kWh"
},
{
"provider": "sensor hist_test",
"name": "max_current",
"value": 2.768851,
"description": "Maximum current draw",
"units": "A"
},
{
"provider": "sensor hist_test",
"name": "min_current",
"value": 0.426725,
"description": "Minimum current draw",
"units": "A"
},
{
"provider": "sensor hist_test",
"name": "avg_current",
"value": 1.706872,
"description": "Average current draw",
"units": "A"
},
{
"provider": "sensor hist_test",
"name": "status",
"value": 2,
"description": "Power Switch Status",
"units": null
},
{
"provider": "sensor hist_test",
"name": "filament",
"value": 19.08058495194607,
"description": "filament usage tracker",
"units": "mm"
},
{
"provider": "spoolman",
"name": "spool_ids",
"value": [
1
],
"description": "Spool IDs used",
"units": null
}
]
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------- | :------: | -------------------------------------------------- |
| `count` | int | The number of entries returned by the query. |
| `jobs` | [object] | An array of [Job History](#job-history-entry-spec) |
| | | objects. |^
| Field | Type | Description |
| ---------------- | :------------: | ----------------------------------------------------------- |
| `job_id` | string | A unique ID for the entry. |
| `user` | string \| null | The user that started the job. Will be `null` |
| | | if Moonraker cannot identify a user (ie: job) |^
| | | was started via Klipper's display. |^
| `filename` | string | The path, relative to `gcodes` root, of the file |
| | | associated with the job. |^
| `exists` | bool | A value of `true` indicates that the file |
| | | associated with the job exists on disk and has |^
| | | not been modified. |^
| `status` | string | The [job status](#job-history-status-desc) |
| | | at the time of query. |^
| `start_time` | float | A timestamp, in unix time, indicating when |
| | | the job started. |^
| `end_time` | float \| null | A timestamp, in unix time, indicating when |
| | | the job finished. Will be `null` if the |^
| | | job is in progress or if Moonraker is |^
| | | interrupted prior to the job completion. |^
| `print_duration` | float | The amount of time, in seconds, the job |
| | | spent printing (ie: printer not idle). |^
| `total_duration` | float | The total amount of time, in seconds, the |
| | | job took to print. This includes time paused. |^
| `filament_used` | float | The amount of filament (in mm) used during the job. |
| `metadata` | object | The [gcode metadata](./file_manager.md#gcode-metadata-spec) |
| | | object associated with the job. The `job_id` and |^
| | | `print_start_time` fields are removed from the metadata as |^
| | | they are redundant. |^
| `auxiliary_data` | [object] | An array of [auxiliary field](#job-history-aux-field-spec) |
| | | objects containing supplemental history data related to |^
| | | the job. |^
{ #job-history-entry-spec } Job History
| Field | Type | Description |
| ------------- | :------------: | ------------------------------------------------- |
| `provider` | string | The component or extension that generated the |
| | | auxiliary field. |^
| `name` | string | A name identifying the field. |
| `description` | string | A brief description of the data in this entry. |
| `value` | any | The value associated with the field. Can be any |
| | | valid JSON type. |^
| `units` | string \| null | The unit type associated with the value. For |
| | | example this would be `mm` for millimeters. Can |^
| | | be `null` if no unit abbreviation is appropriate. |^
{ #job-history-aux-field-spec } Auxiliary Field
| Status | Description |
| ------------------- | ----------------------------------------------------- |
| `in_progress` | The job is currently active. |
| `completed` | The job successfully completed. |
| `cancelled` | The job was cancelled by the user. |
| `error` | The job was aborted due to an error during execution. |
| `klippy_shutdown` | The job was aborted due to Klippy Shutdown. |
| `klippy_disconnect` | Moonraker's connection to Klippy was lost while the |
| | job was in progress. |^
| `interrupted` | Moonraker was abruptly terminated while the job was |
| | in progress. |^
{ #job-history-status-desc } Job Status
///
## Get job totals
```{.http .apirequest title="HTTP Request"}
GET /server/history/totals
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.history.totals",
"id": 5656
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"job_totals": {
"total_jobs": 3,
"total_time": 11748.077333278954,
"total_print_time": 11348.794790096988,
"total_filament_used": 11615.718840001999,
"longest_job": 11665.191012736992,
"longest_print": 11348.794790096988
},
"auxiliary_totals": [
{
"provider": "sensor hist_test",
"field": "power_consumption",
"maximum": 4.119977,
"total": 4.119977
},
{
"provider": "sensor hist_test",
"field": "avg_current",
"maximum": 1.706872,
"total": null
},
{
"provider": "sensor hist_test",
"field": "filament",
"maximum": 19.08058495194607,
"total": 19.08058495194607
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------------ | :------: | ----------------------------------------------- |
| `job_totals` | object | A [Job Totals](#job-history-totals-spec) object |
| | | reporting all current totals. |^
| `auxiliary_totals` | [object] | An array of |
| | | [Auxiliary Total](#job-auxiliary-totals-spec) |^
| | | objects. |^
| Field | Type | Description |
| --------------------- | :------: | ------------------------------------------------------ |
| `total_jobs` | int | The total number of jobs tracked. |
| `total_time` | float | The total amount of job work time (in seconds) |
| | | across all jobs, including time paused. |^
| `total_print_time` | float | The total amount of time printing (in seconds) |
| | | across all jobs. |^
| `total_filament_used` | float | The total amount of filament used (in mm) across |
| | | all jobs. |^
| `longest_job` | float | The maximum time spent working on a single job, |
| | | including time paused. |^
| `longest_print` | float | The maximum time spent printing a single job. |
| `auxiliary_totals` | [object] | An array of |
| | | [Auxiliary Total](#job-auxiliary-totals-spec) objects. |^
{ #job-history-totals-spec } Job Totals
| Field | Type | Description |
| ---------- | :-----------: | ----------------------------------------------- |
| `provider` | string | The component or extension that generated the |
| | | auxiliary totals. |^
| `field` | string | The corresponding `name` of the auxiliary field |
| | | used to generate totals. |^
| `maximum` | float \| null | The maximum value observed across all prints. |
| | | Will be `null` if the maximum is not available. |^
| `total` | float \| null | The accumulated total value across all prints. |
| | | Will be `null` if the total is not available. |^
{ #job-auxiliary-totals-spec } Auxiliary Total
///
## Reset totals
Resets the persistent "job totals" to zero.
```{.http .apirequest title="HTTP Request"}
POST /server/history/reset_totals
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.history.reset_totals",
"id": 5534
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"last_totals": {
"total_jobs": 3,
"total_time": 11748.077333278954,
"total_print_time": 11348.794790096988,
"total_filament_used": 11615.718840001999,
"longest_job": 11665.191012736992,
"longest_print": 11348.794790096988
},
"last_auxiliary_totals": [
{
"provider": "sensor hist_test",
"field": "power_consumption",
"maximum": 4.119977,
"total": 4.119977
},
{
"provider": "sensor hist_test",
"field": "avg_current",
"maximum": 1.706872,
"total": null
},
{
"provider": "sensor hist_test",
"field": "filament",
"maximum": 19.08058495194607,
"total": 19.08058495194607
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ----------------------- | :------: | ----------------------------------------------- |
| `last_totals` | object | A [Job Totals](#job-history-totals-spec) object |
| | | reporting all totals prior to the reset. |^
| `last_auxiliary_totals` | [object] | An array of |
| | | [Auxiliary Total](#job-auxiliary-totals-spec) |^
| | | objects reporting totals prior to the reset. |^
///
## Get a single job
```{.http .apirequest title="HTTP Request"}
GET /server/history/job?uid=<id>
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.history.get_job",
"params":{"uid": "{uid}"},
"id": 4564
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----- | :----: | ------------ | --------------------------------------- |
| `uid` | string | **REQUIRED** | The unique identifier for the requested |
| | | | job history. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"job": {
"job_id": "000001",
"exists": true,
"end_time": 1615764265.6493807,
"filament_used": 7.83,
"filename": "test/history_test.gcode",
"metadata": {
// Object containing metadata at time of job
},
"print_duration": 18.37201827496756,
"status": "completed",
"start_time": 1615764496.622146,
"total_duration": 18.37201827496756
}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ----- | :----: | ------------------------------------------------------------- |
| `job` | object | The requested [Job History](#job-history-entry-spec ) object. |
///
## Delete a job
```{.http .apirequest title="HTTP Request"}
DELETE /server/history/job?uid=<id>
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.history.delete_job",
"params":{
"uid": "{uid}"
},
"id": 5534
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----- | :----: | --------------- | ------------------------------------------ |
| `uid` | string | **REQUIRED** | The unique identifier for the job entry |
| | | if `all==false` | to delete. |^
| `all` | bool | false | When set to `true` all job history entries |
| | | | will be removed. |^
//// tip
If `all = true` is specified the `uid` parameter should be omitted.
////
///
```{.json .apiresponse title="Example Response"}
{
"deleted_jobs": [
"000000",
"000001"
]
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| -------------- | :------: | ------------------------------------- |
| `deleted_jobs` | [string] | An array of unique IDs indicating the |
| | | job entries that were deleted. |^
///
File diff suppressed because it is too large. Load diff
+510
View File
@@ -0,0 +1,510 @@
# Introduction
Moonraker provides APIs over two protocols, HTTP and JSON-RPC. Most
endpoints have corresponding APIs over both protocols. When requests
are exclusive to a protocol or depend on some other condition it will
be noted in the documentation for that specific API.
At a high level, file transfer requests (upload and download) are exclusive
to the HTTP API. The Websocket is required to receive events such as status
updates and gcode responses. For information on how to set up the Websocket,
please see the [Miscellaneous Tutorials](#websocket-setup).
## HTTP API Overview
Moonraker's HTTP API could be described as "REST-ish". Attempts are made to
conform to REST standards, however the dynamic nature of Moonraker's endpoint
registration along with the need to keep consistency between two API protocols
results in an HTTP API that deviates
Moonraker is capable of parsing request arguments from the both the body
(either JSON or form-data depending on the `Content-Type` header) and from
the query string. All arguments are grouped together in one data structure,
with body arguments taking precedence over query arguments. Thus
if the same argument is supplied both in the body and in the
query string the body argument would be used. It is left up to the front end
developer to decide exactly how they want to provide arguments.
Nearly all successful HTTP requests will return a json encoded object in
the form of:
```text
{
"result": <response data>
}
```
The response data may be any valid JSON type. In most cases it will be
a JSON object itself, but some requests may return a simple string.
If the response is not wrapped in an object with a `result` field it will
be noted in the documentation for that API (or API set). Generally this
only applies to endpoints that attempt to emulate other backends.
Should a request result in an error, a standard error code along with
an error specific message is returned, wrapped in a JSON object.
### Query string type hints
By default all arguments passed via the query string are represented as
strings. Most endpoint handlers know the data type for each of their
arguments, thus they can perform conversion from a string type if necessary.
However some endpoints accept arguments of a "generic" type, thus the
client is responsible for specifying the type if "string" is not desirable.
This is not a problem for websocket requests as the JSON parser can extract
the appropriate type. HTTP requests must provide "type hints" in these
scenarios. Moonraker supplies support for the following query string type hints:
- int
- bool
- float
- json
The `json` type hint can be specified to pass an array or an object via
the query string. Remember to percent encode the json string so that
the query string is correctly parsed.
Type hints may be specified by post-fixing them to a key, with a ":"
separating the key and the hint. For example, lets assume that we
have a request that takes `seconds` (integer) and `enabled` (boolean)
arguments. The query string with type hints might look like:
```
?seconds:int=120&enabled:bool=true
```
A query string that takes a `value` argument with which we want to
pass an object, `{foo: 21.5, bar: "hello"}` might look like:
```
?value:json=%7B%22foo%22%3A21.5%2C%22bar%22%3A%22hello%22%7D
```
As you can see, a percent encoded json string is not human readable,
thus using this functionality should be seen as a "last resort." If at
all possible clients should attempt to put these arguments in the body
of a request.
## JSON-RPC API Overview
Websocket, Unix Socket, and MQTT connections exclusively use the API
available over [JSON-RPC 2.0](https://jsonrpc.org). In addition, Moonraker
provides an [JSON-RPC HTTP endpoint](#json-rpc-over-http-endpoint) giving
developers who want to avoid persistent connections a choice to use JSON-RPC.
The Websocket transmits and receives JSON-RPC objects in text frames. MQTT
transmits them in the payload of a topic defined when MQTT is configured. By
default, Moonraker receives JSON-RPC requests from the
`{instance_name}/moonraker/api/request` topic, and publishes responses to the
`{instance_name}/moonraker/api/response` topic. The `{instance_name}` must be
a unique identifier for each instance of Moonraker connected to the broker.
It defaults to the machine's host name.
An encoded request should look something like:
```json
{
"jsonrpc": "2.0",
"method": "API method",
"params": {"arg_one": 1, "arg_two": true},
"id": 354
}
```
The `params` field may be left out if the API request takes no arguments.
The `id` should be a unique value that has no chance of colliding
with other JSON-RPC requests. The `method` is the API method, as defined
for each API in this document.
/// details | Optional MQTT timestamp
type: tip
MQTT requests may provide an optional `mqtt_timestamp` keyword
argument in the `params` field of the JSON-RPC request. To avoid
potential collisions from time drift it is recommended to specify
the timestamp in microseconds since the Unix Epoch. If provided
Moonraker will use the timestamp to discard duplicate requests.
It is recommended to either provide a timestamp or publish API
requests at a QoS level of 0 or 2.
///
A successful request will return a response like the following:
```json
{
"jsonrpc": "2.0",
"result": {"res_data": "success"},
"id": 354
}
```
The `result` will generally contain an object, but as with the HTTP API in some
cases it may simply return a string. The `id` field will return an id that
matches the one provided by the request.
Requests that result in an error will receive a properly formatted
JSON-RPC response:
```json
{
"jsonrpc": "2.0",
"error": {"code": 36000, "message": "Error Message"},
"id": 354
}
```
Some errors may not return a request ID, such as an improperly formatted request.
The [moontest](https://www.github.com/arksine/moontest) repo includes a basic
test interface with example usage for most of the requests below. It also
includes a basic JSON-RPC implementation that uses promises to return responses
and errors (see json-rpc.js).
## Websocket Connections
### Primary websocket
The primary websocket supports Moonraker's JSON-RPC API. Most applications that
desire a websocket connection will make use of the primary websocket.
The primary websocket is available at:
```
ws://host_or_ip:port/websocket`
```
The primary websocket will remain connected until the application disconnects
or Moonraker is shutdown.
### Bridge websocket
The "bridge" websocket provides a near direct passthrough to Klipper's API
Server. Klipper uses its own RPC protocol, which is effectively a simplified
version of the JSON-RPC specification. Developers should refer to
[Klipper's API documentation](https://www.klipper3d.org/API_Server.html)
for details on the protocol and available APIs.
!!! Note
The bridge websocket is described as "near direct passthrough" because
Moonraker handles the ETX (`0x03`) terminator internally. Applications
can expect to receive complete JSON encoded messages in a text frame
without the ETX terminator. Likewise applications should send JSON encoded
messages without the ETX terminator. Messages may be sent using either
text frames or binary frames.
The bridge websocket provides access to diagnostic APIs that are not generally
suitable for Moonraker's primary connection. These requests stream a
substantial amount of data; bridge connections allow Moonraker to avoid
decoding and re-encoding this data, reducing CPU load on the host. The "dump"
requests, such as `motion_report/dump_stepper` and `adxl345/dump_adxl345`, are
examples of APIs that should make use of the bridge websocket.
The bridge websocket is available at:
```
ws://host_or_ip:port/klippysocket
```
The availability of bridge connections depends on Klippy's availability.
If Klippy is not running or its API server is not enabled then a bridge
websocket connection cannot be established. Established bridge connections
will close when Klippy is shutdown or restarted. Such connections will also
be closed if Moonraker is restarted or shutdown.
!!! Note
If JWT or API Key authentication is required the application must use a
[oneshot token](./authorization.md#generate-a-oneshot-token) when connecting
to a bridge socket. Since Moonraker does not decode bridge requests it is
not possible to perform JWT authentication post connection.
## Unix Socket Connection
All JSON-RPC APIs available over the Websocket transport are also available
over the Unix Domain Socket connection. Moonraker creates the socket file at
`<datapath>/comms/moonraker.sock` (ie: `~/printer_data/comms/moonraker.sock`).
The Unix Socket expects UTF-8 encoded JSON-RPC byte strings. Each JSON-RPC
request must be terminated with an ETX character (`0x03`).
The Unix Socket is desirable for front ends and extensions running on the
local machine as authentication is not necessary. There should be a small
performance improvement due to the simplified transport protocol, however
the impact of this is likely negligible.
The `moontest` repo contains a
[python script](https://github.com/Arksine/moontest/blob/master/scripts/unix_socket_test.py)
to test comms over the unix socket.
## JSON-RPC over HTTP Endpoint
Exposes the JSON-RPC interface over HTTP. Most JSON-RPC methods with
corresponding HTTP APIs are available. Methods exclusive to other
transports, such as [Identify Connection](./server.md#identify-connection), are
not available.
/// note
If authentication is required it must be part of the HTTP request,
either using the API Key Header (`X-Api-Key`) or JWT Bearer Token.
///
```{.http .apirequest title="HTTP Request"}
POST /server/jsonrpc
Content-Type: application/json
{
"jsonrpc": "2.0",
"method": "printer.info",
"id": 5153
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"jsonrpc": "2.0",
"id": 5153,
"result": {
"state": "ready",
"state_message": "Printer is ready",
"hostname": "my-pi-hostname",
"software_version": "v0.9.1-302-g900c7396",
"cpu_info": "4 core ARMv7 Processor rev 4 (v7l)",
"klipper_path": "/home/pi/klipper",
"python_path": "/home/pi/klippy-env/bin/python",
"log_file": "/tmp/klippy.log",
"config_file": "/home/pi/printer.cfg"
}
}
```
////
/// note
If an error is encountered while processing a JSON-RPC request
over HTTP the request itself will still return success. The
error will be returned in the response as a JSON-RPC encoded
object.
///
## Jinja2 Template API Calls
Some template options in Moonraker's configuration, such as those in the
[button](../configuration.md#button) component, may call Moonraker APIs through
the `call_method(method_name, kwargs)` context function. The `call_method`
function takes the API's JSON-RPC method name as its first parameter, followed
by a set of keyword arguments as per the method's requirements.
```ini
# moonraker.conf
# Query Printer Objects example
[button check_status]
pin: gpio26
on_press:
{% set query = {"toolhead": ["position"], "print_stats": None} %}
# JSON-RPC method is "printer.objects.query", which takes a single "objects"
# argument
{% set status = call_method("printer.objects.query", objects=query) %}
# do something with the value returned from the object query, perhaps
# send a websocket notification or publish a mqtt topic
# Publish button event to MQTT Topic
[button check_status]
pin: gpio26
on_release:
# JSON-RPC method is "server.mqtt.publish"
{% do call_method("server.mqtt.publish",
topic="moonraker/my-button",
payload="Button Released") %}
```
## Miscellaneous Tutorials
### Websocket setup
The websocket is located at `ws://host:port/websocket`, for example:
```javascript
var s = new WebSocket("ws://" + location.host + "/websocket");
```
/// Note
It may be necessary to authenticate the connection first. This
tutorial assumes that the client is running on a trusted connection.
///
The following is a basic startup sequence that may be used to establish
a full connection to Moonraker and ensure that Klipper is running and
available:
1. Attempt to connect to `/websocket` until successful using a timer-like
mechanism.
2. Once connected, query the [server info](./server.md#query-server-info)
endpoint to check Klippy's state.
- If the response returns an error then either the client
is not authorized or Moonraker is not running. Direct the user to
SSH into the machine and check `<data_folder/logs/moonraker.log`.
- If the response returns success, check the result's `klippy_state`
field:
- `klippy_state == "ready"`: you may proceed to request status of
printer objects make subscriptions, get the file list, etc.
- `klippy_state == "error"`: Klippy has experienced an error
starting up
- `klippy_state == "shutdown"`: Klippy is in a shutdown state.
- `klippy_state == "startup"`: re-request the `server info` endpoint in 2 seconds.
- `klippy_state == "disconnected"`: The Klippy host either isn't running,
has experienced a critical error during startup, or does not have its
API Server enabled.
3. Repeat step 2 until Klipper reports ready.
4. Clients should watch for the `notify_klippy_disconnected` event. If
received then Klippy has either been stopped or restarted. In this
state the client should repeat the steps above to determine when
klippy is ready.
/// note
If Klippy reports an `error` or `shutdown` state it is advisable prompt
the user. You can get a description from the `state_message`
field of a [printer info](./printer.md#get-klippy-host-information) request.
///
### Basic Print Status
An advanced client will likely use subscriptions and notifications
to interact with Moonraker, however simple clients such as home automation
software and embedded devices (ie: ESP32) may only wish to monitor the
status of a print. Below is a high level walkthrough for receiving print state
via polling.
- Set up a timer to poll at the desired interval. Depending on your use
case, 1 to 2 seconds is recommended.
- On each cycle, issue the following request:
```
GET http://host/printer/objects/query?webhooks&virtual_sdcard&print_stats
```
Or via JSON-RPC 2.0:
```json
{
"jsonrpc": "2.0",
"method": "printer.objects.query",
"params": {
"objects": {
"webhooks": null,
"virtual_sdcard": null,
"print_stats": null
}
},
"id": 5664
}
```
- If the request returns an error or the returned `result.status` is an empty
object, then this is an indication that Klippy either experienced an error or
it is not properly configured. Each queried object should be available in
`result.status`. The client should check to make sure that all objects are
received before proceeding.
- Inspect `webhooks.state`. If the value is not `ready` the printer
is not available. `webhooks.message` contains a message pertaining
to the current state.
- If the printer is ready, inspect `print_stats.state`. It may be one
of the following values:
- `standby`: No print in progress
- `printing`: The printer is currently printing
- `paused`: A print in progress has been paused
- `error`: The print exited with an error. `print_stats.message`
contains a related error message
- `complete`: The last print has completed
- If `print_stats.state` is not `standby` then `print_stats.filename`
will report the name of the currently loaded file.
- `print_stats.filename` can be used to fetch file metadata. It
is only necessary to fetch metadata once per print.
```
GET http://host/server/files/metadata?filename=<filename>
```
Or via JSON-RPC 2.0:
```json
{
"jsonrpc": "2.0",
"method": "server.files.metadata",
"params": {
"filename": "{filename}"
},
"id": 5643
}
```
If metadata extraction failed then this request will return an error.
Some metadata fields are only populated for specific slicers, and
unsupported slicers will only return the size and modified date.
- There are multiple ways to calculate the ETA, this example will use
file progress, as it is possible calculate the ETA with or without
metadata.
- If `metadata.estimated_time` is available, the eta calculation can
be done as:
```javascript
// assume "result" is the response from the status query
let vsd = result.status.virtual_sdcard;
let prog_time = vsd.progress * metadata.estimated_time;
let eta = metadata.estimated_time - prog_time
```
Alternatively, one can simply subtract the print duration from
the estimated time:
```javascript
// assume "result" is the response from the status query
let pstats = result.status.print_status;
let eta = metadata.estimated_time - pstats.print_duration;
if (eta < 0) eta = 0;
```
- If no metadata is available, print duration and progress can be used to
calculate the ETA:
```javascript
// assume "result" is the response from the status query
let vsd = result.status.virtual_sdcard;
let pstats = result.status.print_stats;
let total_time = pstats.print_duration / vsd.progress;
let eta = total_time - pstats.print_duration;
```
- It is possible to query additional objects if a client wishes to display
more information (ie: temperatures). See Klipper's
[Status Reference](https://www.klipper3d.org/Status_Reference.html)
documentation for details on objects available for query.
### Bed Mesh Coordinates
The [Bed Mesh](../printer_objects.md#bed_mesh) printer object may be used
to generate three dimensional coordinates of a probed area (or mesh).
Below is an example (in javascript) of how to transform the data received
from a bed_mesh object query into an array of 3D coordinates.
```javascript
// assume that we have executed an object query for bed_mesh and have the
// result. This example generates 3D coordinates for the probed matrix,
// however it would work with the mesh matrix as well
function process_mesh(result) {
let bed_mesh = result.status.bed_mesh;
let matrix = bed_mesh.probed_matrix;
if (!(matrix instanceof Array) || matrix.length < 3 ||
!(matrix[0] instanceof Array) || matrix[0].length < 3)
// make sure that the matrix is valid
return;
let coordinates = [];
// calculate the distance between each sample on both the X an Y
// axes
let x_distance = (bed_mesh.mesh_max[0] - bed_mesh.mesh_min[0]) /
(matrix[0].length - 1);
let y_distance = (bed_mesh.mesh_max[1] - bed_mesh.mesh_min[1]) /
(matrix.length - 1);
let x_idx = 0;
let y_idx = 0;
// transform the matrix of z values into (x, y, z) coordinates
for (const x_axis of matrix) {
x_idx = 0;
// mesh_min is the (x, y) coordinate of the first z sample
let y_coord = bed_mesh.mesh_min[1] + (y_idx * y_distance);
for (const z_coord of x_axis) {
let x_coord = bed_mesh.mesh_min[0] + (x_idx * x_distance);
x_idx++;
coordinates.push([x_coord, y_coord, z_coord]);
}
y_idx++;
}
}
// Use the array of coordinates to visualize the "probed area"
// or mesh..
```
### Converting to Unix Time
Some of Moonraker's APIs return a date represented in Unix time.
Most languages have functionality built in to convert Unix
time to a workable object or string. For example, in JavaScript
one might do something like the following:
```javascript
for (let resp of result.gcode_store) {
let date = new Date(resp.time * 1000);
// Do something with date and resp.message ...
}
```
+440
View File
@@ -0,0 +1,440 @@
# Job Queue Management
The following endpoints may be used to manage Moonraker's job queue.
Note that Moonraker's Job Queue is implemented as a FIFO queue and it may
contain multiple references to the same job.
The queue maintains an internal state attribute, which will always be one
of the following:
| State | Description |
| ---------- | ---------------------------------------------------------------- |
| `ready` | The queue is active and will load the next queued job upon |
| | completion of the current job. |^
| `loading` | The queue is currently loading the next job. If the |
| | `job_queue` configuration specifies a `job_transition_delay` |^
| | and/or a `job_transition_gcode` the queue will remain in the |^
| | `loading` state until both are completed. |^
| `starting` | The state reported while the Job Queue is requesting Klipper |
| | to start the print. |^
| `paused` | When the queue is `paused` it will not load the next queued |
| | job after a working job has completed. The queue will enter |^
| | this state if a pause is requested through the "pause" endpoint, |^
| | an error is encountered during the startup or loading phases, or |^
| | after completion of a job when the `job_queue` configuration |^
| | specifies that `automatic_transition` is set to false. |^
{ #queue-state-desc } Queue State
/// note
All filenames provided to and returned by these endpoints are relative to
the `gcodes` root.
///
## Get job queue status
Retrieves the current state of the job queue.
```{.http .apirequest title="HTTP Request"}
GET /server/job_queue/status
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.status",
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 21.89680004119873
},
{
"filename": "job2.gcode",
"job_id": "0000000066D991F0",
"time_added": 1636151050.7766452,
"time_in_queue": 21.88680004119873
},
{
"filename": "subdir/job3.gcode",
"job_id": "0000000066D99D80",
"time_added": 1636151050.7866452,
"time_in_queue": 21.90680004119873
}
],
"queue_state": "ready"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------- | :------: | -------------------------------------------------------- |
| `queued_jobs` | [object] | An array of `Queued Job` objects. |
| | | #queued-job-spec |+
| `queue_state` | string | The current [state](#queue-state-desc) of the job queue. |
{ #job-queue-status-response-spec }
| Field | Type | Description |
| --------------- | :----: | ------------------------------------------------------- |
| `filename` | string | The name of the gcode file queued. |
| `job_id` | string | A unique ID assigned to the queued job. |
| `time_added` | float | The time (in Unix Time) the job was added to the queue. |
| `time_in_queue` | float | The cumulative amount of time, in seconds, the job has |
| | | been pending in the queue. |^
{ #queued-job-spec } Queued Job
///
## Enqueue a job
Adds a job, or an array of jobs, to the end of the job queue. The same
filename may be specified multiple times to queue a job that repeats.
When multiple jobs are specified they will be enqueued in the order they
are received.
/// note
The request will be aborted and return an error if any of the supplied
files do not exist.
///
```{.http .apirequest title="HTTP Request"}
POST /server/job_queue/job
Content-Type: application/json
{
"filenames": [
"job1.gcode",
"job2.gcode",
"subdir/job3.gcode"
],
"reset": false
}
```
/// tip
If it isn't possible for your client to pass parameters in the body
of the request as a json object, they can be added to the query string
as shown below:
```{.http .apirequest title="HTTP Request"}
POST /server/job_queue/job?filenames=job1.gcode,job2.gcode,subdir/job3.gcode
```
Multiple jobs should be comma separated as shown above.
///
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.post_job",
"params": {
"filenames": [
"job1.gcode",
"job2.gcode",
"subdir/job3.gcode"
],
"reset": false
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ----------- | :------: | ------------ | ------------------------------------------------------- |
| `filenames` | [string] | **REQUIRED** | An array of filenames of jobs to add to the queue. |
| | | | The file names should be paths relative to the `gcodes` |^
| | | | root. All of the specified files must exist, otherwise |^
| | | | the request will return with an error. |^
| `reset` | bool | false | When set to `true` the job queue will be |
| | | | cleared prior to adding the requested jobs. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 0.01680004119873
},
{
"filename": "job2.gcode",
"job_id": "0000000066D991F0",
"time_added": 1636151050.7766452,
"time_in_queue": 0.01480004119873
},
{
"filename": "subdir/job3.gcode",
"job_id": "0000000066D99D80",
"time_added": 1636151050.7866452,
"time_in_queue": 0.010680004119873
}
],
"queue_state": "ready"
}
```
///
/// api-response-spec
open: True
See the [Job Queue Status](#job-queue-status-response-spec)
Response Specification.
///
## Remove a Job
Removes one or more jobs from the queue.
/// Note
Unlike the POST version of this method, it is not necessary that
all job ids exist. If any supplied job id does not exist in the
queue it will be silently ignored. Clients can verify the contents
of the queue via the return value.
///
```{.http .apirequest title="HTTP Request"}
DELETE /server/job_queue/job?job_ids=0000000066D991F0,0000000066D99D80
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.delete_job",
"params": {
"job_ids": [
"0000000066D991F0",
"0000000066D99D80"
]
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| --------- | :------: | --------------- | ------------------------------------------------ |
| `job_ids` | [string] | **REQUIRED** | An array of `job_ids` to remove from the queue. |
| | | if `all==false` | Any job ids that do not exist will be ignored. |^
| `all` | bool | false | When set to `true` all jobs will be removed |
| | | | from the queue. In this case it is not necessary |^
| | | | to set the `job_ids` parameter. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 21.89680004119873
}
],
"queue_state": "ready"
}
```
///
/// api-response-spec
open: True
See the [Job Queue Status](#job-queue-status-response-spec)
Response Specification.
///
## Pause the job queue
Sets the job queue state to "pause", which prevents the next job
in the queue from loading after an job in progress is complete.
If the queue is paused while the queue is in the `loading` state
the load will be aborted.
```{.http .apirequest title="HTTP Request"}
POST /server/job_queue/pause
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.pause",
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 21.89680004119873
},
{
"filename": "job2.gcode",
"job_id": "0000000066D991F0",
"time_added": 1636151050.7766452,
"time_in_queue": 21.88680004119873
},
{
"filename": "subdir/job3.gcode",
"job_id": "0000000066D99D80",
"time_added": 1636151050.7866452,
"time_in_queue": 21.90680004119873
}
],
"queue_state": "paused"
}
```
///
/// api-response-spec
open: True
See the [Job Queue Status](#job-queue-status-response-spec)
Response Specification.
///
## Start the job queue
Starts the job queue. If Klipper is ready to start a print the next
job in the queue will be loaded. Otherwise the queue will be put
into the "ready" state, where the job will be loaded after the current
job completes.
```{.http .apirequest title="HTTP Request"}
POST /server/job_queue/start
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.start",
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 21.89680004119873
},
{
"filename": "job2.gcode",
"job_id": "0000000066D991F0",
"time_added": 1636151050.7766452,
"time_in_queue": 21.88680004119873
},
{
"filename": "subdir/job3.gcode",
"job_id": "0000000066D99D80",
"time_added": 1636151050.7866452,
"time_in_queue": 21.90680004119873
}
],
"queue_state": "loading"
}
```
///
/// api-response-spec
open: True
See the [Job Queue Status](#job-queue-status-response-spec)
Response Specification.
///
## Perform a Queue Jump
Jumps a job to the front of the queue.
```{.http .apirequest title="HTTP Request"}
POST /server/job_queue/jump?job_id=0000000066D991F0
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.job_queue.jump",
"params": {
"job_id": "0000000066D991F0"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| -------- | :----: | ------------ | --------------------------------------- |
| `job_id` | string | **REQUIRED** | The `job_id` of the job to jump to the. |
| | | | front of the queue. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"queued_jobs": [
{
"filename": "job2.gcode",
"job_id": "0000000066D991F0",
"time_added": 1636151050.7766452,
"time_in_queue": 21.88680004119873
},
{
"filename": "job1.gcode",
"job_id": "0000000066D99C90",
"time_added": 1636151050.7666452,
"time_in_queue": 21.89680004119873
},
{
"filename": "subdir/job3.gcode",
"job_id": "0000000066D99D80",
"time_added": 1636151050.7866452,
"time_in_queue": 21.90680004119873
}
],
"queue_state": "loading"
}
```
///
/// api-response-spec
open: True
See the [Job Queue Status](#job-queue-status-response-spec)
Response Specification.
///
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+667
View File
@@ -0,0 +1,667 @@
# Printer Administration
These endpoints provide access to printer state and printer control.
Klippy must be connected to Moonraker to receive a successful response,
and in many cases Klippy must be in the `ready` state.
Most of these endpoints are registered with Moonraker by Klipper.
Requests pass from the frontend through Moonraker directly to Klipper.
Moonraker does not intervene.
## Get Klippy host information
```{.http .apirequest title="HTTP Request"}
GET /printer/info
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.info",
"id": 5445
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"state": "ready",
"state_message": "Printer is ready",
"hostname": "pi-debugger",
"klipper_path": "/home/pi/klipper",
"python_path": "/home/pi/klipper/venv/bin/python",
"process_id": 275124,
"user_id": 1000,
"group_id": 1000,
"log_file": "/home/pi/printer_data/logs/klippy.log",
"config_file": "/home/pi/printer_data/config/printer.cfg",
"software_version": "v0.12.0-85-gd785b396",
"cpu_info": "4 core ?"
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ------------------ | :----: | ----------------------------------------------------- |
| `state` | string | Klippy's current [state](#klippy-state-desc). |
| `state_message` | string | A message describing Klippy's current state. |
| `hostname` | string | Hostname of the machine running Klippy. |
| `klipper_path` | string | Path on disk to the Klipper application. |
| `python_path` | string | Path on disk to the Python executable running Klippy. |
| `process_id` | int | The PID of the current Klippy process. |
| `user_id` | int | The UID of the user the Klippy process belongs to. |
| `group_id` | int | The GID of the group the Klippy process belongs to. |
| `log_file` | string | Path on disk to Klipper's log file. |
| `configfile` | string | Path on disk to Klipper's configuration file. |
| `software_version` | string | Version of the currently running instance of Klipper. |
| `cpu_info` | string | A brief description of the host machine's CPU. |
| State | Description |
| ---------- | ------------------------------------------------------- |
| `ready` | Klippy has initialized and is ready for commands. |
| `startup` | Klippy is currently in its startup phase. |
| `error` | Klippy encountered an error during startup. |
| `shutdown` | Klippy is in the shutdown state. This can be initiated |
| | by the user via an emergency stop, or by the software |^
| | if it encounters a critical error during operation. |^
{ #klippy-state-desc } Klippy State
///
## Emergency Stop
```{.http .apirequest title="HTTP Request"}
POST /printer/emergency_stop
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.emergency_stop",
"id": 4564
}
```
/// Note
This endpoint will immediately halt the printer and put it in a "shutdown"
state. It should be used to implement an "emergency stop" button and
also used if a user enters `M112`(emergency stop) via a console.
///
```{.text .apiresponse title="Response"}
"ok"
```
## Host Restart
Requests a Klipper "soft" restart. This will reload the Klippy application
and configuration. Connected MCUs will not be reset.
```{.http .apirequest title="HTTP Request"}
POST /printer/restart
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.restart",
"id": 4894
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Firmware Restart
Requests a complete Klipper restart. Both the Klippy Application and connected
MCUs will be reset.
```{.http .apirequest title="HTTP Request"}
POST /printer/firmware_restart
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.firmware_restart",
"id": 8463
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Printer Status Requests
### List loaded printer objects
Returns a list of Klipper `printer objects` that are currently loaded.
This can be used to determine if a specific object is available for query
and/or subscription.
```{.http .apirequest title="HTTP Request"}
GET /printer/objects/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.objects.list",
"id": 1454
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"objects": [
"gcode",
"webhooks",
"configfile",
"mcu",
"mcu linux",
"heaters",
"bme280 chamber",
"temperature_sensor chamber",
"filament_switch_sensor extruder_sensor",
"output_pin sensor_toggle",
"gcode_move",
"bed_mesh",
"exclude_object",
"temperature_host RPi",
"temperature_sensor RPi",
"gcode_macro TURN_OFF_MOTORS",
"gcode_macro SET_HOMING_CURRENT",
"temperature_sensor ambient",
"gcode_macro query_bme280",
"pause_resume",
"print_stats",
"virtual_sdcard",
"probe",
"stepper_enable",
"tmc2130 stepper_x",
"tmc2130 stepper_y",
"tmc2130 stepper_z",
"tmc2130 extruder",
"heater_bed",
"heater_fan nozzle_cooling_fan",
"fan",
"menu",
"display_status",
"output_pin BEEPER_pin",
"idle_timeout",
"motion_report",
"query_endstops",
"system_stats",
"manual_probe",
"toolhead",
"extruder"
]
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| --------- | :------: | ------------------------------------------------ |
| `objects` | [string] | A list Klipper printer objects currently loaded. |
///
### Query printer object status
Requests the status of a provided set of printer objects.
/// Tip
See the [Printer Objects](../printer_objects.md) document
for details on the objects available for query.
///
```{.http .apirequest title="HTTP Request"}
POST /printer/objects/query
Content-Type: application/json
{
"objects": {
"gcode_move": null,
"toolhead": ["position", "status"]
}
}
```
/// details | Using the Query String
The HTTP Request may also be performed using the query string. It is
recommended to send the request in the body unless otherwise not possible.
```{.http .apirequest title="HTTP Request"}
GET /printer/objects/query?gcode_move&toolhead&extruder=target,temperature
```
The above will request a status update for all `gcode_move` and `toolhead`
attributes. Only the `temperature` and `target` attributes are requested
for the `extruder`.
///
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.objects.query",
"params": {
"objects": {
"gcode_move": null,
"toolhead": ["position", "status"]
}
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| --------- | :----: | ------------ | ------------------------------------------------------ |
| `objects` | object | **REQUIRED** | An object whose key, value pairs represent one or |
| | | | more [Printer Object Requests](#printer-obj-req-desc). |^
| Key Description | Value Description |
| ------------------------------- | ----------------------------------------------------------- |
| The `key`should be an available | The `value` specifies the attributes of the object that |
| Klipper printer object. | should be returned. If the value is `null` all attributes |^
| { width=40% } | will be returned. Alternatively a list of strings |^
| | specifying the desired attributes can be provided. |^
{ #printer-obj-req-desc } Printer Object Request
//// Note
If a requested printer object or attribute does not exist then the result
will be omitted from the response. No error is returned.
////
///
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"eventtime": 578243.57824499,
"status": {
"gcode_move": {
"absolute_coordinates": true,
"absolute_extrude": true,
"extrude_factor": 1,
"gcode_position": [0, 0, 0, 0],
"homing_origin": [0, 0, 0, 0],
"position": [0, 0, 0, 0],
"speed": 1500,
"speed_factor": 1
},
"toolhead": {
"position": [0, 0, 0, 0],
"status": "Ready"
}
}
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ----------- | :----: | -------------------------------------------------------------- |
| `eventtime` | float | The time at which the status was received, according Klipper's |
| | | monotonic clock. |^
| `status` | object | An object containing the current state of the requested |
| | | printer objects. |^
{ #object-query-response-spec }
///
### Subscribe to printer object status updates
Requests status updates for a set of printer objects. A persistent
connection (Websocket or Unix Socket) is required to fulfill this
request.
Status updates for subscribed objects are sent asynchronously over the
connection. See the
[notify_status_update](./jsonrpc_notifications.md#subscription-updates)
notification for details.
/// Tip
See the [Printer Objects](../printer_objects.md) document
for details on the objects available for subscription.
///
```{.text .apirequest title="HTTP Request"}
Not available
```
```{.json .apirequest title="JSON-RPC Request (Websocket and Unix Socket Only)"}
{
"jsonrpc": "2.0",
"method": "printer.objects.subscribe",
"params": {
"objects": {
"gcode_move": null,
"toolhead": ["position", "status"]
}
},
"id": 5434
}
```
/// api-parameters
open: True
Parameters are identical to the [query](#query-printer-object-status)
status parameters. A new request will override a previous request.
If `objects` is set to an empty object then the subscription will be
cancelled.
///
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"eventtime": 578243.57824499,
"status": {
"gcode_move": {
"absolute_coordinates": true,
"absolute_extrude": true,
"extrude_factor": 1,
"gcode_position": [0, 0, 0, 0],
"homing_origin": [0, 0, 0, 0],
"position": [0, 0, 0, 0],
"speed": 1500,
"speed_factor": 1,
},
"toolhead": {
"position": [0, 0, 0, 0],
"status": "Ready"
}
}
}
```
////
/// api-response-spec
open: True
The response spec is identical to the [query response specification](#object-query-response-spec)
The response may be used to initialize local state without performing a
separate query.
///
### Query Endstops
```{.http .apirequest title="HTTP Request"}
GET /printer/query_endstops/status
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.query_endstops.status",
"id": 3456
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"x": "TRIGGERED",
"y": "open",
"z": "open"
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ----------------------------------------------------------- |
| *variable* | string | The field is the name of the registered endstop. The value |
| | | will be `open` or `TRIGGERED`. |^
///
## GCode APIs
### Run a gcode command
Executes a gcode command. Multiple commands may be executed by separating
them with a newline (`\n`). The request returns when the command or series
of commands have completed, or when the command results in an error.
/// warning
When `M112`(emergency stop) is requested via this endpoint it will not
immediately stop the printer. `M112` will be placed on the gcode queue and
executed after all previous gcodes are complete. If a frontend detects
`M112` via user input (such as a console) it should request the
`/printer/emergency_stop` endpoint to immediately halt the printer. This
may be done in addition to sending the `M112` gcode if desired.
///
```{.http .apirequest title="HTTP Request"}
POST /printer/gcode/script
Content-Type: application/json
{
"script": "G28"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.gcode.script",
"params": {
"script": "G28"
},
"id": 7466}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| -------- | :----: | ------------ | ------------------------------------------------- |
| `script` | string | **REQUIRED** | A GCode Command to run. Multiple commands may be |
| | | | specified, separated by a newline (`\n`). |^
///
```{.text .apiresponse title="Response"}
"ok"
```
### Get GCode Help
Retrieves a list of registered GCode Command Descriptions. Not all registered
GCode commands have a description, so this list should not be treated as an
exhaustive list of all supported commands.
```{.http .apirequest title="HTTP Request"}
GET /printer/gcode/help
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.gcode.help",
"id": 4645
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"RESTART": "Reload config file and restart host software",
"FIRMWARE_RESTART": "Restart firmware, host, and reload config",
"STATUS": "Report the printer status",
"HELP": "Report the list of available extended G-Code commands",
"SAVE_CONFIG": "Overwrite config file and restart",
"SHUTDOWN_MACHINE": "G-Code macro",
"SET_GCODE_VARIABLE": "Set the value of a G-Code macro variable",
"REBOOT_MACHINE": "G-Code macro",
"UPDATE_DELAYED_GCODE": "Update the duration of a delayed_gcode",
"TURN_OFF_HEATERS": "Turn off all heaters",
"TEMPERATURE_WAIT": "Wait for a temperature on a sensor",
"QUERY_ADC": "Report the last value of an analog pin",
"QUERY_FILAMENT_SENSOR": "Query the status of the Filament Sensor",
"SET_FILAMENT_SENSOR": "Sets the filament sensor on/off",
"SET_PIN": "Set the value of an output pin",
"BED_MESH_CALIBRATE": "Perform Mesh Bed Leveling",
"BED_MESH_PROFILE": "Bed Mesh Persistent Storage management",
"BED_MESH_OUTPUT": "Retrieve interpolated grid of probed z-points",
"BED_MESH_MAP": "Serialize mesh and output to terminal",
"BED_MESH_CLEAR": "Clear the Mesh so no z-adjustment is made",
"BED_MESH_OFFSET": "Add X/Y offsets to the mesh lookup",
"SET_GCODE_OFFSET": "Set a virtual offset to g-code positions",
"SAVE_GCODE_STATE": "Save G-Code coordinate state",
"RESTORE_GCODE_STATE": "Restore a previously saved G-Code state",
"GET_POSITION": "Return information on the current location of the toolhead",
"EXCLUDE_OBJECT_START": "Marks the beginning the current object as labeled",
"EXCLUDE_OBJECT_END": "Marks the end the current object",
"EXCLUDE_OBJECT": "Cancel moves inside a specified objects",
"EXCLUDE_OBJECT_DEFINE": "Provides a summary of an object",
"TURN_OFF_MOTORS": "G-Code macro",
"CLEAR_PAUSE": "Clears the current paused state without resuming the print",
"SET_PRINT_STATS_INFO": "Pass slicer info like layer act and total to klipper",
"SDCARD_RESET_FILE": "Clears a loaded SD File. Stops the print if necessary",
"SDCARD_PRINT_FILE": "Loads a SD file and starts the print. May include files in subdirectories.",
"RESPOND": "Echo the message prepended with a prefix",
"PROBE": "Probe Z-height at current XY position",
"QUERY_PROBE": "Return the status of the z-probe",
"PROBE_CALIBRATE": "Calibrate the probe's z_offset",
"PROBE_ACCURACY": "Probe Z-height accuracy at current XY position",
"Z_OFFSET_APPLY_PROBE": "Adjust the probe's z_offset",
"GET_CURRENT_SKEW": "Report current printer skew",
"CALC_MEASURED_SKEW": "Calculate skew from measured print",
"SET_SKEW": "Set skew based on lengths of measured object",
"SKEW_PROFILE": "Profile management for skew_correction",
"SET_STEPPER_ENABLE": "Enable/disable individual stepper by name",
"SET_TMC_FIELD": "Set a register field of a TMC driver",
"INIT_TMC": "Initialize TMC stepper driver registers",
"SET_TMC_CURRENT": "Set the current of a TMC driver",
"DUMP_TMC": "Read and display TMC stepper driver registers",
"PID_CALIBRATE": "Run PID calibration test",
"SET_HEATER_TEMPERATURE": "Sets a heater temperature",
"SET_DISPLAY_TEXT": "Set or clear the display message",
"SET_DISPLAY_GROUP": "Set the active display group",
"STEPPER_BUZZ": "Oscillate a given stepper to help id it",
"FORCE_MOVE": "Manually move a stepper; invalidates kinematics",
"SET_KINEMATIC_POSITION": "Force a low-level kinematic position",
"SET_IDLE_TIMEOUT": "Set the idle timeout in seconds",
"QUERY_ENDSTOPS": "Report on the status of each endstop",
"SET_VELOCITY_LIMIT": "Set printer velocity limits",
"MANUAL_PROBE": "Start manual probe helper script",
"TUNING_TOWER": "Tool to adjust a parameter at each Z height",
"SET_PRESSURE_ADVANCE": "Set pressure advance parameters",
"SET_EXTRUDER_ROTATION_DISTANCE": "Set extruder rotation distance",
"SYNC_EXTRUDER_MOTION": "Set extruder stepper motion queue",
"SET_EXTRUDER_STEP_DISTANCE": "Set extruder step distance",
"SYNC_STEPPER_TO_EXTRUDER": "Set extruder stepper",
"ACTIVATE_EXTRUDER": "Change the active extruder",
"BASE_PAUSE": "Renamed builtin of 'PAUSE'",
"BASE_RESUME": "Renamed builtin of 'RESUME'",
"BASE_CANCEL_PRINT": "Renamed builtin of 'CANCEL_PRINT'",
"ACCEPT": "Accept the current Z position",
"ABORT": "Abort manual Z probing tool",
"TESTZ": "Move to new Z height"
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ----------------------------------------------------------------- |
| *variable* | string | The field is the name of the registered gcode command. The value |
| | | is a string containing the associated help descriptions. |^
//// Note
As mentioned previously, this list is not exhaustive. Help strings are not
available for default gcode handlers such as G1, G28, etc, nor are they
available for extended handlers that failed to register a description in
Klipper's python source.
////
///
## Print Job Management
### Start a print job
```{.http .apirequest title="HTTP Request"}
POST /printer/print/start?filename=test_print.gcode
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.print.start",
"params": {
"filename": "test_print.gcode"
},
"id": 4654
}
```
/// api-parameters
open: true
| Name | Type | Default | Description |
| ---------- | :----: | ------------ | --------------------------------------------------- |
| `filename` | string | **REQUIRED** | The name of the gcode file to print. May be a path |
| | | | relative to the gcode folder. |^
///
```{.text .apiresponse title="Response"}
"ok"
```
### Pause a print job
```{.http .apirequest title="HTTP Request"}
POST /printer/print/pause
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.print.pause",
"id": 4564
}
```
```{.text .apiresponse title="Response"}
"ok"
```
### Resume a print job
```{.http .apirequest title="HTTP Request"}
POST /printer/print/resume
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.print.resume",
"id": 1465
}
```
```{.text .apiresponse title="Response"}
"ok"
```
### Cancel a print job
```{.http .apirequest title="HTTP Request"}
POST /printer/print/cancel
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "printer.print.cancel",
"id": 2578
}
```
```{.text .apiresponse title="Response"}
"ok"
```
+648
View File
@@ -0,0 +1,648 @@
# Server Administration
These endpoints provide access to server status, data tracking, and
administrative requests.
## Query Server Info
```{.http .apirequest title="HTTP Request"}
GET /server/info
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.info",
"id": 9546
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"klippy_connected": true,
"klippy_state": "ready",
"components": [
"database",
"file_manager",
"klippy_apis",
"machine",
"data_store",
"shell_command",
"proc_stats",
"history",
"octoprint_compat",
"update_manager",
"power"
],
"failed_components": [],
"registered_directories": ["config", "gcodes", "config_examples", "docs"],
"warnings": [
"Invalid config option 'api_key_path' detected in section [authorization]. Remove the option to resolve this issue. In the future this will result in a startup error.",
"Unparsed config section [fake_section] detected. This may be the result of a component that failed to load. In the future this will result in a startup error."
],
"websocket_count": 2,
"moonraker_version": "v0.7.1-105-ge4f103c",
"api_version": [1, 4, 0],
"api_version_string": "1.4.0"
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ------------------------ | :------: | -------------------------------------------------------- |
| `klippy_connected` | bool | Moonraker's connection status to the Klippy Host. |
| `klippy_state` | string | Klippy's current state. Expand for available values. |
| #klippy-state-desc | | |+
| `components` | [string] | A list of Moonraker components that are currently |
| | | loaded. |^
| `failed_components` | [string] | A list of Moonraker components that failed to load. |
| `registered_directories` | [string] | A list "roots" registered with Moonraker's file manager. |
| `warnings` | [string] | A list of warning messages describing errors encountered |
| | | during initialization or regular operation. |^
| `websocket_count` | int | The number of currently active websocket connections. |
| `moonraker_version` | string | The version of the Moonraker Application. |
| `api_version` | [int] | The version of the API in tuple format. |
| `api_version_string` | string | The version of the API in string format. |
| State | Description |
| -------------- | ------------------------------------------------------------------ |
| `disconnected` | Moonraker is currently disconnect from Klippy. |
| `startup` | Klippy is currently initializing. |
| `ready` | Klippy is active and ready to receive commands. |
| `error` | Klippy experienced an error during startup. |
| `shutdown` | Klippy has been emergency stopped. This can occur at user request |
| | or if a critical error is encountered while running. |^
{ #klippy-state-desc }
///
## Get Server Configuration
```{.http .apirequest title="HTTP Request"}
GET /server/config
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.config",
"id": 5616
}
```
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"config": {
"server": {
"host": "0.0.0.0",
"port": 7125,
"ssl_port": 7130,
"enable_debug_logging": true,
"enable_asyncio_debug": false,
"klippy_uds_address": "/tmp/klippy_uds",
"max_upload_size": 210,
"ssl_certificate_path": null,
"ssl_key_path": null
},
"dbus_manager": {},
"database": {
"database_path": "~/.moonraker_database",
"enable_database_debug": false
},
"file_manager": {
"enable_object_processing": true,
"queue_gcode_uploads": true,
"config_path": "~/printer_config",
"log_path": "~/logs"
},
"klippy_apis": {},
"machine": {
"provider": "systemd_dbus"
},
"shell_command": {},
"data_store": {
"temperature_store_size": 1200,
"gcode_store_size": 1000
},
"proc_stats": {},
"job_state": {},
"job_queue": {
"load_on_startup": true,
"automatic_transition": false,
"job_transition_delay": 2,
"job_transition_gcode": "\nM118 Transitioning to next job..."
},
"http_client": {},
"announcements": {
"dev_mode": false,
"subscriptions": []
},
"authorization": {
"login_timeout": 90,
"force_logins": false,
"cors_domains": [
"*.home",
"http://my.mainsail.xyz",
"http://app.fluidd.xyz",
"*://localhost:*"
],
"trusted_clients": [
"192.168.1.0/24"
]
},
"zeroconf": {},
"octoprint_compat": {
"enable_ufp": true,
"flip_h": false,
"flip_v": false,
"rotate_90": false,
"stream_url": "/webcam/?action=stream",
"webcam_enabled": true
},
"history": {},
"secrets": {
"secrets_path": "~/moonraker_secrets.ini"
},
"mqtt": {
"address": "eric-work.home",
"port": 1883,
"username": "{secrets.mqtt_credentials.username}",
"password_file": null,
"password": "{secrets.mqtt_credentials.password}",
"mqtt_protocol": "v3.1.1",
"instance_name": "pi-debugger",
"default_qos": 0,
"status_objects": {
"webhooks": null,
"toolhead": "position,print_time",
"idle_timeout": "state",
"gcode_macro M118": null
},
"api_qos": 0,
"enable_moonraker_api": true
},
"template": {}
},
"orig": {
"DEFAULT": {},
"server": {
"enable_debug_logging": "True",
"max_upload_size": "210"
},
"file_manager": {
"config_path": "~/printer_config",
"log_path": "~/logs",
"queue_gcode_uploads": "True",
"enable_object_processing": "True"
},
"machine": {
"provider": "systemd_dbus"
},
"announcements": {},
"job_queue": {
"job_transition_delay": "2.",
"job_transition_gcode": "\nM118 Transitioning to next job...",
"load_on_startup": "True"
},
"authorization": {
"trusted_clients": "\n192.168.1.0/24",
"cors_domains": "\n*.home\nhttp://my.mainsail.xyz\nhttp://app.fluidd.xyz\n*://localhost:*"
},
"zeroconf": {},
"octoprint_compat": {},
"history": {},
"secrets": {
"secrets_path": "~/moonraker_secrets.ini"
},
"mqtt": {
"address": "eric-work.home",
"port": "1883",
"username": "{secrets.mqtt_credentials.username}",
"password": "{secrets.mqtt_credentials.password}",
"enable_moonraker_api": "True",
"status_objects": "\nwebhooks\ntoolhead=position,print_time\nidle_timeout=state\ngcode_macro M118"
}
},
"files": [
{
"filename": "moonraker.conf",
"sections": [
"server",
"file_manager",
"machine",
"announcements",
"job_queue",
"authorization",
"zeroconf",
"octoprint_compat",
"history",
"secrets"
]
},
{
"filename": "include/extras.conf",
"sections": [
"mqtt"
]
}
]
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :------: | ---------------------------------------------------------------------- |
| `config` | object | An object containing the full Moonraker configuration. Each field of |
| | | this object is a section name. The value for each section is an |^
| | | object mapping option names to values. Values are cast to their |^
| | | internal type. Default values not specified in the configuration |^
| | | files are included. |^
| `orig` | object | An object containing the original configuration as read from the |
| | | configuration file(s). Like `config`, each field is a section name |^
| | | and each value is a mapping of options to values. Only values present |^
| | | in the configuration files are reported, and all values are strings. |^
| `files` | [object] | An array of [File Objects](#file-object-spec) describing the config |
| | | files parsed. |^
| Field | Type | Description |
| ---------- | :------: | ----------------------------------------------------------------- |
| `filename` | string | The name of the configuration file. This name is a path relative |
| | | to the main configuration file's parent folder. |^
| `sections` | [string] | The config sections parsed from this file. |
{ #file-object-spec } File Object
///
## Request Cached Temperature Data
```{.http .apirequest title="HTTP Request"}
GET /server/temperature_store?include_monitors=false
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.temperature_store",
"params": {
"include_monitors": false
},
"id": 2313
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------------------ | :--: | ------- | -------------------------------------------- |
| `include_monitors` | bool | `false` | When set to `true` the response will include |
| | | | sensors reported as `temperature monitors.` |^
| | | | A temperature monitor is a specific type of |^
| | | | sensor that may include `null` values in |^
| | | | the `temperatures` field of the response. |^
///
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"extruder": {
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1],
"targets": [0, 0, 0, 0, 0],
"powers": [0, 0, 0, 0, 0]
},
"temperature_fan my_fan": {
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1],
"targets": [0, 0, 0, 0, 0],
"speeds": [0, 0, 0, 0, 0]
},
"temperature_sensor my_sensor": {
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1]
}
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ---------- | :----: | ----------------------------------------------------------------------------- |
| *variable* | object | A primary object including zero or more [Sensor Objects](#sensor-obj-spec). |
| | | The `fields` in this object will be sensor names as reported by Klippy. |^
| | | If Klippy has not been initialized or reports no sensors this object will |^
| | | be empty. |^
| Field | Type | Description |
| -------------- | :------: | ------------------------------------------------------------------ |
| `temperatures` | [float?] | Contains the history of temperature measurements of this sensor. |
| | | If the sensor is a `temperature monitor` values may be `null`. A |^
| | | `null` value indicates that the sensor recorded no measurement at |^
| | | that time. |^
| `targets` | [float] | Contains the history of temperature targets for heaters. |
| `speeds` | [float] | Contains a history of `speeds` for fans. This value should be |
| | | between 0 and 1 indicating the pwm duty cycle. |^
| `powers` | [float] | Contains a history fof `powers` for heaters. This value should be |
| | | between 0 and 1 indicating the pwm duty cycle. |^
{ #sensor-obj-spec } Sensor Object
//// Note
Fields not reported by a sensor will be omitted in the `Sensor Object`.
Each array in the `Sensor Object` is a FIFO queue, where the measurement at index 0
is the oldest value. The time period between each measurement is 1 second. The
maximum length of the array is set in Moonraker's configuration, where the default is
1200 values.
////
///
## Request Cached GCode Responses
```{.http .apirequest title="HTTP Request"}
GET /server/gcode_store?count=100
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.gcode_store",
"params": {
"count": 100
},
"id": 7643
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------- | :--: | ------------ | --------------------------------------------------- |
| `count` | int | *Store Size* | The number of cached gcode responses to return. The |
| | | | default is to return all cached items. |^
///
//// collapse-code
```{.json .apiresponse title="Example Response"}
{
"gcode_store": [
{
"message": "FIRMWARE_RESTART",
"time": 1615832299.1167388,
"type": "command"
},
{
"message": "// Klipper state: Ready",
"time": 1615832309.9977088,
"type": "response"
},
{
"message": "M117 This is a test",
"time": 1615834094.8662775,
"type": "command"
},
{
"message": "G4 P1000",
"time": 1615834098.761729,
"type": "command"
},
{
"message": "STATUS",
"time": 1615834104.2860553,
"type": "command"
},
{
"message": "// Klipper state: Ready",
"time": 1615834104.3299904,
"type": "response"
}
]
}
```
////
/// api-response-spec
open: True
| Field | Type | Description |
| ------------- | :------: | ---------------------------------------------------------------- |
| `gcode_store` | [object] | An array of [GCode Tracking Objects](#gc-tracking-obj-spec). |
| | | The array is a FIFO queue with the oldest item being at index 0. |^
| Field | Type | Description |
| --------- | :----: | ------------------------------------------------------------------ |
| `message` | string | The GCode Message associated with ths object. |
| `time` | float | The time at which the message was received reported in Unix Time. |
| `type` | string | The message type. Can be `command` or `response`. Commands are |
| | | only tracked when received through Moonraker's gcode API endpoint. |^
{ #gc-tracking-obj-spec } GCode Tracking Object
///
## Rollover Logs
Requests a manual rollover for log files registered with Moonraker's
log management facility. Currently these are limited to `moonraker.log`
and `klippy.log`.
/// Warning
Moonraker must be able to manage Klipper's systemd service to
perform a manual rollover. The rollover will fail under the following
conditions:
- Moonraker cannot detect Klipper's systemd unit
- Moonraker cannot detect the location of Klipper's files
- A print is in progress
///
```{.http .apirequest title="HTTP Request"}
POST /server/logs/rollover
Content-Type: application/json
{
"application": "moonraker"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.logs.rollover",
"params": {
"application": "moonraker"
},
"id": 4656
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------------- | :----: | ------- | ------------------------------------------------------- |
| `application` | string | *all* | The name of the application for which the log should be |
| | | | rolled over. Can be `moonraker` or `klipper`. When no |^
| | | | value is specified all logs are rolled over. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"rolled_over": [
"moonraker",
"klipper"
],
"failed": {}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| ------------- | :------: | -------------------------------------------------------- |
| `rolled_over` | [string] | A list of application names successfully rolled over. |
| `failed` | object | An object where the fields consist of applications names |
| | | that failed the rollover procedure. The value assigned |^
| | | to each field is an error message. |^
///
## Restart Server
```{.http .apirequest title="HTTP Request"}
POST /server/restart
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.restart",
"id": 4656
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Identify Connection
This method provides a way for applications with persistent connections
to identify themselves to Moonraker. This information may be used by
Moonraker perform an action or present information based on if a specific
type of frontend is connected. Currently this method is only available
to websocket and unix socket connections. Once this endpoint returns
success it cannot be called again, repeated calls will result in an error.
```{.text .apirequest title="HTTP request"}
Not Available
```
```{.json .apirequest title="JSON-RPC request (Websocket/Unix Socket Only)"}
{
"jsonrpc": "2.0",
"method": "server.connection.identify",
"params": {
"client_name": "moontest",
"version": "0.0.1",
"type": "web",
"url": "http://github.com/arksine/moontest",
"access_token": "<base64 encoded token>",
"api_key": "<system API key>"
},
"id": 4656
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| -------------- | :----: | ------------ | -------------------------------------------------- |
| `client_name` | string | **REQUIRED** | The name of the application identifying itself, |
| | | | ie: `Mainsail`, `Fluidd`, `KlipperScreen`, etc. |^
| `version` | string | **REQUIRED** | The version of the application identifying itself. |
| `type` | string | **REQUIRED** | The type of the application. Expand for available |
| | | | values. |^
| | | | #valid-id-type-desc |+
| `url` | string | **REQUIRED** | The project URL or homepage for the application. |
| `access_token` | string | `null` | An optional JSON Web Token used to authenticate |
| | | | the websocket connection. Only needed when the |^
| | | | app uses JWT authentication and did not |^
| | | | authenticate through the original Websocket |^
| | | | Request. |^
| `api_key` | string | `null` | An optional API Key used to authenticate the |
| | | | connection. Only needed when the APP uses API |^
| | | | Key authentication and did not authenticate |^
| | | | through the original Websocket Request. |^
| Name | Description |
| --------- | --------------------------------------------------------------- |
| `web` | A web application like `Mainsail` and `Fluidd`. |
| `mobile` | A mobile application like `Mobileraker`. |
| `desktop` | A desktop application like `OrcaSlicer`. |
| `display` | An application intended to drive displays like `KlipperScreen`. |
| `bot` | An interactive bot like `MoonCord`. |
| `agent` | An external extension like `Obico`. |
| `other` | Anything that doesn't fit in to the above categories. |
{: #valid-id-type-desc }
//// Note
When identifying as an `agent`, only one instance should be connected
to Moonraker at a time. If multiple agents of the same `client_name`
attempt to identify themselves this endpoint will return an error.
See the [extensions](./extensions.md) document for more information about
`agents`.
////
//// Tip
See the authorization API documentation for details on JWT and API Key authentication.
////
///
```{.json .apiresponse title="Example Response"}
{
"connection_id": 1730367696
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| --------------- | :--: | ---------------------------------------- |
| `connection_id` | int | A unique identifier for this connection. |
///
## Get Websocket ID
!!! Warning
This method is deprecated. Please use the
[identify endpoint](#identify-connection) to retrieve the
Websocket's UID
```{.text .apirequest title="HTTP request"}
Not Available
```
```{json .apirequest title="JSON-RPC request (Websocket/Unix Socket Only)"}
{
"jsonrpc": "2.0",
"method": "server.websocket.id",
"id": 4656
}
```
```{.json .apiresponse title="Example Response"}
{
"websocket_id": 1730367696
}
```
/// api-response-spec
open: True
| Field | Type | Description |
| -------------- | :--: | ---------------------------------------- |
| `websocket_id` | int | A unique identifier for this connection. |
///
+770
View File
@@ -0,0 +1,770 @@
# Update Management
The endpoints in the section are available when the `[update_manager]`
component has been configured in `moonraker.conf`. They may be used
to manage updates for Moonraker, Klipper, OS Packages, and additional
software added through the configuration.
## Get update status
```{.http .apirequest title="HTTP Request"}
GET /machine/update/status
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.status",
"id": 4644
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| --------- | :--: | ------- | ----------------------------------------------- |
| `refresh` | bool | false | *DEPRECATED*. When `true` an attempt will |
| | | | be made to refresh all updaters. The refresh |^
| | | | will abort under the following conditions:<BR/> |^
| | | | - an update is in progress<BR/> |^
| | | | - a print is in progress<BR/> |^
| | | | - the update manager hasn't completed |^
| | | | initialization<BR/> |^
| | | | - a refresh has been performed within the last |^
| | | | 60 seconds<BR/> |^
//// Note
The `refresh` parameter is deprecated. Front end developers should use the
[refresh endpoint](#refresh-update-status) to request a refresh.
////
///
/// collapse-code
```{.json #status-example-response .apiresponse title="Example Response"}
{
"busy": false,
"github_rate_limit": 60,
"github_requests_remaining": 57,
"github_limit_reset_time": 1615836932,
"version_info": {
"system": {
"name": "system",
"configured_type": "system",
"package_count": 4,
"package_list": [
"libtiff5",
"raspberrypi-sys-mods",
"rpi-eeprom-images",
"rpi-eeprom"
]
},
"moonraker": {
"channel": "dev",
"debug_enabled": true,
"is_valid": true,
"configured_type": "git_repo",
"corrupt": false,
"info_tags": [],
"detected_type": "git_repo",
"name": "moonraker",
"remote_alias": "arksine",
"branch": "master",
"owner": "arksine",
"repo_name": "moonraker",
"version": "v0.7.1-364",
"remote_version": "v0.7.1-364",
"rollback_version": "v0.7.1-360",
"current_hash": "ecfad5cff15fff1d82cb9bdc64d6b548ed53dfaf",
"remote_hash": "ecfad5cff15fff1d82cb9bdc64d6b548ed53dfaf",
"is_dirty": false,
"detached": true,
"commits_behind": [],
"git_messages": [],
"full_version_string": "v0.7.1-364-gecfad5c",
"pristine": true,
"recovery_url": "https://github.com/Arksine/moonraker.git",
"remote_url": "https://github.com/Arksine/moonraker.git",
"warnings": [],
"anomalies": [
"Unofficial remote url: https://github.com/Arksine/moonraker-fork.git",
"Repo not on official remote/branch, expected: origin/master, detected: altremote/altbranch",
"Detached HEAD detected"
]
},
"mainsail": {
"name": "mainsail",
"owner": "mainsail-crew",
"version": "v2.1.1",
"remote_version": "v2.1.1",
"rollback_version": "v2.0.0",
"configured_type": "web",
"channel": "stable",
"info_tags": [
"desc=Mainsail Web Client",
"action=some_action"
],
"warnings": [],
"anomalies": [],
"is_valid": true
},
"fluidd": {
"name": "fluidd",
"owner": "fluidd-core",
"version": "v1.16.2",
"remote_version": "v1.16.2",
"rollback_version": "v1.15.0",
"configured_type": "web",
"channel": "beta",
"info_tags": [],
"warnings": [],
"anomalies": [],
"is_valid": true
},
"klipper": {
"channel": "dev",
"debug_enabled": true,
"is_valid": true,
"configured_type": "git_repo",
"corrupt": false,
"info_tags": [],
"detected_type": "git_repo",
"name": "klipper",
"remote_alias": "origin",
"branch": "master",
"owner": "Klipper3d",
"repo_name": "klipper",
"version": "v0.10.0-1",
"remote_version": "v0.10.0-41",
"rollback_version": "v0.9.1-340",
"current_hash": "4c8d24ae03eadf3fc5a28efb1209ce810251d02d",
"remote_hash": "e3cbe7ea3663a8cd10207a9aecc4e5458aeb1f1f",
"is_dirty": false,
"detached": false,
"commits_behind": [
{
"sha": "e3cbe7ea3663a8cd10207a9aecc4e5458aeb1f1f",
"author": "Kevin O'Connor",
"date": "1644534721",
"subject": "stm32: Clear SPE flag on a change to SPI CR1 register",
"message": "The stm32 specs indicate that the SPE bit must be cleared before\nchanging the CPHA or CPOL bits.\n\nReported by @cbc02009 and @bigtreetech.\n\nSigned-off-by: Kevin O'Connor <kevin@koconnor.net>",
"tag": null
},
{
"sha": "99d55185a21703611b862f6ce4b80bba70a9c4b5",
"author": "Kevin O'Connor",
"date": "1644532075",
"subject": "stm32: Wait for transmission to complete before returning from spi_transfer()",
"message": "It's possible for the SCLK pin to still be updating even after the\nlast byte of data has been read from the receive pin. (In particular\nin spi mode 0 and 1.) Exiting early from spi_transfer() in this case\ncould result in the CS pin being raised before the final updates to\nSCLK pin.\n\nAdd an additional wait at the end of spi_transfer() to avoid this\nissue.\n\nSigned-off-by: Kevin O'Connor <kevin@koconnor.net>",
"tag": null
}
],
"git_messages": [],
"full_version_string": "v0.10.0-1-g4c8d24ae-shallow",
"pristine": true,
"recovery_url": "https://github.com/Klipper3d/klipper.git",
"remote_url": "https://github.com/Klipper3d/klipper.git",
"warnings": [],
"anomalies": []
}
}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------------------------- | :----: | ----------------------------------------------------- |
| `busy` | bool | Set to `true` if an update is currently in progress. |
| `github_rate_limit` | int | The maximum number of GitHub API requests allowed. |
| | | An unauthenticated user is typically allowed 60 |^
| | | requests per hour. |^
| `github_requests_remaining` | int | The number of GitHub API requests remaining until the |
| | | reset time is reached. |^
| `github_limit_reset_time` | int | The time when the rate limit will reset, reported in |
| | | unix time. |^
| `version_info` | object | A `Version Info` object containing the update status |
| | | for each configured software updater. |^
| | | #version-info-desc |+
{ #update-status-spec }
| Field | Type | Description |
| --------- | :----: | ---------------------------------------------------------- |
| `system` | object | A [System Status](#system-status-spec) object. |
| | | This field is only available when the `update_manager` is |^
| | | configured to update system packages. |^
| _updater_ | object | A `Status Update` object. There are multiple sub-types of |
| | | status objects, the specific type can be determined by the |^
| | | object's [configured_type](#configured-type-desc) field. |^
| | | The `version_info` object may have multiple _updater_ |^
| | | items. The field name for each updater will match the |^
| | | object's `name`. |^
{ #version-info-desc } Version Info
| Type | Description |
| ---------- | ---------------------------------------------------------- |
| `git_repo` | A [Git Repo Status](#git-repo-status-spec) object. |
| | The software is distributed through a git repo on GitHub. |^
| `web` | A [Net Hosted Status](#net-app-status-spec ) object. |
| | The software is a web application. |^
| | Updates are GitHub hosted releases packaged in a zip file. |^
| `zip` | A [Net Hosted Status](#net-app-status-spec ) object. |
| | The software is a local application, optionally installed |^
| | as a system service. Updates are GitHub hosted releases |^
| | packaged in a zip file. |^
| `python` | A [Python Package Status](#python-status-spec) object. |
| | The software is a Python Application installed in its own |^
| | virtualenv. Updates may be hosted on PyPI or GitHub. |^
| | Pip is used to deploy updates. |^
| `system` | A [System Status](#system-status-spec) object. This type |
| | is internally managed and only applicable to the system |^
| | package manager. |^
{ #configured-type-desc } Configured Types
| Field | Type | Description |
| ---------------------- | :------: | -------------------------------------------------------- |
| `name` | string | The name of the software to manage updates for. |
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
| `detected_type` | string | **DEPRECATED.** Will always report `git_repo`. |
| `channel` | string | The configured update `channel`. |
| | | #git-repo-channel-desc |+
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
| | | configuration is not supported by the type. Will |^
| | | always be `false` for `git_repo` types as all channels |^
| | | are supported. |^
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
| | | enabled. In this condition updates may proceed when the |^
| | | repo's HEAD is detached. |^
| `is_valid` | bool | Set to `true` when repo detection completes and passes |
| | | all validity checks. |^
| `version` | string | The current detected version. |
| `remote_version` | string | The latest version available on the remote. |
| `rollback_version` | string | The version prior to the last update. This version is |
| | | used during a `rollback` request. |^
| `full_version_string` | string | The complete version string reported by `git describe`. |
| | | Generally includes an abbreviated hash of the current |^
| | | commit and tags such as "dirty" when appropriate. |^
| `remote_hash` | string | The latest available commit hash on the remote. |
| `current_hash` | string | The commit hash the local repo is currently on. |
| `remote_alias` | string | The git alias of the remote. The git default for the |
| | | primary alias is `origin`. |^
| `remote_url` | string | Full URL of the git remote matching the current |
| | | `remote_alias`. |^
| `recovery_url` | string | The `origin` git remote URL for this repo. This URL is |
| | | used to perform a `hard recovery` when requested. |^
| `owner` | string | The owner of the remote repo as detected from the remote |
| | | URL. |^
| `branch` | string | The name of the current git branch. |
| `repo_name` | string | The name of the remote repo as detected from the remote |
| | | URL. |^
| `is_dirty` | bool | Set to `true` if the repo is "dirty", ie: if one or |
| | | more files in the repo have been modified. |^
| `corrupt` | bool | Set to `true` if the repo is corrupt. This indicates |
| | | that the local repo is broken and needs to be recovered. |^
| `pristine` | bool | Set to `true` when the repo is clean and no untracked |
| | | files exist in the repo. |^
| `detached` | bool | Set to `true` when the git repo's HEAD is detached. |
| `git_messages` | [string] | An array of strings containing the output from a failed |
| | | `git` command during initialization or an update. This |^
| | | array will be empty if all `git` commands succeed. |^
| `anomalies` | [string] | An array of strings that describe anomalies found during |
| | | initialization. An anomaly can be defined as an |^
| | | unexpected condition that does not result in an |^
| | | `invalid` repo state. Updates may proceed when |^
| | | anomalies are detected. An example of an anomaly is the |^
| | | presence of "untracked files" in the repo. |^
| `warnings` | [string] | An array of strings that describe warnings detected |
| | | during repo initialization. When a warning is present |^
| | | the repo is marked invalid and updates are disabled. |^
| `commits_behind` | [object] | An array of `Commit Info` objects providing commit data |
| | | on upstream commits available for update. This array is |^
| | | limited to a size of 30 untagged commits. Any tagged |^
| | | commits within 100 commits behind are included. |^
| | | #git-commit-info-spec |+
| `commits_behind_count` | int | The total number of commits the current repo is behind |
| | | the next update. This number may be greater than the |^
| | | length of the `commits_behind` array. |^
| `info_tags` | object | An object containing custom tags added to the updater's |
| | | configuration in `moonraker.conf`. The values will |^
| | | always be strings. Client developers may define what |^
| | | tags, if any, users will configure. The software can |^
| | | then choose to display information or perform a |^
| | | specific action pre/post update if necessary. |^
{ #git-repo-status-spec } Git Repo Status
| Channel | Description |
| -------- | --------------------------------------------------------- |
| `stable` | The repo will update to the latest tagged stable release. |
| `beta` | The repo will update to the latest tag. This may include |
| | tags with `beta` and `release candidate` identifiers. |^
| `dev` | The repo will update to the latest available commit. |
{ #git-repo-channel-desc }
| Field | Type | Description |
| --------- | :------------: | ----------------------------------------------------- |
| `author` | string | The author of the commit. |
| `date` | string | The date of the commit in unix time. Note that the |
| | | date is extracted from the git log as a string value. |^
| | | It should be converted to an integer prior to |^
| | | processing from unix time. |^
| `sha` | string | The commit hash. |
| `subject` | string | The title of the commit. |
| `message` | string | The content in the body of the commit. |
| `tag` | string \| null | The name of the associated tag if present. Will be |
| | | null if the commit has no tag. |^
{ #git-commit-info-spec } Commit Info
| Field | Type | Description |
| ------------------ | :------: | -------------------------------------------------------- |
| `name` | string | The name of the software to manage updates for. |
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
| `channel` | string | The configured update `channel`. |
| | | #net-hosted-channel-desc |+
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
| | | configuration is not supported by the type. |^
| | | are supported. |^
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
| | | enabled. |^
| `owner` | string | The owner of the GitHub repo hosting the software. |
| `repo_name` | string | The name of the GitHub repo hosting the software. |
| `last_error` | string | A message associated with the last error encountered |
| | | after initialization or an update. Will be an empty |^
| | | string if no errors were detected. |^
| `version` | string | The current detected version. |
| `remote_version` | string | The version of the latest available release on GitHub. |
| `rollback_version` | string | The version prior to the last update. This version is |
| | | used during a `rollback` request. |^
| `is_valid` | bool | Set to `true` when the updater has completed |
| | | initialization and all validity checks passed. |^
| `anomalies` | [string] | An array of strings that describe anomalies found during |
| | | initialization. An anomaly can be defined as an |^
| | | unexpected condition that does not result in an |^
| | | `invalid` updater state. Updates may proceed when |^
| | | anomalies are detected. |^
| `warnings` | [string] | An array of strings that describe warnings detected |
| | | during initialization. When a warning is present |^
| | | the updater is marked invalid and updates are disabled. |^
| `info_tags` | object | An object containing custom tags added to the updater's |
| | | configuration in `moonraker.conf`. The values will |^
| | | always be strings. Client developers may define what |^
| | | tags, if any, users will configure. The software can |^
| | | then choose to display information or perform a |^
| | | specific action pre/post update if necessary. |^
{ #net-app-status-spec } Net Hosted Status
| Channel | Description |
| -------- | --------------------------------------------------------- |
| `stable` | The software will update to the stable release on GitHub. |
| `beta` | The software will update to the latest release on GitHub, |
| | including those marked as "pre-release". |^
{ #net-hosted-channel-desc }
| Field | Type | Description |
| --------------------- | :------------: | --------------------------------------------------------- |
| `name` | string | The name of the software to manage updates for. |
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
| `channel` | string | The configured update `channel`. |
| | | #python-channel-desc |+
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
| | | configuration is not supported by the type. |^
| | | are supported. |^
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
| | | enabled. |^
| `owner` | string | The owner of the GitHub repo hosting the software. |
| | | Will be a `?` when no repo owner is detected. |^
| `repo_name` | string | The name of the GitHub repo hosting the software. |
| | | Will be a `?` when no repo name is detected. |^
| `branch` | string \| null | The name of the branch on the GitHub remote to build |
| | | `dev` updates from. Will be `null` if no primary branch |^
| | | is configured. |^
| `version` | string | The current detected version. |
| `remote_version` | string | The version of the latest available release on GitHub. |
| `rollback_version` | string | The version prior to the last update. This version is |
| | | used during a `rollback` request. |^
| `full_version_string` | string | The complete version string extracted from the python |
| | | package's metadata. |^
| `current_hash` | string | The hash of the commit used to build the current version |
| | | of the package. A placeholder of `not-specified` is used |^
| | | when the the current hash is not provided in the package |^
| | | metadata. |^
| `remote_hash` | string | The hash of the latest update available. A placeholder of |
| | | `update-available` is used when the remote hash is not |^
| | | provided by the remote host and updates are available. |^
| `is_valid` | bool | Set to `true` when the updater has completed |
| | | initialization and all validity checks passed. |^
| `is_dirty` | bool | Set to `true` if the repo was modified at the time the |
| | | package was built. |^
| `changelog_url` | string | A URL to the software's changelog. Will be an empty |
| | | string if no changelog URL is detected. |^
| `anomalies` | [string] | An array of strings that describe anomalies found during |
| | | initialization. An anomaly can be defined as an |^
| | | unexpected condition that does not result in an |^
| | | `invalid` updater state. Updates may proceed when |^
| | | anomalies are detected. |^
| `warnings` | [string] | An array of strings that describe warnings detected |
| | | during initialization. When a warning is present |^
| | | the updater is marked invalid and updates are disabled. |^
| `info_tags` | object | An object containing custom tags added to the updater's |
| | | configuration in `moonraker.conf`. The values will |^
| | | always be strings. Client developers may define what |^
| | | tags, if any, users will configure. The software can |^
| | | then choose to display information or perform a |^
| | | specific action pre/post update if necessary. |^
{ #python-status-spec } Python Package Status
| Channel | Description |
| -------- | -------------------------------------------------------- |
| `stable` | The software will update to the stable release on GitHub |
| | or PyPI. |^
| `beta` | Only applies to packages installed via GitHub. The |
| | software will update to the latest release, including |^
| | hose marked as "pre-release". |^
| `dev` | Only applies to packages installed via GitHub. The |
| | software will update to the latest commit available. |^
{ #python-channel-desc }
| Field | Type | Description |
| ----------------- | :------: | -------------------------------------------------------- |
| `name` | string | The name of the software to manage updates for. Will |
| | | always be `system`. |^
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
| | | Will always be `system`. |^
| `package_count` | int | The number of system packages that require updating. |
| `package_list` | [string] | An array of package names that require updating. |
{ #system-status-spec } System Update Status
///
## Refresh update status
Refreshes the internal update state for the requested software.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/refresh
Content-Type: application/json
{
"name": "klipper"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.refresh",
"params": {
"name": "klipper"
},
"id": 4644
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------- | ----------------------------------------------------- |
| `name` | string | `null` | The name of the software to refresh. |
| | | | If omitted all registered software will be refreshed. |^
///
/// Note
This endpoint will raise 503 error under the following conditions:
- An update is in progress
- A print is in progress
- The update manager hasn't completed initialization
///
For an example response refer to the
[Status Example Response](#status-example-response).
/// api-response-spec
open: True
The response spec is identical to the
[Status Request Specification](#update-status-spec)
///
/// Tip
Applications should use care when calling this method as a refresh
is CPU intensive and may be time consuming. Moonraker can be
configured to refresh state periodically, thus it is recommended
that applications avoid their own procedural implementations.
Instead it is best to call this API only when a user requests a
refresh.
///
## Perform an Upgrade
*Added in API Version 1.5.0*
Upgrade to the most recent release of the requested software.
If an update is requested while a print is in progress then this
request will return an error.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/upgrade
Content-Type: application/json
{
"name": "app_name"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.upgrade",
"params": {
"name": "app_name"
},
"id": 8546
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------- | ------------------------------------ |
| `name` | string | null | The name of the software to upgrade. |
| | | | If omitted all registered |^
| | | | software updates will be upgraded. |^
///
```{.text .apiresponse title="Response"}
"ok"
```
## Recover a corrupt repo
On occasion a git command may fail resulting in a repo in a
dirty or invalid state. This endpoint may be used to attempt
to recover a git repo that is dirty, broken, or corrupt.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/recover
Content-Type: application/json
{
"name": "moonraker",
"hard": false
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.recover",
"params": {
"name": "moonraker",
"hard": false
},
"id": 4564
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------------ | --------------------------------------------------- |
| `name` | string | **REQUIRED** | The name of the software to recover. |
| `hard` | bool | false | Determines the [mode](#git-repo-recovery-mode-desc) |
| | | | used to perform the recovery. |^
| Name | Description |
| --------------- | ------------------------------------------------------- |
| `hard == false` | Moonraker will attempt to recover the repo by running |
| | `git reset`. This will generally work for repos that |^
| | are dirty, but will not correct repos that are corrupt. |^
| `hard == true` | Moonraker will remove the current repo and re-clone it. |
{ #git-repo-recovery-mode-desc } Recovery Modes
///
```{.text .apiresponse title="Response"}
"ok"
```
## Rollback to the previous version
```{.http .apirequest title="HTTP Request"}
POST /machine/update/rollback
Content-Type: application/json
{
"name": "moonraker"
}
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method": "machine.update.rollback",
"params": {
"name": "moonraker"
},
"id": 4564
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Perform a full update
*Deprecated in API Version 1.5.0, superseded by the*
*[Upgrade](#perform-an-upgrade) endpoint.*
Attempts to update all registered software. Updates are performed in the
following order:
- `system` if enabled
- All optional software configured in `moonraker.conf`.
- Klipper
- Moonraker
```{.http .apirequest title="HTTP Request"}
POST /machine/update/full
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.full",
"id": 4645
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Update Moonraker
*Deprecated in API Version 1.5.0, superseded by the*
*[Upgrade](#perform-an-upgrade) endpoint.*
Upgrades to the latest version of Moonraker and restarts
the service. If an update is requested while a print is in progress then
this request will return an error.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/moonraker
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.moonraker",
"id": 4645
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Update Klipper
*Deprecated in API Version 1.5.0, superseded by the*
*[Upgrade](#perform-an-upgrade) endpoint.*
Upgrades to the latest version of Klipper and restarts
the service. If an update is requested while a print is in progress
then this request will return an error.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/klipper
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.klipper",
"id": 5745
}
```
```{.text .apiresponse title="Response"}
"ok"
```
## Update Client
*Deprecated in API Version 1.5.0, superseded by the*
*[Upgrade](#perform-an-upgrade) endpoint.*
Update to the most recent release of the requested software.
If an update is requested while a print is in progress then this
request will return an error.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/client
Content-Type: application/json
{
"name": "app_name"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.client",
"params": {
"name": "app_name"
},
"id": 8546
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | ------- | ------------------------------------ |
| `name` | string | null | The name of the software to upgrade. |
| | | | If omitted all registered |^
| | | | software updates will be upgraded. |^
///
```{.text .apiresponse title="Response"}
"ok"
```
## Update System Packages
*Deprecated in API Version 1.5.0, superseded by the*
*[Upgrade](#perform-an-upgrade) endpoint.*
Upgrades system packages. If an update is requested while a print is
in progress then this request will return an error.
```{.http .apirequest title="HTTP Request"}
POST /machine/update/system
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "machine.update.system",
"id": 4564
}
```
```{.text .apiresponse title="Response"}
"ok"
```
+471
View File
@@ -0,0 +1,471 @@
# Webcam Management
Moonraker maintains webcam configuration in its database so
various applications and front-ends can share this configuration
through a consistent interface. The endpoints in this section
may be used to manage various webcam configurations.
/// note
Moonraker does not directly manipulate webcams.
External applications, such as
[crowsnest](https://github.com/mainsail-crew/crowsnest),
handle direct webcam functionality.
///
## List Webcams
```{.http .apirequest title="HTTP Request"}
GET /server/webcams/list
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.webcams.list",
"id": 4654
}
```
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"webcams": [
{
"name": "testcam3",
"location": "door",
"service": "mjpegstreamer",
"enabled": true,
"icon": "mdiWebcam",
"target_fps": 20,
"target_fps_idle": 5,
"stream_url": "http://camera.lan/webcam?action=stream",
"snapshot_url": "http://camera.lan/webcam?action=snapshot",
"flip_horizontal": false,
"flip_vertical": true,
"rotation": 90,
"aspect_ratio": "4:3",
"extra_data": {},
"source": "config",
"uid": "55d3801e-fdc1-438d-8728-2fff8b83b909"
},
{
"name": "tc2",
"location": "printer",
"service": "mjpegstreamer",
"enabled": true,
"icon": "mdiWebcam",
"target_fps": 15,
"target_fps_idle": 5,
"stream_url": "http://printer.lan/webcam?action=stream",
"snapshot_url": "http://printer.lan/webcam?action=snapshot",
"flip_horizontal": false,
"flip_vertical": false,
"rotation": 0,
"aspect_ratio": "4:3",
"extra_data": {},
"source": "database",
"uid": "65e51c8a-6763-41d4-8e76-345bb6e8e7c3"
},
{
"name": "TestCam",
"location": "printer",
"service": "mjpegstreamer",
"enabled": true,
"icon": "mdiWebcam",
"target_fps": 15,
"target_fps_idle": 5,
"stream_url": "/webcam/?action=stream",
"snapshot_url": "/webcam/?action=snapshot",
"flip_horizontal": false,
"flip_vertical": false,
"rotation": 0,
"aspect_ratio": "4:3",
"extra_data": {},
"source": "database",
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
}
]
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| --------- | :------: | ------------------------------------------------------- |
| `webcams` | [object] | An array of [Webcam Entry](#webcam-entry-spec) objects. |
| Field | Type | Description |
| ----------------- | :----: | ------------------------------------------------------------- |
| `name` | string | Friendly name of the webcam. |
| `location` | string | A single word description of where the webcam |
| | | is located or what it is viewing. |^
| `service` | string | The name of the webcam streaming service used to |
| | | operate the webcam. |^
| `enabled` | bool | Set to `true` when the webcam is available, `false` |
| | | otherwise. |^
| `icon` | string | Name of the icon associated with the webcam. |
| `target_fps` | int | Target frames per second when the printer is active. |
| `target_fps_idle` | int | Target frames per second when the printer is idle. |
| `stream_url` | string | The url for the webcam's stream request. This may |
| | | be a complete url, or a url path relative to |^
| | | Moonraker's host. |^
| `snapshot_url` | string | The url for the webcam's snapshot request. This may |
| | | be a complete url, or a url path relative to |^
| | | Moonraker's host. If the webcam does not support |^
| | | a snapshot url this will be an empty string. |^
| `flip_horizontal` | bool | A value of `true` indicates that the stream should |
| | | be flipped horizontally. |^
| `flip_vertical` | bool | A value of `true` indicates that the stream should |
| | | be flipped vertically. |^
| `rotation` | int | Indicates the amount of clockwise rotation, in |
| | | degrees, that should be applied to the stream. May |^
| | | be 0, 90, 180, or 270. |^
| `aspect_ratio` | string | Indicates the aspect ratio of the stream. The format |
| | | should be `W:H`, for example `4:3` or `16:9`. |^
| `extra_data` | object | An object containing custom configuration added by |
| | | frontends. |^
| `source` | string | The [configuration source](#webcam-configuration-source-desc) |
| | | of the webcam entry. |^
| `uid` | string | A unique identifier assigned to the webcam entry. |
{ #webcam-entry-spec } Webcam Entry
| Source | Description |
| ---------- | -------------------------------------------------------------- |
| `database` | The webcam's configuration is stored in Moonraker's database. |
| | These entries are generally added by front-ends via the webcam |^
| | API. Front-ends may modify and remove these entries. |^
| `config` | The webcam's configuration is sourced from `moonraker.conf`. |
| | The webcam endpoints can not modify or remove these entries. |^
{ #webcam-configuration-source-desc } Configuration Source
//// note
Moonraker does not provide a specification for the `location`, `service`,
and `icon` fields. These fields can contain any string value, generally
front-ends set these values based on their needs. Developers should
consider using the same values that existing front-ends (such as Mainsail
and Fluidd) currently use to maintain compatibility.
////
///
## Get Webcam Information
```{.http .apirequest title="HTTP Request"}
GET /server/webcams/item?uid=341778f9-387f-455b-8b69-ff68442d41d9
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.webcams.get_item",
"params": {
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | -------------- | ----------------------------------------------- |
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
| | | | this parameter is considered required, if |^
| | | | omitted the request will fall back on looking |^
| | | | up the camera by `name`. |^
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
| | | | parameter is deprecated, all future |^
| | | | implementations should use the `uid` parameter. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"webcam": {
"name": "TestCam",
"location": "printer",
"service": "mjpegstreamer",
"enabled": true,
"icon": "mdiWebcam",
"target_fps": 15,
"target_fps_idle": 5,
"stream_url": "/webcam/?action=stream",
"snapshot_url": "/webcam/?action=snapshot",
"flip_horizontal": false,
"flip_vertical": false,
"rotation": 0,
"aspect_ratio": "4:3",
"extra_data": {},
"source": "database",
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :----: | ----------------------------------------------- |
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
| | | the requested webcam. |^
///
## Add or update a webcam
Adds a new webcam entry or updates an existing entry. When updating
an entry only the fields provided will be modified.
/// Note
A webcam configured in `moonraker.conf` cannot be updated or
overwritten using this API.
///
```{.http .apirequest title="HTTP Request"}
POST /server/webcams/item
Content-Type: application/json
{
"name": "cam_name",
"snapshot_url": "http://printer.lan:8080/webcam?action=snapshot",
"stream_url": "http://printer.lan:8080/webcam?action=stream"
}
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.webcams.post_item",
"params": {
"name": "cam_name",
"snapshot_url": "/webcam?action=snapshot",
"stream_url": "/webcam?action=stream"
},
"id": 4654
}
```
/// api-parameters
open: True
//// note
The default values in the parameter specification below apply to *new* webcam
entries. Existing entries to be updated only require the `uid` parameter,
all other parameters default to their existing value.
////
| Name | Type | Default | Description |
| ----------------- | :----: | --------------- | ---------------------------------------------------- |
| `uid` | string | null | The unique ID of an existing Webcam Entry to |
| | | | modify. If omitted the request will attempt |^
| | | | to create a new Webcam Entry, otherwise the |^
| | | | existing entry will be updated. |^
| `name` | string | **REQUIRED** | The friendly name of the webcam. Each webcam |
| | | | entry must have a *unique* name. |^
| `location` | string | "printer" | A single word description of where the webcam |
| | | | is located or what it is viewing. |^
| `icon` | string | "mdiWebcam" | Name of the icon associated with the webcam. |
| `enabled` | bool | true | Set to `true` when the webcam is available, `false` |
| | | | otherwise. |^
| `service` | string | "mjpegstreamer" | The name of the webcam streaming service used to |
| | | | operate the webcam. |^
| `target_fps` | int | 15 | Target frames per second when the printer is active. |
| `target_fps_idle` | int | 5 | Target frames per second when the printer is idle. |
| `stream_url` | string | **REQUIRED** | The url for the webcam's stream request. This may |
| | | | be a complete url or a url path relative to |^
| | | | Moonraker's host. |^
| `snapshot_url` | string | "" | The url for the webcam's snapshot request. This may |
| | | | be a complete url or a url path relative to |^
| | | | Moonraker's host. |^
| `flip_horizontal` | bool | false | A value of `true` indicates that the stream should |
| | | | be flipped horizontally. |^
| `flip_vertical` | bool | false | A value of `true` indicates that the stream should |
| | | | be flipped vertically. |^
| `rotation` | int | 0 | Indicates the amount of clockwise rotation, in |
| | | | degrees, that should be applied to the stream. May |^
| | | | be 0, 90, 180, or 270. |^
| `aspect_ratio` | string | "4:3" | Indicates the aspect ratio of the stream. The format |
| | | | should be `W:H`, for example `4:3` or `16:9`. |^
| `extra_data` | object | {} | An object containing custom configuration added by |
| | | | frontends. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"webcam": {
"name": "TestCam",
"location": "printer",
"service": "mjpegstreamer",
"enabled": true,
"icon": "mdiWebcam",
"target_fps": 15,
"target_fps_idle": 5,
"stream_url": "/webcam/?action=stream",
"snapshot_url": "/webcam/?action=snapshot",
"flip_horizontal": false,
"flip_vertical": false,
"rotation": 0,
"aspect_ratio": "4:3",
"extra_data": {},
"source": "database",
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :----: | ----------------------------------------------- |
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
| | | the new or updated webcam. |^
///
## Delete a webcam
/// Note
A webcam configured via `moonraker.conf` cannot be deleted
using this API.
///
```{.http .apirequest title="HTTP Request"}
DELETE /server/webcams/item?uid=341778f9-387f-455b-8b69-ff68442d41d9
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.webcams.delete_item",
"params": {
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | -------------- | ----------------------------------------------- |
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
| | | | this parameter is considered required, if |^
| | | | omitted the request will fall back on looking |^
| | | | up the camera by `name`. |^
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
| | | | parameter is deprecated, all future |^
| | | | implementations should use the `uid` parameter. |^
///
Parameters:
- `uid`: The webcam's assigned unique ID. This parameter is optional, when
not specified the request will fallback to the `name` parameter.
- `name`: The name of the webcam to delete. If the named webcam is not
available the request will return with an error. This parameter must
be provided when the `uid` is omitted.
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"webcam": {
"name": "TestCam",
"location": "printer",
"service": "mjpegstreamer",
"target_fps": 15,
"stream_url": "/webcam/?action=stream",
"snapshot_url": "/webcam/?action=snapshot",
"flip_horizontal": false,
"flip_vertical": false,
"rotation": 0,
"source": "database",
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
}
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| -------- | :----: | ----------------------------------------------- |
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
| | | the deleted webcam. |^
///
## Test a webcam
Resolves a webcam's stream and snapshot urls. If the snapshot
is served over http, a test is performed to see if the url is
reachable.
```{.http .apirequest title="HTTP Request"}
POST /server/webcams/test?uid=341778f9-387f-455b-8b69-ff68442d41d9
```
```{.json .apirequest title="JSON-RPC Request"}
{
"jsonrpc": "2.0",
"method": "server.webcams.test",
"params": {
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
},
"id": 4654
}
```
/// api-parameters
open: True
| Name | Type | Default | Description |
| ------ | :----: | -------------- | ----------------------------------------------- |
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
| | | | this parameter is considered required, if |^
| | | | omitted the request will fall back on looking |^
| | | | up the camera by `name`. |^
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
| | | | parameter is deprecated, all future |^
| | | | implementations should use the `uid` parameter. |^
///
/// collapse-code
```{.json .apiresponse title="Example Response"}
{
"name": "TestCam",
"snapshot_reachable": true,
"snapshot_url": "http://127.0.0.1:80/webcam/?action=snapshot",
"stream_url": "http://127.0.0.1:80/webcam/?action=stream"
}
```
///
/// api-response-spec
open: True
| Field | Type | Description |
| -------------------- | :----: | ------------------------------------------ |
| `name` | string | The friendly name of the webcam tested. |
| `snapshot_reachable` | bool | Value will be `true` if Moonraker is able |
| | | to successfully resolve and connect to the |^
| | | snapshot url. |^
| `snapshot_url` | string | The resolved snapshot url. |
| `stream_url` | string | The resolved stream url. |
///
+22
View File
@@ -0,0 +1,22 @@
# 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). Communication 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.
Front end and other client developers may refer to the
[External API](./external_api/introduction.md)
documentation.
Backend developers should refer to the
[contributing](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.
+708 -104
View File
@@ -1,19 +1,44 @@
## Installation
#
This document provides a guide on how to install Moonraker on a Raspberry
Pi running Raspian/Rasperry Pi OS. Other SBCs and/or linux distributions
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.
This document provides a guide on how to install Moonraker on a Debian
based Linux Distributions. Other linux distributions 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. After installation you should make
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
[Klipper's Documentation](https://klipper3d.com/Overview.html) for details.
After installing Klipper you should make sure to add Moonraker's
[configuration requirements](#klipper-configuration-requirements).
After Klipper is installed, you need to modify its "default" file. This file
contains klipper's command line arguments, and you must add an argument that
instructs Klippy to create a Unix Domain socket:
### Klipper Configuration Requirements
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
```
### Enabling Klipper's Unix Domain Socket Server
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:
```
sudo nano /etc/default/klipper
```
@@ -28,7 +53,7 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
```
You need to add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
Add `-a /home/pi/printer_data/comms/klippy.sock` to KLIPPY_ARGS:
```
# Configuration for /etc/init.d/klipper
@@ -36,14 +61,17 @@ 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"
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /home/pi/printer_data/comms/klippy.sock
```
You may also want to take this opportunity to change the location of
printer.cfg to match Moonraker's "config_path" option (see the
[configuration document](configuration.md#primary-configuration)
for more information on the config_path). For example, if the `config_path`
option is set to `~/printer_config`, your klipper defaults file might look
like the following:
!!! 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
@@ -51,123 +79,699 @@ KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_data/config/printer.cfg -l /home/pi/printer_data/logs/klippy.log -a /home/pi/printer_data/comms/klippy.sock"
```
If necessary, create the config directory and move printer.cfg to it:
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
Moonraker provides an install script that can be used to facilitate
installation. The type of installation depends on where the install
script is located on the host file system. If the install script is
downloaded and run individually, the script will install Moonraker as
a Python Package using pip. If the script is run from Moonraker's
original source it will install Moonraker from source.
Prior to installation it is necessary to open a terminal on the host
machine, or SSH into it. It is recommended to read this entire
section before proceeding with the installation.
### Installing the Moonraker Python package
The Python Package version of Moonraker will receive fewer updates, and
should generally be more stable. This is intended for users that do
not need to run unofficial 3rd party extensions, such as
[Moonraker-Timelapse](https://github.com/mainsail-crew/moonraker-timelapse),
and do not desire to run the "bleeding edge" version of Moonraker.
To perform this installation, download Moonraker's
[install script](https://raw.githubusercontent.com/Arksine/moonraker/master/scripts/install-moonraker.sh)
from Github, then run the installer:
```
cd ~
mkdir printer_config
mv printer.cfg printer_config
```
You can now install the Moonraker application:
```
cd ~
git clone https://github.com/Arksine/moonraker.git
```
Prior to installation it is a good idea to create
[moonraker.conf](configuration.md). If you are using the `config_path`,
create it in the specified directory otherwise create it in the HOME
directory. A sample `moonraker.conf` may be found in the `docs` folder
of this repo.
For a default installation run the following commands:
```
cd ~/moonraker/scripts
wget https://raw.githubusercontent.com/Arksine/moonraker/master/scripts/install-moonraker.sh
./install-moonraker.sh
```
Or to install with `moonraker.conf` in the `config_path`:
### Installing Moonraker from source
Moonraker can be run directly from source. This method of installation will
clone Moonraker's git repository, and may receive frequent bleeding edge
updates. Users who want to test Moonraker, run unofficial modifications, and
do not mind SSHing into the host to correct issues should choose this option.
To install Moonraker from source, clone its git repository then run the installer:
```
cd ~/moonraker/scripts
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
cd ~
git clone https://github.com/Arksine/moonraker.git
~/moonraker/scripts/install-moonraker.sh
```
The install script has a few command line options that may be useful,
### Customizing the installation
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
[configuration documentation](./configuration.md).
The install script has several command line options that may be useful,
particularly for those upgrading:
- -r\
This will rebuild the virtual environment for existing installations.
Sometimes this is necessary when a dependency has been added.
- -f\
This will tell the script to overwrite Moonraker's "defaults" file.
By default the script will not modify the "defaults" file if it is
detected as present.
- -c /path/to/moonraker.conf\
This allows the user to specify the path to Moonraker's config file.
The default location is `/home/<user>/moonraker.conf`.
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
- `-f`:
Force an overwrite of Moonraker's systemd script. In addition, a
new `moonraker.env` file will be created, and the PolKit rules will
be re-installed. By default these items will not be modified if
they exist.
- `-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 configuration 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.
- `-s`:
Installs Moonraker's [speedup](#optional-speedups) Python packages in the
Python environment.
Now you may install a client, such as
[Mainsail](https://github.com/meteyou/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd)
Additionally, installation may be customized with the following environment
variables:
- `MOONRAKER_VENV`
- `MOONRAKER_REBUILD_ENV`
- `MOONRAKER_FORCE_SYSTEM_INSTALL`
- `MOONRAKER_DISABLE_SYSTEMCTL`
- `MOONRAKER_SKIP_POLKIT`
- `MOONRAKER_CONFIG_PATH`
- `MOONRAKER_LOG_PATH`
- `MOONRAKER_DATA_PATH`
- `MOONRAKER_SPEEDUPS`
When the script completes it should start the Moonraker system service. If Klipper
is running and Moonraker is able to establish a connection the following log entry
should be available in `klippy.log`:
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
Now you may wish to install a frontend, such as
[Mainsail](https://github.com/mainsail-crew/mainsail) or
[Fluidd](https://github.com/fluidd-core/fluidd).
!!! Note
Moonraker's installer does not include nginx as a 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`.
## Command line Usage
The configuration and log file paths may be specified via the command
line.
```
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
/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
│   └── moonraker-sql.db
├── 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 desirable 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. See the
[environment file section](#the-environment-file) for details.
- The `ExecStart` field begins with the python executable, followed by
by the environment variable `MOONRAKER_ARGS`. This variable is set in
the environment file.
## 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] [-d <data path>] [-c <configfile>] [-l <logfile>] [-u <unixsocket>] [-n] [-v] [-g] [-o]
Moonraker - Klipper API Server
optional arguments:
options:
-h, --help show this help message and exit
-d <data path>, --datapath <data path>
Location of Moonraker Data File Path
-c <configfile>, --configfile <configfile>
Location of moonraker configuration file
Path to Moonraker's configuration file
-l <logfile>, --logfile <logfile>
log file name and location
Path to Moonraker's log file
-u <unixsocket>, --unixsocket <unixsocket>
Path to Moonraker's unix domain socket
-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:
- config file path- `~/moonraker.conf`
- log file path - `/tmp/moonraker.log`
- `data path`: `$HOME/printer_data`
- `config file`: `$HOME/printer_data/config/moonraker.conf`
- `log file`: `$HOME/printer_data/logs/moonraker.log`
- `unix socket`: `$HOME/printer_data/comms/moonraker.sock`
- logging to a file is enabled
- Verbose logging is disabled
- Moonraker's debug features are disabled
- The asyncio debug flag is set to false
If one needs to start moonraker without generating a log file, the
'-n' option may be used, for example:
!!! 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.
!!! Warning
Moonraker's `--unixsocket` option should not be confused with Klipper's
`--api-server` option. The `unixsocket` option for Moonraker specifies
the path where Moonraker will create a unix domain socket that serves its
JSON-RPC API.
If is necessary to run Moonraker without logging to a file the
`-n` option may be used, for example:
```
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -d ~/printer_data -n
```
In general it is not recommended to install moonraker with this option.
While moonraker will still log to stdout, all requests for support must
be accompanied by moonraker.log.
These options may be changed by editing
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
may also be used to modify the config file location.
!!! Tip
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`.
## Prerequisites (Klipper Configuration)
Each command line argument has an associated environment variable that may
be used to specify options in place of the command line.
Moonraker depends on the following Klippy extras for full functionality:
- [virtual_sdcard]
- [pause_resume]
- [display_status]
- `MOONRAKER_DATA_PATH="<data path>"`: equivalent to `-d <data path>`
- `MOONRAKER_CONFIG_PATH="<configfile>"`: equivalent to `-c <configfile>`
- `MOONRAKER_LOG_PATH="<logfile>"`: equivalent to `-l <logfile>`
- `MOONRAKER_UDS_PATH="<unixsocket>"`: equivalent to `-u <unixsocket>`
- `MOONRAKER_DISABLE_FILE_LOG="y"`: equivalent to `-n`
- `MOONRAKER_VERBOSE_LOGGING="y"`: equivalent to `-v`
- `MOONRAKER_ENABLE_DEBUG="y"`: equivalent to `-g`.
- `MOONRAKER_ASYNCIO_DEBUG="y"`: equivalent to `-o`
!!! Note
Command line arguments take priority over environment variables when
both are specified.
[The environment file](#the-environment-file) may be used to set Moonraker's
command line arguments and/or environment variables.
## 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:
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:
```
[pause_resume]
[display_status]
[virtual_sdcard]
path: ~/gcode_files
MOONRAKER_DATA_PATH="/home/pi/printer_data"
MOONRAKER_ARGS="-m moonraker"
PYTHONPATH="/home/pi/moonraker"
```
NOTES:
- Make sure that Moonraker (and Klipper) has read and write access to the
directory set in the `path` option for the `virtual_sdcard`.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
Once Moonraker receives the path it will retain it regardless of Klippy's
state, and update it if the path is changed in printer.cfg.
Please see [configuration.md](configuration.md) for details on how to
configure moonraker.conf.
A legacy installation converted to the updated flexible service unit
might contain the following. Note that this example uses command line
arguments instead of environment variables, either would be acceptable:
```
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
[arguments and/or environment variables](#command-line-usage)
supplied to Moonraker by editing this file and restarting the service.
The following example sets a custom config file path, log file path,
enables verbose logging, and enables debug features:
```
MOONRAKER_DATA_PATH="/home/pi/printer_data"
MOONRAKER_CONFIG_PATH="/home/pi/printer_data/config/moonraker-1.conf"
MOONRAKER_LOG_PATH="/home/pi/printer_data/logs/moonraker-1.log"
MOONRAKER_VERBOSE_LOGGING="y"
MOONRAKER_ENABLE_DEBUG="y"
MOONRAKER_ARGS="-m moonraker"
PYTHONPATH="/home/pi/moonraker"
```
## Optional Speedups
Moonraker supports two optional Python packages that can be used to reduce
its CPU load:
- [msgspec](https://github.com/jcrist/msgspec): Replaces the builtin `json`
encoder/decoder. Requires Python >= 3.8.
- [uvloop](https://github.com/MagicStack/uvloop/): Replaces the default asyncio
eventloop implementation.
If these packages are installed in Moonraker's python environment Moonraker will
load them. For existing installations this can be done manually with a command
like:
```
~/moonraker-env/bin/pip install -r ~/moonraker/scripts/moonraker-speedups.txt
```
After installing the speedup packages it is possible to revert back to the
default implementation by specifying one or both of the following
environment variables in [moonraker.env](#the-environment-file):
- `MOONRAKER_ENABLE_MSGSPEC="n"`
- `MOONRAKER_ENABLE_UVLOOP="n"`
## 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 authorized 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
```
!!! 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.
```shell
cd ~/moonraker/scripts
./install-moonraker.sh
```
2) Configure Moonraker to use the legacy backend implementations for
the `machine` and/or `update_manager` components, ie:
```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
```
!!! 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:
```
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
```
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):
```
cd ~/moonraker/scripts
./fetch-apikey.sh
```
Additionally its possible to generate a new API Key with the `-g`
option:
```
cd ~/moonraker/scripts
./fetch-apikey.sh -g
```
If Moonraker is running it must be restarted for the new API key to
take affect:
```
sudo systemctl restart moonraker
```
#### Retrieve the API Key via the browser from a trusted client:
- 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"}
## Database Backup and Restore
Moonraker stores persistent data using an Sqlite database. By default
the database file is located at `<data_folder>/database/moonraker-sql.db`.
API Endpoints are available to backup and restore the database. All
backups are stored at `<data_folder>/backup/database/<backup_name>` and
restored from the same location. Database files may contain sensitive
information, therefore they are not served by Moonraker. Another protocol
such as SCP, SMB, etc is required to transfer a backup off of the host.
Alternatively it is possible to perform a manual backup by copying the
existing database file when the Moonraker service has been stopped.
Restoration can be performed by stopping the Moonraker service and
overwriting the existing database with the backup.
### LDMB Database (deprecated)
Previous versions of Moonraker used 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
```
+16 -2
View File
@@ -1,9 +1,12 @@
# 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: True
config_path: ~/printer_config
enable_debug_logging: False
[authorization]
enabled: True
@@ -13,3 +16,14 @@ trusted_clients:
cors_domains:
# Allow CORS requests for Fluidd
http://app.fluidd.xyz
# Enable OctoPrint compatibility for Slicer uploads
# Supports Cura, Slic3r, and Slic3r derivatives
# (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
+2243 -250
View File
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
# The MIT License (MIT)
#
# Copyright (c) 2014 - 2023 Isaac Muse
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# flake8: noqa
"""Collapsible code."""
import xml.etree.ElementTree as etree
from markdown import util as mutil
import re
from pymdownx.blocks.block import Block
from pymdownx.blocks import BlocksExtension
# Fenced block placeholder for SuperFences
FENCED_BLOCK_RE = re.compile(
r'^([\> ]*){}({}){}$'.format(
mutil.HTML_PLACEHOLDER[0],
mutil.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)',
mutil.HTML_PLACEHOLDER[-1]
)
)
class CollapseCode(Block):
"""Collapse code."""
NAME = 'collapse-code'
def on_init(self):
"""Handle initialization."""
# Track tab group count across the entire page.
if 'collapse_code_count' not in self.tracker:
self.tracker['collapse_code_count'] = 0
self.expand = self.config['expand_text']
if not isinstance(self.expand, str):
raise ValueError("'expand_text' must be a string")
self.collapse = self.config['collapse_text']
if not isinstance(self.collapse, str):
raise ValueError("'collapse_text' must be a string")
self.expand_title = self.config['expand_title']
if not isinstance(self.expand_title, str):
raise ValueError("'expand_title' must be a string")
self.collapse_title = self.config['collapse_title']
if not isinstance(self.collapse_title, str):
raise ValueError("'collapse_title' must be a string")
def on_create(self, parent):
"""Create the element."""
self.count = self.tracker['collapse_code_count']
self.tracker['collapse_code_count'] += 1
el = etree.SubElement(parent, 'div', {'class': 'collapse-code'})
etree.SubElement(
el,
'input',
{
"type": "checkbox",
"id": "__collapse{}".format(self.count),
"name": "__collapse{}".format(self.count),
'checked': 'checked'
}
)
return el
def on_end(self, block):
"""Convert non list items to details."""
el = etree.SubElement(block, 'div', {'class': 'code-footer'})
attrs = {'for': '__collapse{}'.format(self.count), 'class': 'expand', 'tabindex': '0'}
if self.expand_title:
attrs['title'] = self.expand_title
expand = etree.SubElement(el, 'label', attrs)
expand.text = self.expand
attrs = {'for': '__collapse{}'.format(self.count), 'class': 'collapse', 'tabindex': '0'}
if self.collapse_title:
attrs['title'] = self.collapse_title
collapse = etree.SubElement(el, 'label', attrs)
collapse.text = self.collapse
class CollapseCodeExtension(BlocksExtension):
"""Admonition Blocks Extension."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'expand_text': ['Expand', "Set the text for the expand button."],
'collapse_text': ['Collapse', "Set the text for the collapse button."],
'expand_title': ['expand', "Set the text for the expand title."],
'collapse_title': ['collapse', "Set the text for the collapse title."]
}
super().__init__(*args, **kwargs)
def extendMarkdownBlocks(self, md, blocks):
"""Extend Markdown blocks."""
blocks.register(CollapseCode, self.getConfigs())
def makeExtension(*args, **kwargs):
"""Return extension."""
return CollapseCodeExtension(*args, **kwargs)
+7
View File
@@ -0,0 +1,7 @@
from setuptools import setup
setup(
name='pymdown_extras',
version='1.0.0',
py_modules=['collapse_code'],
install_requires=['pymdown-extensions>=10.7'],
)
+2
View File
@@ -0,0 +1,2 @@
:root>*{--md-code-link-bg-color:hsla(0, 0%, 96%, 1);--md-code-link-accent-bg-color:var(--md-code-link-bg-color);--md-default-bg-color--trans:rgb(100%, 100%, 100%, 0);--md-code-title-bg-color:var(--md-code-bg-color);--md-code-inline-bg-color:var(--md-code-bg-color);--md-code-special-bg-color:#e8e8e8;--md-code-alternate-bg-color:var(--md-code-bg-color);--md-code-hl-punctuation-color:var(--md-code-fg-color);--md-code-hl-namespace-color:var(--md-code-fg-color);--md-code-hl-entity-color:var(--md-code-hl-keyword-color);--md-code-hl-tag-color:var(--md-code-hl-keyword-color);--md-code-hl-builtin-color:var(--md-code-hl-constant-color);--md-code-hl-class-color:var(--md-code-hl-function-color);--md-typeset-a-color:#00bcd4;--md-progress-stripe:var(--md-default-bg-color--lighter);--md-progress-100:#00e676;--md-progress-80:#00e676;--md-progress-60:#fbc02d;--md-progress-40:#ff9100;--md-progress-20:#ff5252;--md-progress-0:#ff1744;--md-typeset-kbd-color:#ebebeb;--md-typeset-kbd-border-color:#b8b8b8;--md-typeset-kbd-accent-color:hsla(0, 100%, 100%, 1)}:root>[data-md-color-scheme=slate]{--md-code-link-bg-color:hsla(232, 15%, 15%, 1);--md-code-link-accent-bg-color:var(--md-code-link-bg-color);--md-code-special-bg-color:#2b2d3b;--md-default-bg-color--trans:hsla(232,15%,15%, 0);--md-default-bg-color--ultra-dark:#111217;--md-code-title-bg-color:var(--md-primary-fg-color--dark);--md-shadow-z2:0 0.2rem 0.5rem hsla(0, 0%, 0%, 0.3),0 0 0.05rem hsla(0, 0%, 0%, 0.2);--md-typeset-kbd-color:var(--md-default-fg-color--lightest);--md-typeset-kbd-border-color:#1a1c24;--md-typeset-kbd-accent-color:var(--md-default-fg-color--lighter)}:root>[data-md-color-scheme=dracula]{--md-default-fg-color:rgba(248, 248, 242, 0.87);--md-default-fg-color--light:rgba(248, 248, 242, 0.54);--md-default-fg-color--lighter:rgba(248, 248, 242, 0.16);--md-default-fg-color--lightest:rgba(248, 248, 242, 0.07);--md-default-autocomplete-fg-color:rgba(248, 248, 242, 0.4);--md-shadow-z2:0 0.2rem 0.5rem hsla(0, 0%, 0%, 0.3),0 0 0.05rem hsla(0, 0%, 0%, 0.2);--md-default-bg-color:var(--md-default-bg-color--darkest);--md-default-bg-color--light:rgba(50, 52, 67, 0.7);--md-default-bg-color--lighter:rgba(50, 52, 67, 0.3);--md-default-bg-color--lightest:rgba(50, 52, 67, 0.12);--md-default-bg-color--trans:rgba(50, 52, 67, 0);--md-default-bg-color--dark:#2b2e3b;--md-default-bg-color--darker:#252732;--md-default-bg-color--darkest:#1e2029;--md-default-bg-color--ultra-dark:#111217;--md-text-color:var(--md-default-fg-color);--md-typeset-color:var(--md-default-fg-color);--md-admonition-fg-color:var(--md-default-fg-color);--md-code-fg-color:hsl(60, 30%, 96%);--md-code-bg-color:hsl(231, 15%, 18%);--md-code-title-bg-color:var(--md-default-bg-color--ultra-dark);--md-code-inline-bg-color:#323443;--md-code-hl-operator-color:hsl(326, 100%, 74%);--md-code-hl-punctuation-color:hsl(60, 30%, 96%);--md-code-hl-string-color:hsl(65, 92%, 76%);--md-code-hl-special-color:hsl(265, 89%, 78%);--md-code-hl-number-color:hsl(265, 89%, 78%);--md-code-hl-keyword-color:hsl(326, 100%, 74%);--md-code-hl-name-color:hsl(60, 30%, 96%);--md-code-hl-constant-color:hsl(265, 89%, 78%);--md-code-hl-function-color:hsl(135, 94%, 65%);--md-code-hl-comment-color:hsl(225, 27%, 51%);--md-code-hl-variable-color:hsl(31, 100%, 71%);--md-code-hl-generic-color:hsl(225, 27%, 51%);--md-code-hl-color:hsl(231, 25%, 25%);--md-code-hl-entity-color:hsl(135, 94%, 65%);--md-code-hl-tag-color:hsl(326, 100%, 74%);--md-code-hl-namespace-color:hsl(60, 30%, 96%);--md-code-hl-builtin-color:hsl(191, 97%, 77%);--md-code-hl-class-color:hsl(191, 97%, 77%);--md-code-special-bg-color:#1c1e26;--md-code-alternate-bg-color:#3d3e49;--md-code-link-bg-color:#364653;--md-typeset-a-color:hsl(191, 97%, 77%);--md-typeset-mark-color:#6e7252;--md-typeset-del-color:#734568;--md-typeset-ins-color:#36724e;--md-progress-stripe:var(--md-default-bg-color--lightest);--md-progress-100:hsl(135, 94%, 65%);--md-progress-80:hsl(135, 92%, 79%);--md-progress-60:hsl(65, 92%, 76%);--md-progress-40:hsl(31, 100%, 71%);--md-progress-20:hsl(326, 100%, 74%);--md-progress-0:hsl(0, 100%, 67%);--md-typeset-kbd-color:var(--md-default-fg-color--lightest);--md-typeset-kbd-border-color:var(--md-default-bg-color--ultra-dark);--md-typeset-kbd-accent-color:var(--md-default-fg-color--lighter)}[data-md-color-scheme=dracula] :not([data-md-color-scheme])[data-md-color-primary=red],[data-md-color-scheme=dracula][data-md-color-primary=red]{--md-primary-code-bg-color:#47303a;--md-primary-fg-color:hsla(0deg, 100%, 67%, 1);--md-primary-fg-color--transparent:hsla(0deg, 100%, 67%, 0.1);--md-primary-fg-color--light:hsla(0deg, 100%, 72%, 1);--md-primary-fg-color--dark:hsla(0deg, 100%, 62%, 1);--md-primary-bg-color:var(--md-default-bg-color);--md-primary-bg-color--light:var(--md-default-bg-color--light)}[data-md-color-scheme=dracula] :not([data-md-color-scheme])[data-md-color-primary=pink],[data-md-color-scheme=dracula][data-md-color-primary=pink]{--md-primary-code-bg-color:#47354b;--md-primary-fg-color:hslLine truncated
/*# sourceMappingURL=extra-950ac449d4.css.map */
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["palette/_colors.scss","extra.css","extensions/_highlight.scss","extensions/_tables.scss","utilities/_break.scss"],"names":[],"mappings":"AAEA,QAEE,wBAAA,oBACA,+BAAA,6BACA,6BAAA,yBACA,yBAAA,wBACA,0BAAA,wBAEA,2BAAA,QACA,6BAAA,wBAEA,+BAAA,wBACA,6BAAA,wBAEA,0BAAA,gCACA,uBAAA,gCACA,2BAAA,iCACA,yBAAA,iCAGA,qBAAA,QAGA,qBAAA,oCACA,kBAAA,QACA,iBAAA,QACA,iBAAA,QACA,iBAAA,QACA,iBAAA,QACA,gBAAA,QAGA,uBAAA,QACA,8BAAA,QACA,8BAAA,uBAEA,mCAEE,wBAAA,uBACA,+BAAA,6BACA,2BAAA,QACA,6BAAA,qBAEA,kCAAA,QAGA,yBAAA,iCAGA,eAAA,EAAA,OAAA,OAAA,oBAAA,CCjBmC,EAAE,EAAE,QAAQ,qBDqB/C,uBAAA,qCACA,8BAAA,QACA,8BAAA,oCAIF,qCAEE,sBAAA,0BACA,6BAAA,0BACA,+BAAA,0BACA,gCAAA,0BACA,mCAAA,yBACA,eAAA,EAAA,OAAA,OAAA,oBAAA,CCtBmC,EAAE,EAAE,QAAQ,qBDyB/C,sBAAA,oCACA,6BAAA,sBACA,+BAAA,sBACA,gCAAA,uBACA,6BAAA,oBAGA,4BAAA,QACA,8BAAA,QACA,+BAAA,QACA,kCAAA,QAGA,gBAAA,2BACA,mBAAA,2BAGA,yBAAA,2BAGA,mBAAA,kBACA,mBAAA,mBACA,yBAAA,uCACA,0BAAA,QACA,4BAAA,oBACA,+BAAA,kBACA,0BAAA,kBACA,2BAAA,mBACA,0BAAA,mBACA,2BAAA,oBACA,wBAAA,kBACA,4BAAA,mBACA,4BAAA,mBACA,2BAAA,mBACA,4BAAA,mBACA,2BAAA,mBACA,mBAAA,mBAGA,0BAAA,mBACA,uBAAA,oBACA,6BAAA,kBACA,2BAAA,mBACA,yBAAA,mBAEA,2BAAA,QACA,6BAAA,QACA,wBAAA,QAGA,qBAAA,mBACA,wBAAA,QACA,uBAAA,QACA,uBAAA,QAGA,qBAAA,qCACA,kBAAA,mBACA,iBAAA,mBACA,iBAAA,kBACA,iBAAA,mBACA,iBAAA,oBACA,gBAAA,kBAGA,uBAAA,qCACA,8BAAA,uCACA,8BAAA,oCCrCJ,uFDiEE,0DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCChEJ,wFDsDE,2DAIE,2BAAA,QACA,sBAAA,2BACA,mCAAA,6BACA,6BAAA,2BACA,4BAAA,2BACA,sBAAA,2BACA,6BAAA,kCCrDJ,0FD2CE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC1CJ,+FDgCE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC/BJ,wFDqBE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCpBJ,0FDUE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCTJ,8FDDE,iEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCEJ,wFDZE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCaJ,wFDvBE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCwBJ,yFDlCE,4DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCmCJ,+FD7CE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC8CJ,wFDxDE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCyDJ,0FDnEE,6DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCCoEJ,yFD9EE,4DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCC+EJ,0FDzFE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC0FJ,+FDpGE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCqGJ,uFDzEE,yDAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCC4EJ,wFDlFE,0DAEE,+BAAA,QACA,qBAAA,2BACA,kCAAA,6BACA,qBAAA,2BACA,4BAAA,kCCqFJ,0FD3FE,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC8FJ,+FDpGE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCuGJ,wFD7GE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCgHJ,0FDtHE,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCyHJ,8FD/HE,gEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCkIJ,wFDxIE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC2IJ,wFDjJE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCoJJ,yFD1JE,2DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC6JJ,+FDnKE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCsKJ,wFD5KE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC+KJ,0FDrLE,4DAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCCwLJ,yFD9LE,2DAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCCiMJ,0FDvME,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC0MJ,+FDhNE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCEjNF,eACE,MAAA,iCAGF,eDmaF,eChaI,MAAA,8BAGF,eACE,MAAA,+BDmaJ,eChaE,eAEE,MAAA,gCAGF,eACE,MAAA,kCAGF,eD8ZF,eACA,eC5ZI,MAAA,+BAEF,eD8ZF,eC5ZI,MAAA,4BAOF,2BACI,OAAA,EACA,QAAA,EAAA,cACA,MAAA,wBACA,iBAAA,+BACA,cAAA,MACA,WAAA,KAKF,mBACE,MAAA,kBACA,iBAAA,uCACA,WAAA,MAAA,MACA,WAAA,iBAAA,MAGA,qBACE,MAAA,oCAGF,yBACE,iBAAA,8CAEA,2BACE,MAAA,oCAMR,qBACE,QAAA,EAIF,oBACE,WAAA,OAGF,uBAGE,cAAA,EAAA,YAAA,EAAA,SAAA,EAEA,+BACE,aAAA,MAOA,sDACE,iBAAA,gCAQF,gDACE,aAAA,eACA,YAAA,gBACA,cAAA,cACA,aAAA,eACA,iBAAA,gCAMN,qCAaE,SAAA,SACA,QAAA,MACA,WAAA,IACA,QAAA,KAAA,eAAA,KAAA,eACA,YAAA,IACA,UAAA,OACA,iBAAA,8BACA,uBAAA,MACA,wBAAA,MAlBA,yCACE,WAAA,EAEA,8CACE,uBAAA,EACA,wBAAA,EAgBJ,6CACE,SAAA,SACA,KAAA,cACA,MAAA,eACA,OAAA,eACA,iBAAA,2BACA,mBAAA,uRAAA,WAAA,uRACA,oBAAA,UAAA,YAAA,UACA,kBAAA,QAAA,UAAA,QACA,QAAA,GAIJ,8CACE,mBAAA,qoBAAA,WAAA,qoBAGF,+CACE,mBAAA,kRAAA,WAAA,kRAGF,2BACE,SAAA,SACA,WAAA,IACA,cAAA,IAEA,+BACE,WAAA,EACA,cAAA,EAGF,iCACE,QAAA,KAEA,8CACE,MAAA,KACA,OAAALine truncated
+2
View File
@@ -0,0 +1,2 @@
!function(){"use strict";var t;t=function(){for(var t=document.querySelectorAll("tbody"),e=0;e<t.length;e++)for(var n=t[e].children,o=function(){var t=n[r];if(t.hasAttribute("compact-container")){var e=n[r-1];t.classList.add("table-container"),e.classList.add("table-container-ctrl"),e.addEventListener("click",(function(n){e.hasAttribute("open")?(t.removeAttribute("open"),e.removeAttribute("open")):(t.setAttribute("open",""),e.setAttribute("open",""))}))}},r=1;r<n.length;r++)o()},window.document$?window.document$.subscribe(t):document.addEventListener("DOMContentLoaded",t)}();
//# sourceMappingURL=compact-tables-qqTQvuZ9.js.map
@@ -0,0 +1 @@
{"version":3,"file":"compact-tables-qqTQvuZ9.js","sources":["compact-tables.js"],"sourcesContent":["(() => {\n const main = () => {\n // Iterate through all tables looking for containers. This\n // works without assigning IDs to everything.\n const tbody_list = document.querySelectorAll(\"tbody\")\n for (let i = 0; i < tbody_list.length; i++) {\n const tbody = tbody_list[i]\n const row_list = tbody.children\n for (let j = 1; j < row_list.length; j++) {\n const cur_row = row_list[j]\n if (cur_row.hasAttribute(\"compact-container\")) {\n const control_row = row_list[j-1]\n cur_row.classList.add(\"table-container\")\n control_row.classList.add(\"table-container-ctrl\")\n control_row.addEventListener(\"click\", (event) => {\n if (control_row.hasAttribute(\"open\")) {\n cur_row.removeAttribute(\"open\")\n control_row.removeAttribute(\"open\")\n } else {\n cur_row.setAttribute(\"open\", \"\")\n control_row.setAttribute(\"open\", \"\")\n }\n })\n }\n }\n }\n }\n\n if (window.document$) {\n // Material specific hook\n window.document$.subscribe(main)\n } else {\n // Normal non-Material specific hook\n document.addEventListener(\"DOMContentLoaded\", main)\n }\n\n})()"],"names":["main","tbody_list","document","querySelectorAll","i","length","row_list","children","_loop","cur_row","j","hasAttribute","control_row","classList","add","addEventListener","event","removeAttribute","setAttribute","window","document$","subscribe"],"mappings":"yBAAA,IACUA,IAAO,WAIT,IADA,IAAMC,EAAaC,SAASC,iBAAiB,SACpCC,EAAI,EAAGA,EAAIH,EAAWI,OAAQD,IAGnC,IAFA,IACME,EADQL,EAAWG,GACFG,SAAQC,EAAAA,WAE3B,IAAMC,EAAUH,EAASI,GACzB,GAAID,EAAQE,aAAa,qBAAsB,CAC3C,IAAMC,EAAcN,EAASI,EAAE,GAC/BD,EAAQI,UAAUC,IAAI,mBACtBF,EAAYC,UAAUC,IAAI,wBAC1BF,EAAYG,iBAAiB,SAAS,SAACC,GAC/BJ,EAAYD,aAAa,SACzBF,EAAQQ,gBAAgB,QACxBL,EAAYK,gBAAgB,UAE5BR,EAAQS,aAAa,OAAQ,IAC7BN,EAAYM,aAAa,OAAQ,IAEzC,GACJ,GAfKR,EAAI,EAAGA,EAAIJ,EAASD,OAAQK,IAAGF,KAoB5CW,OAAOC,UAEPD,OAAOC,UAAUC,UAAUrB,GAG3BE,SAASa,iBAAiB,mBAAoBf"}
+177 -20
View File
@@ -1,5 +1,162 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
##
This file tracks configuration changes and deprecations. Additionally
changes to Moonraker that require user intervention will be tracked
here.
### December 24th 2023
- The `gpio` component no longer depends on `libgpiod`. Instead,
Moonraker now uses the [python-periphery](https://github.com/vsergeev/python-periphery)
library to manage GPIOs. This comes with several benefits:
- Distributions that do no ship with `libgpiod` will not fail during
installation if the `python3-libgpiod` package isn't present.
- Distributions with a Kernel Version of 5.5 or higher support bias
flags (ie: pull up or pull down). Previously this functionality
was tied to the `libgpiod` version. Specifically, Debian Buster
ships with a Kernel that supports bias, however the `libgpiod`
version does not.
- Version 2.0+ of `libgpiod` includes dramatic API changes that are
wholly incompatible with prior versions. Therefore maintaining
future versions would effectively require supporting two APIs.
- The `[button]` component now includes a `debounce_period` option.
This addition is the result of a behavior change in how gpio state
changes are debounced. Debouncing will now delay the event by the
time specified in the `debounce_period`. Additional state changes
received during this delay will not trigger a button event. The
`[button]` module retains the `minimum_event_time` option which will
ignore events shorter than the specified time.
### July 18th 2023
- The following changes have been made to `[update_manager <name>]`
extensions of the `git_repo` type:
- The `env` option has been deprecated. New configurations should
use the `virtualenv` option in its place.
- The `install_script` option has been deprecated. New configurations
should use the `system_dependencies` option to specify system package
dependencies.
- Configuration options for `[spoolman]` have been added
- Configuration options for `[sensor]` have been added
### February 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 precedence. 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.
### February 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 `[authorization]` 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
@@ -15,10 +172,10 @@ such as a configuration change or a reinstallation.
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
```
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
@@ -31,24 +188,24 @@ such as a configuration change or a reinstallation.
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
```
~/moonraker/scripts/install-moonraker.sh -r
- The power plugin configuration has changed. See the
[install guide](installation.md#power-control-plugin) for
[the configuration documentation](./configuration.md#power) 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
to unexport any currently used pins. For example, the following command
may be used to unexport pin 19:
```
echo 19 > /sys/class/gpio/unexport
```
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
```
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.
-1377
View File
File diff suppressed because it is too large. Load diff
+144
View File
@@ -0,0 +1,144 @@
site_name: Moonraker
site_url: https://moonraker.readthedocs.io
repo_url: https://github.com/Arksine/moonraker
edit_uri: blob/master/docs/
nav:
- Installation: installation.md
- Configuration : configuration.md
- Developer Documentation:
- External API:
- Introduction: external_api/introduction.md
- Server Administration: external_api/server.md
- Printer Administration: external_api/printer.md
- System Administration: external_api/machine.md
- File Management: external_api/file_manager.md
- Authorization and Authentication: external_api/authorization.md
- Database Management: external_api/database.md
- Job Queue Management: external_api/job_queue.md
- Job History Management: external_api/history.md
- Announcements: external_api/announcements.md
- Webcam Management: external_api/webcams.md
- Update Management: external_api/update_manager.md
- Switches, Sensors, and Devices: external_api/devices.md
- Third Party Integrations: external_api/integrations.md
- Extensions: external_api/extensions.md
- JSON-RPC Notifications: external_api/jsonrpc_notifications.md
- Printer Objects: printer_objects.md
- Components: components.md
- Contribution Guidelines: contributing.md
- Changelog: changelog.md
theme:
name: material
palette:
- scheme: default
primary: blue grey
accent: light blue
toggle:
icon: material/weather-sunny
name: Switch to Dark Mode
- scheme: slate
primary: black
accent: light blue
toggle:
icon: material/weather-night
name: Switch to Light Mode
font:
text: Roboto
code: Roboto Mono
features:
- navigation.top
- navigation.instant
- navigation.indexes
- navigation.expand
- toc.follow
- content.tabs.link
- search.share
- search.highlight
- search.suggest
- content.code.copy
- content.code.annotations
plugins:
- search
markdown_extensions:
- abbr
- admonition
- attr_list
- def_list
- footnotes
- md_in_html
- toc:
permalink: true
- pymdownx.arithmatex:
generic: true
- pymdownx.betterem:
smart_enable: all
- pymdownx.caret
- pymdownx.details
- pymdownx.emoji:
emoji_index: !!python/name:material.extensions.emoji.twemoji
emoji_generator: !!python/name:material.extensions.emoji.to_svg
- pymdownx.highlight
- pymdownx.inlinehilite
- pymdownx.keys
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.tilde
- pymdownx.saneheaders
- pymdownx.blocks.admonition
- pymdownx.blocks.details:
types:
- name: details-new
class: new
- name: details-settings
class: settings
- name: details-note
class: note
- name: details-abstract
class: abstract
- name: details-info
class: info
- name: details-tip
class: tip
- name: details-success
class: success
- name: details-question
class: question
- name: details-warning
class: warning
- name: details-failure
class: failure
- name: details-danger
class: danger
- name: details-bug
class: bug
- name: details-example
class: example
- name: details-quote
class: quote
- name: api-example-response
class: example
title: "Response Example"
- name: api-response-spec
class: info
title: "Response Specification"
- name: api-parameters
class: info
title: "Parameters"
- name: api-notification-spec
class: info
title: "Notification Parameter Specification"
- tables
- compact_tables:
auto_insert_break: false
- collapse_code:
expand_text: ''
collapse_text: ''
extra_css:
- src/css/extra-950ac449d4.css
extra_javascript:
- src/js/compact-tables-qqTQvuZ9.js
+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()
-364
View File
@@ -1,364 +0,0 @@
# Klipper Web Server Rest API
#
# 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 mimetypes
import logging
import tornado
from inspect import isclass
from tornado.escape import url_unescape
from tornado.routing import Rule, PathMatches, AnyMatches
from utils import ServerError
from websockets import WebRequest, WebsocketManager, WebSocket
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
from authorization import Authorization
# These endpoints are reserved for klippy/server communication only and are
# not exposed via http or the websocket
RESERVED_ENDPOINTS = [
"list_endpoints", "gcode/subscribe_output",
"register_remote_method"
]
EXCLUDED_ARGS = ["_", "token", "connection_id"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
# Status objects require special parsing
def _status_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
val = request_handler.get_argument(key)
if not val:
args[key] = None
else:
args[key] = val.split(',')
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
# Built-in Query String Parser
def _default_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
args[key] = request_handler.get_argument(key)
return args
class MutableRouter(tornado.web.ReversibleRuleRouter):
def __init__(self, application):
self.application = application
self.pattern_to_rule = {}
super(MutableRouter, self).__init__(None)
def get_target_delegate(self, target, request, **target_params):
if isclass(target) and issubclass(target, tornado.web.RequestHandler):
return self.application.get_handler_delegate(
request, target, **target_params)
return super(MutableRouter, self).get_target_delegate(
target, request, **target_params)
def has_rule(self, pattern):
return pattern in self.pattern_to_rule
def add_handler(self, pattern, target, target_params):
if pattern in self.pattern_to_rule:
self.remove_handler(pattern)
new_rule = Rule(PathMatches(pattern), target, target_params)
self.pattern_to_rule[pattern] = new_rule
self.rules.append(new_rule)
def remove_handler(self, pattern):
rule = self.pattern_to_rule.pop(pattern, None)
if rule is not None:
try:
self.rules.remove(rule)
except Exception:
logging.exception(f"Unable to remove rule: {pattern}")
class APIDefinition:
def __init__(self, endpoint, http_uri, ws_methods,
request_methods, parser):
self.endpoint = endpoint
self.uri = http_uri
self.ws_methods = ws_methods
if not isinstance(request_methods, list):
request_methods = [request_methods]
self.request_methods = request_methods
self.parser = parser
class MoonrakerApp:
def __init__(self, config):
self.server = config.get_server()
self.tornado_server = None
self.api_cache = {}
self.registered_base_handlers = []
self.max_upload_size = config.getint('max_upload_size', 200)
self.max_upload_size *= 1024 * 1024
# Set Up Websocket and Authorization Managers
self.wsm = WebsocketManager(self.server)
self.auth = Authorization(config['authorization'])
mimetypes.add_type('text/plain', '.log')
mimetypes.add_type('text/plain', '.gcode')
mimetypes.add_type('text/plain', '.cfg')
debug = config.getboolean('enable_debug_logging', True)
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
app_handlers = [
(AnyMatches(), self.mutable_router),
(r"/websocket", WebSocket),
(r"/api/version", EmulateOctoprintHandler)]
self.app = tornado.web.Application(
app_handlers,
serve_traceback=debug,
websocket_ping_interval=10,
websocket_ping_timeout=30,
parent=self)
self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers
logfile = config['system_args'].get('logfile')
if logfile:
self.register_static_file_handler("moonraker.log", logfile)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
self.auth.register_handlers(self)
def listen(self, host, port):
self.tornado_server = self.app.listen(
port, address=host, max_body_size=self.max_upload_size,
xheaders=True)
def get_server(self):
return self.server
def get_auth(self):
return self.auth
def get_websocket_manager(self):
return self.wsm
async def close(self):
if self.tornado_server is not None:
self.tornado_server.stop()
await self.tornado_server.close_all_connections()
await self.wsm.close()
self.auth.close()
def register_remote_handler(self, endpoint):
if endpoint in RESERVED_ENDPOINTS:
return
api_def = self._create_api_definition(endpoint)
if api_def.uri in self.registered_base_handlers:
# reserved handler or already registered
return
logging.info(
f"Registering remote endpoint - "
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
f"Websocket: {', '.join(api_def.ws_methods)}")
self.wsm.register_remote_handler(api_def)
params = {}
params['arg_parser'] = api_def.parser
params['remote_callback'] = api_def.endpoint
self.mutable_router.add_handler(
api_def.uri, RemoteRequestHandler, params)
self.registered_base_handlers.append(api_def.uri)
def register_local_handler(self, uri, request_methods,
callback, protocol=["http", "websocket"]):
if uri in self.registered_base_handlers:
return
api_def = self._create_api_definition(
uri, request_methods, is_remote=False)
msg = "Registering local endpoint"
if "http" in protocol:
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
params = {}
params['methods'] = request_methods
params['arg_parser'] = api_def.parser
params['callback'] = callback
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
self.registered_base_handlers.append(uri)
if "websocket" in protocol:
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
self.wsm.register_local_handler(api_def, callback)
logging.info(msg)
def register_static_file_handler(self, pattern, file_path):
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path):
pattern += '()'
elif os.path.isdir(file_path):
if pattern[-1] != "/":
pattern += "/"
pattern += "(.*)"
else:
logging.info(f"Invalid file path: {file_path}")
return
logging.debug(f"Registering static file: ({pattern}) {file_path}")
params = {'path': file_path}
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
def register_upload_handler(self, pattern):
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
def remove_handler(self, endpoint):
api_def = self.api_cache.get(endpoint)
if api_def is not None:
self.wsm.remove_handler(api_def.uri)
self.mutable_router.remove_handler(api_def.ws_method)
def _create_api_definition(self, endpoint, request_methods=[],
is_remote=True):
if endpoint in self.api_cache:
return self.api_cache[endpoint]
if endpoint[0] == '/':
uri = endpoint
elif is_remote:
uri = "/printer/" + endpoint
else:
uri = "/server/" + endpoint
ws_methods = []
if is_remote:
# Remote requests accept both GET and POST requests. These
# requests execute the same callback, thus they resolve to
# only a single websocket method.
ws_methods.append(uri[1:].replace('/', '.'))
request_methods = ['GET', 'POST']
else:
name_parts = uri[1:].split('/')
if len(request_methods) > 1:
for req_mthd in request_methods:
func_name = req_mthd.lower() + "_" + name_parts[-1]
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
else:
ws_methods.append(".".join(name_parts))
if not is_remote and len(request_methods) != len(ws_methods):
raise self.server.error(
"Invalid API definition. Number of websocket methods must "
"match the number of request methods")
if endpoint.startswith("objects/"):
parser = _status_parser
else:
parser = _default_parser
api_def = APIDefinition(endpoint, uri, ws_methods,
request_methods, parser)
self.api_cache[endpoint] = api_def
return api_def
# ***** Dynamic Handlers*****
class RemoteRequestHandler(AuthorizedRequestHandler):
def initialize(self, remote_callback, arg_parser):
super(RemoteRequestHandler, self).initialize()
self.remote_callback = remote_callback
self.query_parser = arg_parser
async def get(self):
await self._process_http_request()
async def post(self):
await self._process_http_request()
async def _process_http_request(self):
conn = self.get_associated_websocket()
args = self.query_parser(self)
try:
result = await self.server.make_request(
WebRequest(self.remote_callback, args, conn=conn))
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
self.finish({'result': result})
class LocalRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, arg_parser):
super(LocalRequestHandler, self).initialize()
self.callback = callback
self.methods = methods
self.query_parser = arg_parser
async def get(self):
if 'GET' in self.methods:
await self._process_http_request('GET')
else:
raise tornado.web.HTTPError(405)
async def post(self):
if 'POST' in self.methods:
await self._process_http_request('POST')
else:
raise tornado.web.HTTPError(405)
async def delete(self):
if 'DELETE' in self.methods:
await self._process_http_request('DELETE')
else:
raise tornado.web.HTTPError(405)
async def _process_http_request(self, method):
conn = self.get_associated_websocket()
args = self.query_parser(self)
try:
result = await self.callback(
WebRequest(self.request.path, args, method, conn=conn))
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
self.finish({'result': result})
class FileRequestHandler(AuthorizedFileHandler):
def set_extra_headers(self, path):
# The call below shold never return an empty string,
# as the path should have already been validated to be
# a file
basename = os.path.basename(self.absolute_path)
self.set_header(
"Content-Disposition", f"attachment; filename={basename}")
async def delete(self, path):
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path, plus=False)
file_manager = self.server.lookup_plugin('file_manager')
try:
filename = await file_manager.delete_file(path)
except self.server.error as e:
if e.status_code == 403:
raise tornado.web.HTTPError(
403, "File is loaded, DELETE not permitted")
else:
raise tornado.web.HTTPError(e.status_code, str(e))
self.finish({'result': filename})
class FileUploadHandler(AuthorizedRequestHandler):
async def post(self):
file_manager = self.server.lookup_plugin('file_manager')
try:
result = await file_manager.process_file_upload(self.request)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e))
self.finish(result)
class EmulateOctoprintHandler(AuthorizedRequestHandler):
def get(self):
self.finish({
'server': "1.1.1",
'api': "0.1",
'text': "OctoPrint Upload Emulator"})
+1
View File
@@ -0,0 +1 @@
# Assets Package Definition
+10
View File
@@ -0,0 +1,10 @@
klipper_mcu
webcamd
MoonCord
KlipperScreen
moonraker-telegram-bot
moonraker-obico
sonar
crowsnest
octoeverywhere
ratos-configurator
+502
View File
@@ -0,0 +1,502 @@
<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. If the
front end is hosted on a default port (80 for http, 443 for https),
you may remove the port from the address.
</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>
-284
View File
@@ -1,284 +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 re
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
from utils import ServerError
TOKEN_TIMEOUT = 5
CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
class Authorization:
def __init__(self, config):
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
self.api_key_file = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = config.getboolean('enabled', True)
self.trusted_connections = {}
self.access_tokens = {}
# Get allowed cors domains
cors_cfg = config.get('cors_domains', "").strip()
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
for d in cors_cfg.split('\n')if d.strip()]
# Get Trusted Clients
self.trusted_ips = []
self.trusted_ranges = []
trusted_clients = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
if c.strip()]
for ip in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
except ValueError:
tc = None
if tc is None:
# Check ip network
try:
tc = ipaddress.ip_network(ip)
except ValueError:
raise ServerError(
f"Invalid option in trusted_clients: {ip}")
self.trusted_ranges.append(tc)
else:
self.trusted_ips.append(tc)
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
app.register_local_handler(
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, web_request):
return self.get_access_token()
def _read_api_key(self):
if os.path.exists(self.api_key_file):
with open(self.api_key_file, 'r') as f:
api_key = f.read()
return api_key
# API Key file doesn't exist. Generate
# a new api key and create the file.
logging.info(
f"No API Key file found, creating new one at:"
f"\n{self.api_key_file}")
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_file, 'w') as f:
f.write(api_key)
return api_key
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(
f"Trusted Connection Expired, IP: {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(
f"Trusted Connection Detected, IP: {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(
f"Unable to Create IP Address {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 check_cors(self, origin, request=None):
if origin is None:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self, origin, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self):
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
conn = self.wsm.get_websocket(conn_id)
return conn
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
+1299
View File
File diff suppressed because it is too large. Load diff
@@ -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>
#
+546
View File
@@ -0,0 +1,546 @@
# Printer GCode Analysis using Klipper Estimator
#
# Copyright (C) 2025 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import sys
import os
import platform
import pathlib
import stat
import re
import logging
import asyncio
import shlex
from ..common import RequestType
from ..utils import json_wrapper as jsonw
from typing import (
TYPE_CHECKING,
Union,
Optional,
Dict,
Any,
Tuple
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .update_manager.update_manager import UpdateManager
from .application import MoonrakerApp
from .klippy_connection import KlippyConnection
from .authorization import Authorization
from .file_manager.file_manager import FileManager
from .machine import Machine
from .shell_command import ShellCommandFactory
from .http_client import HttpClient
StrOrPath = Union[str, pathlib.Path]
ESTIMATOR_URL = (
"https://github.com/Annex-Engineering/klipper_estimator/"
"releases/latest/download/{asset}"
)
UPDATE_CONFIG = {
"type": "executable",
"channel": "stable",
"repo": "Annex-Engineering/klipper_estimator",
"is_system_service": "False",
"path": ""
}
RELEASE_INFO = {
"project_name": "klipper_estimator",
"project_owner": "Annex-Engineering",
"version": "",
"asset_name": ""
}
IDENT_REGEX = r"^; Processed by klipper_estimator (?P<version>v?\d+(?:\.\d+)*)"
def _check_processed(gc_path: pathlib.Path) -> str | None:
size = gc_path.stat().st_size
# Read the last 64K
start = max(0, size - (64 * 1024))
with gc_path.open("rb") as f:
if start:
f.seek(start)
data = f.read().decode(errors="ignore")
# If Klipper Estimator is processed multiple times it will
# add a new identifier for each one.
versions = re.findall(IDENT_REGEX, data, re.MULTILINE)
if not versions:
return None
return versions[-1]
class GcodeAnalysis:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.cmd_lock = asyncio.Lock()
self.file_manger: FileManager = self.server.lookup_component("file_manager")
data_path = self.server.get_app_args()["data_path"]
tool_folder = pathlib.Path(data_path).joinpath("tools/klipper_estimator")
if not tool_folder.exists():
tool_folder.mkdir(parents=True)
self.estimator_timeout = config.getint("estimator_timeout", 600)
self.auto_analyze = config.getboolean("enable_auto_analysis", False)
self.auto_dump_defcfg = config.getboolean("auto_dump_default_config", False)
self.default_config = tool_folder.joinpath("default_estimator_cfg.json")
self.estimator_config = self.default_config
est_config = config.get("estimator_config", None)
if est_config is not None:
est_path = self.file_manger.get_full_path("config", est_config.strip("/"))
if ".." in est_path.parts:
raise config.error(
"Value for option 'estimator_config' must not contain "
"a '..' segment"
)
if not est_path.exists():
raise config.error(
f"File '{est_config}' does not exist in 'config' root"
)
self.estimator_config = est_path
self.estimator_path: pathlib.Path | None = None
self.estimator_ready: bool = False
self.estimator_version: str = "?"
pltform_choices = ["rpi", "linux", "osx", "auto"]
pltform = config.getchoice("platform", pltform_choices, default_key="auto")
if pltform == "auto":
auto_pfrm = self._detect_platform()
if auto_pfrm is not None:
self.estimator_path = tool_folder.joinpath(
f"klipper_estimator_{auto_pfrm}"
)
else:
exec_name = f"klipper_estimator_{pltform}"
self.estimator_path = tool_folder.joinpath(exec_name)
enable_updates = config.getboolean("enable_estimator_updates", False)
self.updater_registered: bool = False
if enable_updates:
if self.estimator_path is None:
logging.info(
"Klipper estimator platform not detected, updates disabled"
)
elif not config.has_section("update_manager"):
logging.info("Update Manager not configured, updates disabled")
else:
try:
um: UpdateManager
um = self.server.load_component(config, "update_manager")
updater_cfg = UPDATE_CONFIG
updater_cfg["path"] = str(tool_folder)
um.register_updater("klipper_estimator", updater_cfg)
except self.server.error:
logging.exception("Klipper Estimator update registration failed")
else:
self.updater_registered = True
if not self.updater_registered:
# Add reserved path when updates are disabled
self.file_manger.add_reserved_path("analysis", tool_folder, False)
# Register Klipper Estimator's GCode Processor configuration
# with the metadata processor. Keep a reference to the config
# so it can be updated after the Klipper Estimator Executable is
# verified in component_init().
self.proc_config: Dict[str, Any] = {
"name": "klipper_estimator",
"command": [
str(self.estimator_path),
"--config_file",
str(self.estimator_config),
"post-process",
"{gcode_file_path}"
],
"timeout": self.estimator_timeout,
"version": self.estimator_version,
"ident": {
"regex": IDENT_REGEX,
"location": "footer"
},
"enabled": False
}
mdst = self.file_manger.get_metadata_storage()
mdst.register_gcode_processor("klipper_estimator", self.proc_config)
self.server.register_endpoint(
"/server/analysis/status", RequestType.GET,
self._handle_status_request
)
self.server.register_endpoint(
"/server/analysis/estimate", RequestType.POST,
self._handle_estimator_request
)
self.server.register_endpoint(
"/server/analysis/process", RequestType.POST,
self._handle_estimator_request
)
self.server.register_endpoint(
"/server/analysis/dump_config", RequestType.POST,
self._handle_dump_cfg_request
)
self.server.register_event_handler(
"server:klippy_ready", self._on_klippy_ready
)
@property
def estimator_version_tuple(self) -> Tuple[int, ...]:
if self.estimator_version in ["?", ""]:
return tuple()
ver_string = self.estimator_version
if ver_string[0] == "v":
ver_string = ver_string[1:]
return tuple([int(p) for p in ver_string.split(".")])
async def _on_klippy_ready(self) -> None:
if not self.estimator_ready:
return
if self.auto_dump_defcfg or not self.default_config.exists():
logging.info(
"Dumping default Klipper Estimator configuration to "
f"{self.default_config}"
)
eventloop = self.server.get_event_loop()
if (
self.auto_analyze and
self.default_config == self.estimator_config and
not self.default_config.exists()
):
async def _dump_and_update_proc_cfg() -> None:
await self._dump_estimator_config(self.default_config)
self._update_gcode_proc_config()
eventloop.create_task(_dump_and_update_proc_cfg())
else:
eventloop.create_task(self._dump_estimator_config(self.default_config))
async def component_init(self) -> None:
if self.estimator_path is not None:
if not self.estimator_path.exists():
# Download Klipper Estimator
await self._download_klipper_estimator(self.estimator_path)
if not self._check_estimator_perms(self.estimator_path):
self.server.add_warning(
"[analysis]: Moonraker lacks permission to execute "
"Klipper Estimator"
)
else:
await self._detect_estimator_version()
if self.estimator_version == "?":
logging.info("Failed to initialize Klipper Estimator")
else:
await self._check_release_info(self.estimator_path)
self.estimator_ready = True
logging.info(
f"Klipper Estimator Version {self.estimator_version} detected"
)
self._update_gcode_proc_config()
def _update_gcode_proc_config(self) -> None:
self.proc_config["version"] = self.estimator_version
enabled = False
if self.auto_analyze:
if not self.estimator_ready:
enabled = False
logging.info(
"Klipper Estimator executable failed validation, "
"auto analysis disabled."
)
elif not self.estimator_config.is_file():
enabled = False
logging.info(
"Klipper Estimator config file does not exist, "
"auto analysis disabled."
)
else:
logging.info("Klipper Estimator Auto Analysis Enabled")
enabled = True
self.proc_config["enabled"] = enabled
def _detect_platform(self) -> Optional[str]:
# Detect OS
if sys.platform.startswith("darwin"):
return "osx"
elif sys.platform.startswith("linux"):
# Get architecture
arch: str = platform.machine()
if not arch:
self.server.add_warning(
"[analysis]: Failed to detect CPU architecture. "
"Manual configuration of the 'platform' option is required.",
"analysis_estimator"
)
return None
if arch == "x86_64":
return "linux"
elif arch in ("armv7l", "aarch64"):
# TODO: Other platforms may work, not sure
return "rpi"
else:
self.server.add_warning(
f"[analysis]: Unsupported CPU architecture '{arch}'. "
"Manual configuration of the 'platform' option is required.",
"analysis_estimator"
)
return None
else:
self.server.add_warning(
f"[analysis]: Unsupported platform '{sys.platform}'. "
"Manual configuration of the 'platform' option is required.",
"analysis_estimator"
)
async def _download_klipper_estimator(self, estimator_path: pathlib.Path) -> None:
"""
Download Klipper Estimator, set executable permissions, and generate
the release_info.json file
"""
async with self.cmd_lock:
est_name = estimator_path.name
logging.info(f"Downloading latest {est_name}...")
url = ESTIMATOR_URL.format(asset=est_name)
http_client: HttpClient = self.server.lookup_component("http_client")
try:
await http_client.download_file(
url, "application/octet-stream", estimator_path
)
except asyncio.CancelledError:
raise
except Exception:
logging.exception("Failed to download Klipper estimator")
else:
logging.info("Klipper Estimator download complete.")
async def _detect_estimator_version(self) -> None:
cmd = f"{self.estimator_path} --version"
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
ret = await scmd.exec_cmd(cmd, timeout=10.)
ver_match = re.match(r"klipper_estimator (v?\d+(?:\.\d+)*)", ret)
if ver_match is None:
self.estimator_version = "?"
else:
self.estimator_version = ver_match.group(1)
def _check_estimator_perms(self, estimator_path: pathlib.Path) -> bool:
if not estimator_path.is_file():
return False
req_perms = stat.S_IXUSR | stat.S_IXGRP
kest_perms = stat.S_IMODE(estimator_path.stat().st_mode)
if req_perms & kest_perms != req_perms:
logging.info("Setting executable permissions for Klipper Estimator...")
try:
estimator_path.chmod(kest_perms | req_perms)
except OSError:
logging.exception(
"Failed to set Klipper Estimator Permissions"
)
return os.access(estimator_path, os.X_OK)
async def _check_release_info(self, estimator_path: pathlib.Path) -> None:
rinfo_file = estimator_path.parent.joinpath("release_info.json")
if rinfo_file.is_file():
return
logging.info("Creating release_info.json for Klipper Estimator...")
rinfo = dict(RELEASE_INFO)
rinfo["version"] = self.estimator_version
rinfo["asset_name"] = estimator_path.name
eventloop = self.server.get_event_loop()
await eventloop.run_in_thread(rinfo_file.write_bytes, jsonw.dumps(rinfo))
if self.updater_registered:
logging.info("Refreshing Klipper Estimator Updater Instance...")
um: UpdateManager = self.server.lookup_component("update_manager")
eventloop.create_task(um.refresh_updater("klipper_estimator", True))
def _get_moonraker_url(self) -> str:
machine: Machine = self.server.lookup_component("machine")
app: MoonrakerApp = self.server.lookup_component("application")
host_info = self.server.get_host_info()
host_addr: str = host_info["address"]
if host_addr.lower() in ("all", "0.0.0.0", "localhost", "127.0.0.1"):
address = "127.0.0.1"
elif host_addr.lower() == "::":
address = "::1"
else:
address = machine.public_ip
if not address:
address = f"{host_info['hostname']}.local"
elif ":" in address:
# ipv6 address
address = f"[{address}]"
port = host_info["port"]
return f"http://{address}:{port}{app.route_prefix}"
def _gen_estimator_cmd(
self,
gc_path: pathlib.Path,
est_cfg_path: pathlib.Path,
is_post_process: bool = False
) -> str:
if self.estimator_path is None or not self.estimator_ready:
raise self.server.error("Klipper Estimator not available")
if not est_cfg_path.exists():
raise self.server.error(
f"Klipper Estimator config {est_cfg_path.name} does not exist"
)
action = "post-process" if is_post_process else "estimate -f json"
cmd = str(self.estimator_path)
cmd = f"{cmd} --config_file {shlex.quote(str(est_cfg_path))}"
cmd = f"{cmd} {action} {shlex.quote(str(gc_path))}"
return cmd
def _gen_dump_cmd(self) -> str:
if self.estimator_path is None or not self.estimator_ready:
raise self.server.error("Klipper Estimator not available")
return f"{self.estimator_path} {self._gen_url_opts()} dump-config"
def _gen_url_opts(self) -> str:
url = self._get_moonraker_url()
opts = f"--config_moonraker_url {url}"
auth: Optional[Authorization]
auth = self.server.lookup_component("authorization", None)
api_key = auth.get_api_key() if auth is not None else None
if api_key is not None:
opts = f"{opts} --config_moonraker_api_key {api_key}"
return opts
async def _dump_estimator_config(self, dest: pathlib.Path) -> Dict[str, Any]:
async with self.cmd_lock:
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
eventloop = self.server.get_event_loop()
if not kconn.is_ready():
raise self.server.error(
"Klipper Estimator cannot dump configuration, Klippy not ready",
504
)
dump_cmd = self._gen_dump_cmd()
try:
ret = await scmd.exec_cmd(
dump_cmd, timeout=10., log_complete=False, log_stderr=True
)
await eventloop.run_in_thread(dest.write_text, ret)
except scmd.error:
raise self.server.error(
"Klipper Estimator dump-config failed", 500
) from None
return jsonw.loads(ret)
async def estimate_file(
self, gc_path: pathlib.Path, est_config: Optional[pathlib.Path] = None
) -> Dict[str, Any]:
async with self.cmd_lock:
if est_config is None:
# Fall back to estimator config specified in the [analysis] section.
est_config = self.estimator_config
if not est_config.is_file():
raise self.server.error(
f"Estimator config file '{est_config}' does not exist"
)
if not gc_path.is_file():
raise self.server.error(f"GCode File '{gc_path}' does not exist")
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
est_cmd = self._gen_estimator_cmd(gc_path, est_config)
ret = await scmd.exec_cmd(est_cmd, self.estimator_timeout)
data = jsonw.loads(ret)
return data["sequences"][0]
async def post_process_file(
self,
gc_path: pathlib.Path,
est_config: Optional[pathlib.Path] = None,
force: bool = False
) -> Dict[str, Any]:
async with self.cmd_lock:
if est_config is None:
# Fall back to estimator config specified in the [analysis] section.
est_config = self.estimator_config
if not est_config.is_file():
raise self.server.error(
f"Estimator config file '{est_config}' does not exist"
)
if not gc_path.is_file():
raise self.server.error(f"GCode File '{gc_path}' does not exist")
eventloop = self.server.get_event_loop()
proc_ver = await eventloop.run_in_thread(_check_processed, gc_path)
bypassed = processed = proc_ver is not None
if not processed or force:
scmd: ShellCommandFactory
scmd = self.server.lookup_component("shell_command")
pp_cmd = self._gen_estimator_cmd(gc_path, est_config, True)
await scmd.exec_cmd(pp_cmd, self.estimator_timeout)
proc_ver = self.estimator_version
bypassed = False
else:
logging.info(f"File {gc_path.name} already processed, aborting")
return {
"prev_processed": processed,
"version": proc_ver,
"bypassed": bypassed,
}
async def _handle_status_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
est_exec = "unknown"
if self.estimator_path is not None:
est_exec = self.estimator_path.name
is_default = self.estimator_config == self.default_config
return {
"estimator_executable": est_exec,
"estimator_ready": self.estimator_ready,
"estimator_version": self.estimator_version,
"estimator_config_exists": self.estimator_config.exists(),
"using_default_config": is_default
}
async def _handle_estimator_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
gcode_file = web_request.get_str("filename").strip("/")
estimator_config = web_request.get_str("estimator_config", None)
gc_path = self.file_manger.get_full_path("gcodes", gcode_file)
if not gc_path.is_file():
raise self.server.error(
f"GCode File '{gcode_file}' does not exit in gcodes path"
)
est_cfg_path = self.estimator_config
if estimator_config is not None:
estimator_config = estimator_config.strip("/")
est_cfg_path = self.file_manger.get_full_path("config", estimator_config)
if ".." in est_cfg_path.parts:
raise self.server.error(
"Invalid value for param 'estimator_config', '..' segments "
"are not allowed"
)
ep = web_request.get_endpoint().split("/")[-1]
if ep == "estimate":
ret = await self.estimate_file(gc_path, est_cfg_path)
elif ep == "process":
force = web_request.get_boolean("force", False)
ret = await self.post_process_file(gc_path, est_cfg_path, force)
else:
raise self.server.error(f"Unknown request {ep}", 404)
return ret
async def _handle_dump_cfg_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
dest = web_request.get_str("dest_config", None)
root: str | None = None
if dest is not None:
root = "config"
dest = dest.strip("/")
if ".." in pathlib.Path(dest).parts:
raise self.server.error(
"Parameter 'dest_config' may not contain '..' parts"
)
dest_config = self.file_manger.get_full_path("config", dest)
else:
dest = self.default_config.name
dest_config = self.default_config
result = await self._dump_estimator_config(dest_config)
return {
"dest_root": root,
"dest_config_path": dest,
"klipper_estimator_config": result
}
def load_component(config: ConfigHelper) -> GcodeAnalysis:
return GcodeAnalysis(config)
+556
View File
@@ -0,0 +1,556 @@
# 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 ..common import RequestType
from typing import (
TYPE_CHECKING,
Awaitable,
List,
Dict,
Any,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common 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", RequestType.GET,
self._list_announcements
)
self.server.register_endpoint(
"/server/announcements/dismiss", RequestType.POST,
self._handle_dismiss_request
)
self.server.register_endpoint(
"/server/announcements/update", RequestType.POST,
self._handle_update_request
)
self.server.register_endpoint(
"/server/announcements/feed", RequestType.POST | RequestType.DELETE,
self._handle_feed_request
)
self.server.register_endpoint(
"/server/announcements/feeds", RequestType.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 = web_request.get_list("subscriptions", 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]:
req_type = web_request.get_request_type()
name: str = web_request.get("name")
name = name.lower()
changed: bool = False
db: MoonrakerDatabase = self.server.lookup_component("database")
result = "skipped"
if req_type == RequestType.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 req_type == RequestType.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)
self.eventloop.create_task(self._notify_internal())
return entry
async def _notify_internal(self) -> None:
entries = await self.entry_mgr.list_entries()
self.server.send_event(
"announcements:entries_updated", {"entries": entries}
)
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 register_feed(self, name: str) -> None:
name = name.lower()
if name in self.subscriptions:
logging.info(f"Feed {name} already configured")
return
logging.info(f"Registering feed {name}")
self.configured_feeds.append(name)
self.subscriptions[name] = RssFeed(name, self.entry_mgr, self.dev_mode)
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:
data_path = pathlib.Path(self.server.get_app_arg("data_path"))
dev_folder = data_path.joinpath("development/announcements")
dev_folder.mkdir(parents=True, exist_ok=True)
self.dev_xml_path = dev_folder.joinpath(self.xml_file)
logging.info(
f"Announcement Feed {name}: Dev XML path set to {self.dev_xml_path}"
)
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)
File diff suppressed because it is too large. Load diff
+941
View File
@@ -0,0 +1,941 @@
# 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
from tornado.web import HTTPError
from libnacl.sign import Signer, Verifier
from ..utils import json_wrapper as jsonw
from ..common import RequestType, TransportType, SqlTableDefinition, UserInfo
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .websockets import WebsocketManager
from tornado.httputil import HTTPServerRequest
from .database import MoonrakerDatabase as DBComp
from .database import DBProviderWrapper
from .ldap import MoonrakerLDAP
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
OneshotToken = Tuple[IPAddr, Optional[UserInfo], 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
FQDN_CACHE_TIMEOUT = 84000
PRUNE_CHECK_TIME = 300.
USER_TABLE = "authorized_users"
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 UserSqlDefinition(SqlTableDefinition):
name = USER_TABLE
prototype = (
f"""
{USER_TABLE} (
username TEXT PRIMARY KEY NOT NULL,
password TEXT NOT NULL,
created_on REAL NOT NULL,
salt TEXT NOT NULL,
source TEXT NOT NULL,
jwt_secret TEXT,
jwk_id TEXT,
groups pyjson
)
"""
)
version = 1
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
if last_version == 0:
users: Dict[str, Dict[str, Any]]
users = db_provider.get_namespace("authorized_users")
api_user = users.pop(API_USER, {})
if not isinstance(api_user, dict):
api_user = {}
user_vals: List[Tuple[Any, ...]] = [
UserInfo(
username=API_USER,
password=api_user.get("api_key", uuid.uuid4().hex),
created_on=api_user.get("created_on", time.time())
).as_tuple()
]
for key, user in users.items():
if not isinstance(user, dict):
logging.info(
f"Auth migration, skipping invalid value: {key} {user}"
)
continue
user_vals.append(UserInfo(**user).as_tuple())
placeholders = ",".join("?" * len(user_vals[0]))
conn = db_provider.connection
with conn:
conn.executemany(
f"INSERT OR IGNORE INTO {USER_TABLE} VALUES({placeholders})",
user_vals
)
db_provider.wipe_local_namespace("authorized_users")
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] = {}
self.fqdn_cache: Dict[IPAddr, Dict[str, Any]] = {}
if self.default_source not in AUTH_SOURCES:
self.server.add_warning(
"[authorization]: option 'default_source' - Invalid "
f"value '{self.default_source}', falling back to "
"'moonraker'."
)
self.default_source = "moonraker"
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')
self.user_table = database.register_table(UserSqlDefinition())
self.users: Dict[str, UserInfo] = {}
self.api_key = uuid.uuid4().hex
hi = self.server.get_host_info()
self.issuer = f"http://{hi['hostname']}:{hi['port']}"
self.public_jwks: Dict[str, Dict[str, Any]] = {}
self.trusted_users: Dict[IPAddr, Dict[str, Any]] = {}
self.oneshot_tokens: Dict[str, OneshotToken] = {}
# 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:
self.server.add_warning(
f"[authorization]: Unsafe domain '{domain}' in option "
f"'cors_domains'. Wildcards are not permitted in the"
" top level domain."
)
continue
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.server.register_endpoint(
"/access/login", RequestType.POST, self._handle_login,
transports=TransportType.HTTP | TransportType.WEBSOCKET,
auth_required=False
)
self.server.register_endpoint(
"/access/logout", RequestType.POST, self._handle_logout,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/refresh_jwt", RequestType.POST, self._handle_refresh_jwt,
transports=TransportType.HTTP | TransportType.WEBSOCKET,
auth_required=False
)
self.server.register_endpoint(
"/access/user", RequestType.all(), self._handle_user_request,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/users/list", RequestType.GET, self._handle_list_request,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/user/password", RequestType.POST, self._handle_password_reset,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/api_key", RequestType.GET | RequestType.POST,
self._handle_apikey_request,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/oneshot_token", RequestType.GET, self._handle_oneshot_request,
transports=TransportType.HTTP | TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/access/info", RequestType.GET, self._handle_info_request,
transports=TransportType.HTTP | TransportType.WEBSOCKET,
auth_required=False
)
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"
)
async def component_init(self) -> None:
# Populate users from database
cursor = await self.user_table.execute(f"SELECT * FROM {USER_TABLE}")
self.users = {row[0]: UserInfo(**dict(row)) for row in await cursor.fetchall()}
need_sync = self._initialize_users()
if need_sync:
await self._sync_user_table()
self.prune_timer.start(delay=PRUNE_CHECK_TIME)
async def _sync_user(self, username: str) -> None:
user = self.users[username]
vals = user.as_tuple()
placeholders = ",".join("?" * len(vals))
async with self.user_table as tx:
await tx.execute(
f"REPLACE INTO {USER_TABLE} VALUES({placeholders})", vals
)
async def _sync_user_table(self) -> None:
async with self.user_table as tx:
await tx.execute(f"DELETE FROM {USER_TABLE}")
user_vals: List[Tuple[Any, ...]]
user_vals = [user.as_tuple() for user in self.users.values()]
if not user_vals:
return
placeholders = ",".join("?" * len(user_vals[0]))
await tx.executemany(
f"INSERT INTO {USER_TABLE} VALUES({placeholders})", user_vals
)
def _initialize_users(self) -> bool:
need_sync = False
api_user: Optional[UserInfo] = self.users.get(API_USER, None)
if api_user is None:
need_sync = True
self.users[API_USER] = UserInfo(username=API_USER, password=self.api_key)
else:
self.api_key = api_user.password
for username, user_info in list(self.users.items()):
if username == API_USER:
continue
# generate jwks for valid users
if user_info.jwt_secret is not None:
try:
priv_key = self._load_private_key(user_info.jwt_secret)
jwk_id = user_info.jwk_id
assert jwk_id is not None
except (self.server.error, KeyError, AssertionError):
logging.info("Invalid jwk found for user, removing")
user_info.jwt_secret = None
user_info.jwk_id = None
self.users[username] = user_info
need_sync = True
continue
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
return need_sync
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
if web_request.get_request_type() == RequestType.POST:
self.api_key = uuid.uuid4().hex
self.users[API_USER].password = self.api_key
await 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}")
jwk_id: Optional[str] = self.users[username].jwk_id
self.users[username].jwt_secret = None
self.users[username].jwk_id = None
if jwk_id is not None:
self.public_jwks.pop(jwk_id, None)
await self._sync_user(username)
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")
login_req = self.force_logins and len(self.users) > 1
request_trusted: Optional[bool] = None
user = web_request.get_current_user()
req_ip = web_request.ip_addr
if user is not None and user.username == TRUSTED_USER:
request_trusted = True
elif req_ip is not None:
request_trusted = await self._check_authorized_ip(req_ip)
return {
"default_source": self.default_source,
"available_sources": sources,
"login_required": login_req,
"trusted": request_trusted
}
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 user_info.jwt_secret is None or user_info.jwk_id is None:
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.source,
'action': 'user_jwt_refresh'
}
async def _handle_user_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
req_type = web_request.get_request_type()
if req_type == RequestType.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.source,
"created_on": user.created_on
}
elif req_type == RequestType.POST:
# Create User
return await self._login_jwt_user(web_request, new_user_request=True)
elif req_type == RequestType.DELETE:
# Delete User
return await 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.source,
'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.source == "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
await self._sync_user(username)
return {
'username': username,
'action': "user_password_reset"
}
async def _login_jwt_user(
self, web_request: WebRequest, new_user_request: 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}")
if username in RESERVED_USERS:
raise self.server.error(f"Invalid Request for user {username}")
user_info: UserInfo
is_local_user = source == "moonraker"
need_create = new_user_request
if source == "ldap":
if new_user_request:
raise self.server.error("Invalid Request to create new LDAP User")
if self.ldap is None:
raise self.server.error(
"LDAP authentication not available", 401
)
await self.ldap.authenticate_ldap_user(username, password)
need_create = username not in self.users
if need_create:
if username in self.users:
raise self.server.error(f"User {username} already exists")
if is_local_user:
# only generate a hashed password when local authentication
# is required
salt = secrets.token_bytes(32)
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
else:
salt = b""
hashed_pass = ""
user_info = UserInfo(
username=username,
password=hashed_pass,
salt=salt.hex(),
source=source,
)
self.users[username] = user_info
await self._sync_user(username)
else:
if username not in self.users:
raise self.server.error(f"Unregistered User: {username}")
user_info = self.users[username]
auth_src = user_info.source
if auth_src != source:
raise self.server.error(
f"Moonraker cannot authenticate user '{username}', must "
f"specify source '{auth_src}'", 401
)
if is_local_user:
# Only local users require password authentication
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")
jwt_secret_hex: Optional[str] = user_info.jwt_secret
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() # type: ignore
user_info.jwk_id = jwk_id
self.users[username] = user_info
await 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)
if user_info.jwk_id is None:
user_info.jwk_id = base64url_encode(secrets.token_bytes()).decode()
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 new_user_request:
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.source,
'refresh_token': refresh_token,
'action': "user_created" if new_user_request else "user_logged_in"
}
async 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.username
if 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[UserInfo] = self.users.get(username)
if user_info is None:
raise self.server.error(f"No registered user: {username}")
if user_info.jwk_id is not None:
self.public_jwks.pop(user_info.jwk_id, None)
del self.users[username]
async with self.user_table as tx:
await tx.execute(
f"DELETE FROM {USER_TABLE} WHERE username = ?", (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(jsonw.dumps(header))
jwt_payload = base64url_encode(jsonw.dumps(payload))
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", check_exp: bool = True
) -> UserInfo:
message, sig = token.rsplit('.', maxsplit=1)
enc_header, enc_payload = message.split('.')
header: Dict[str, Any] = jsonw.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: Optional[str] = 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] = jsonw.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 check_exp and payload['exp'] < int(time.time()):
raise self.server.error("JWT Expired", 401)
# get user
user_info: Optional[UserInfo] = 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) -> UserInfo:
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) -> UserInfo:
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}")
for ip, fqdn_info in list(self.fqdn_cache.items()):
exp_time = fqdn_info["expires_at"]
if cur_time >= exp_time:
domain: str = fqdn_info["domain"]
self.fqdn_cache.pop(ip, None)
logging.info(f"Cached FQDN Expired, IP: {ip}, domain: {domain}")
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[UserInfo]) -> 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, required: bool = True
) -> Optional[UserInfo]:
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(errors="ignore")
elif auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
else:
return None
if auth_token:
try:
return self.decode_jwt(auth_token, check_exp=required)
except Exception:
logging.exception(f"JWT Decode Error {auth_token}")
raise HTTPError(401, "JWT Decode Error")
return None
async 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
if self.trusted_domains:
if ip in self.fqdn_cache:
fqdn: str = self.fqdn_cache[ip]["domain"]
else:
eventloop = self.server.get_event_loop()
try:
fut = eventloop.run_in_thread(socket.getfqdn, str(ip))
fqdn = await asyncio.wait_for(fut, 5.0)
except asyncio.TimeoutError:
logging.info("Call to socket.getfqdn() timed out")
return False
else:
fqdn = fqdn.lower()
self.fqdn_cache[ip] = {
"expires_at": time.time() + FQDN_CACHE_TIMEOUT,
"domain": fqdn
}
return fqdn in self.trusted_domains
return False
async def _check_trusted_connection(
self, ip: Optional[IPAddr]
) -> Optional[UserInfo]:
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]["user"]
elif await self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_users[ip] = {
"user": UserInfo(TRUSTED_USER, "", curtime),
"expires_at": exp_time
}
return self.trusted_users[ip]["user"]
return None
def _check_oneshot_token(
self, token: str, cur_ip: Optional[IPAddr]
) -> Optional[UserInfo]:
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
async def authenticate_request(
self, request: HTTPServerRequest, auth_required: bool = True
) -> Optional[UserInfo]:
if request.method == "OPTIONS":
return None
# Check JSON Web Token
jwt_user = self._check_json_web_token(request, auth_required)
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
# then trusted user authentication is disabled
if self.force_logins and len(self.users) > 1:
if not auth_required:
return None
raise HTTPError(401, "Unauthorized, Force Logins Enabled")
# Check if IP is trusted. If this endpoint doesn't require authentication
# then it is acceptable to return None
trusted_user = await self._check_trusted_connection(ip)
if trusted_user is not None:
return trusted_user
if not auth_required:
return None
raise HTTPError(401, "Unauthorized")
async def check_cors(self, origin: Optional[str]) -> 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}")
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 await self._check_authorized_ip(ipaddr):
logging.debug(f"Cors request matched trusted IP: {ip}")
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def cors_enabled(self) -> bool:
return self.cors_domains is not None
def get_api_key(self) -> Optional[str]:
if not self.enable_api_key:
return None
return self.api_key
def close(self) -> None:
self.prune_timer.stop()
def load_component(config: ConfigHelper) -> Authorization:
return Authorization(config)
+125
View File
@@ -0,0 +1,125 @@
# 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 .application 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") # noqa: F841
try:
btn = GpioButton(cfg)
except Exception as e:
msg = f"Failed to load button [{cfg.get_name()}]\n{e}"
self.server.add_warning(msg, exc_info=e)
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()
self.gpio_event = config.getgpioevent("pin", self._on_gpio_event)
self.min_event_time = config.getfloat("minimum_event_time", 0, minval=0.0)
debounce_period = config.getfloat("debounce_period", .05, minval=0.01)
self.gpio_event.setup_debounce(debounce_period, 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:
if elapsed_time < self.min_event_time:
return
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)
+174
View File
@@ -0,0 +1,174 @@
# Klipper data logging and storage storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from collections import deque
from ..common import RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Deque,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .klippy_connection import KlippyConnection
from .klippy_apis import KlippyAPI as APIComp
GCQueue = Deque[Dict[str, Any]]
TempStore = Dict[str, Dict[str, Deque[Optional[float]]]]
TEMP_UPDATE_TIME = 1.
def _round_null(val: Optional[float], ndigits: int) -> Optional[float]:
if val is None:
return val
return round(val, ndigits)
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
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
self.subscription_cache = kconn.get_subscription_cache()
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
self.temperature_store: TempStore = {}
self.temp_monitors: List[str] = []
eventloop = self.server.get_event_loop()
self.temp_update_timer = eventloop.register_timer(
self._update_temperature_store)
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", RequestType.GET,
self._handle_temp_store_request
)
self.server.register_endpoint(
"/server/gcode_store", RequestType.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
heaters: Dict[str, List[str]] = result.get("heaters", {})
sensors = heaters.get("available_sensors", [])
self.temp_monitors = heaters.get("available_monitors", [])
sensors.extend(self.temp_monitors)
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 = {}
valid_fields = ("temperature", "target", "power", "speed")
for sensor in sensors:
reported_fields = [
f for f in list(status.get(sensor, {}).keys()) if f in valid_fields
]
if not reported_fields:
logging.info(f"No valid fields reported for sensor: {sensor}")
self.temperature_store.pop(sensor, None)
continue
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
for field in list(new_store[sensor].keys()):
if field not in reported_fields:
new_store[sensor].pop(field, None)
else:
initial_val: Optional[float]
initial_val = _round_null(status[sensor][field], 2)
new_store[sensor][field].append(initial_val)
else:
new_store[sensor] = {}
for field in reported_fields:
if field not in new_store[sensor]:
initial_val = _round_null(status[sensor][field], 2)
new_store[sensor][field] = deque(
[initial_val], maxlen=self.temp_store_size
)
self.temperature_store = new_store
self.temp_update_timer.start(delay=1.)
else:
logging.info("No sensors found")
self.temperature_store = {}
self.temp_monitors = []
self.temp_update_timer.stop()
def _update_temperature_store(self, eventtime: float) -> float:
for sensor_name, sensor in self.temperature_store.items():
sdata: Dict[str, Any] = self.subscription_cache.get(sensor_name, {})
for field, store in sensor.items():
store.append(_round_null(sdata.get(field, store[-1]), 2))
return eventtime + TEMP_UPDATE_TIME
async def _handle_temp_store_request(
self, web_request: WebRequest
) -> Dict[str, Dict[str, List[Optional[float]]]]:
include_monitors = web_request.get_boolean("include_monitors", False)
store = {}
for name, sensor in self.temperature_store.items():
if not include_monitors and name in self.temp_monitors:
continue
store[name] = {f"{k}s": 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()
if script.strip():
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)
File diff suppressed because it is too large. Load diff
+150
View File
@@ -0,0 +1,150 @@
# 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 asyncio
import pathlib
import logging
import dbus_fast
from dbus_fast.aio import MessageBus, ProxyInterface
from dbus_fast.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_fast.Variant
DbusError = dbus_fast.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_fast.Variant("u", os.getpid()),
"start-time": dbus_fast.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 asyncio.CancelledError:
raise
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 asyncio.CancelledError:
raise
except Exception as e:
if self.server.is_debug_enabled():
logging.exception("Failed to get PolKit interface")
else:
logging.info(f"Failed to get PolKit interface: {e}")
self.polkit = None
async def check_permission(self,
action: str,
err_msg: str = ""
) -> bool:
if self.polkit is None:
self.server.add_warning(
"Unable to find DBus PolKit Interface, this suggests PolKit "
"is not installed on your OS.",
"dbus_polkit"
)
return False
try:
ret = await self.polkit.call_check_authorization( # type: ignore
self.polkit_subject, action, {}, 0, "")
except asyncio.CancelledError:
raise
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 available")
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)
+257
View File
@@ -0,0 +1,257 @@
# 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
from ..common import BaseRemoteConnection, RequestType, TransportType
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 ..common 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, BaseRemoteConnection] = {}
self.agent_methods: Dict[int, List[str]] = {}
self.uds_server: Optional[asyncio.AbstractServer] = None
self.server.register_endpoint(
"/connection/register_remote_method", RequestType.POST,
self._register_agent_method,
transports=TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/connection/send_event", RequestType.POST, self._handle_agent_event,
transports=TransportType.WEBSOCKET
)
self.server.register_endpoint(
"/server/extensions/list", RequestType.GET, self._handle_list_extensions
)
self.server.register_endpoint(
"/server/extensions/request", RequestType.POST, self._handle_call_agent
)
def register_agent(self, connection: BaseRemoteConnection) -> 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: BaseRemoteConnection) -> None:
name = connection.client_data["name"]
if name in self.agents:
klippy: Klippy = self.server.lookup_component("klippy_connection")
registered_methods = self.agent_methods.pop(connection.uid, [])
for method in registered_methods:
klippy.unregister_method(method)
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 _register_agent_method(self, web_request: WebRequest) -> str:
conn = web_request.get_client_connection()
if conn is None:
raise self.server.error("No connection detected")
method_name = web_request.get_str("method_name")
klippy: Klippy = self.server.lookup_component("klippy_connection")
klippy.register_method_from_agent(conn, method_name)
self.agent_methods.setdefault(conn.uid, []).append(method_name)
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_with_response(method, args)
async def start_unix_server(self) -> None:
sockfile: str = self.server.get_app_args()["unix_socket_path"]
sock_path = pathlib.Path(sockfile).expanduser().resolve()
logging.info(f"Creating Unix Domain Socket at '{sock_path}'")
try:
self.uds_server = await asyncio.start_unix_server(
self.on_unix_socket_connected, sock_path, limit=UNIX_BUFFER_LIMIT
)
except asyncio.CancelledError:
raise
except Exception:
logging.exception(f"Failed to create Unix Domain Socket: {sock_path}")
self.uds_server = None
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(BaseRemoteConnection):
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[bytes, str]) -> None:
if isinstance(message, str):
data = message.encode() + b"\x03"
else:
data = message + 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
+275
View File
@@ -0,0 +1,275 @@
# 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 os
import re
import asyncio
import pathlib
import logging
import periphery
from ..utils import KERNEL_VERSION
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..eventloop import EventLoop
GpioEventCallback = Callable[[float, float, int], Optional[Awaitable[None]]]
GPIO_PATTERN = r"""
(?P<bias>[~^])?
(?P<inverted>!)?
(?:(?P<chip_id>gpiochip[0-9]+)/)?
(?P<pin_name>gpio(?P<pin_id>[0-9]+))
"""
BIAS_FLAG_TO_DESC: Dict[str, str] = {
"^": "pull_up",
"~": "pull_down",
"*": "disable" if KERNEL_VERSION >= (5, 5) else "default"
}
class GpioFactory:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.reserved_gpios: Dict[str, GpioBase] = {}
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, initial_value)
gpio = self._request_gpio(pparams)
try:
gpio_out = GpioOutputPin(gpio, pparams)
except Exception:
logging.exception("Error Instantiating GpioOutputPin")
gpio.close()
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: GpioEventCallback
) -> GpioEvent:
pin_params = self._parse_pin(pin_name, req_type="event")
gpio = self._request_gpio(pin_params)
event_loop = self.server.get_event_loop()
try:
gpio_event = GpioEvent(event_loop, gpio, pin_params, callback)
except Exception:
logging.exception("Error Instantiating GpioEvent")
gpio.close()
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]) -> periphery.GPIO:
full_name = pin_params["full_name"]
if full_name in self.reserved_gpios:
raise self.server.error(f"GPIO {full_name} already reserved")
chip_path = pathlib.Path("/dev").joinpath(pin_params["chip_id"])
if not chip_path.exists():
raise self.server.error(f"Chip path {chip_path} does not exist")
try:
gpio = periphery.GPIO(
str(chip_path),
pin_params["pin_id"],
pin_params["direction"],
edge=pin_params.get("edge", "none"),
bias=pin_params.get("bias", "default"),
inverted=pin_params["inverted"],
label="moonraker"
)
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 gpio
def _parse_pin(
self, pin_desc: str, initial_value: int = 0, req_type: str = "out"
) -> Dict[str, Any]:
params: Dict[str, Any] = {
"orig": pin_desc,
"inverted": False,
"request_type": req_type,
"initial_value": initial_value
}
pin_match = re.match(GPIO_PATTERN, pin_desc, re.VERBOSE)
if pin_match is None:
raise self.server.error(
f"Invalid pin format {pin_desc}. Refer to the configuration "
"documentation for details on the pin format."
)
bias_flag: Optional[str] = pin_match.group("bias")
params["inverted"] = pin_match.group("inverted") is not None
if req_type == "event":
params["direction"] = "in"
params["edge"] = "both"
params["bias"] = BIAS_FLAG_TO_DESC[bias_flag or "*"]
elif req_type == "out":
if bias_flag is not None:
raise self.server.error(
f"Invalid pin format {pin_desc}. Bias flag {bias_flag} "
"not available for output pins."
)
initial_state = bool(initial_value) ^ params["inverted"]
params["direction"] = "low" if not initial_state else "high"
chip_id: str = pin_match.group("chip_id") or "gpiochip0"
pin_name: str = pin_match.group("pin_name")
params["pin_id"] = int(pin_match.group("pin_id"))
params["chip_id"] = chip_id
params["full_name"] = f"{chip_id}:{pin_name}"
return params
def close(self) -> None:
for gpio in self.reserved_gpios.values():
gpio.close()
class GpioBase:
def __init__(
self, gpio: periphery.GPIO, pin_params: Dict[str, Any]
) -> None:
self.orig: str = pin_params["orig"]
self.name: str = pin_params["full_name"]
self.inverted: bool = pin_params["inverted"]
self.gpio = gpio
self.value: int = pin_params.get("initial_value", 0)
def close(self) -> None:
self.gpio.close()
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.gpio.write(bool(self.value))
MAX_ERRORS = 50
ERROR_RESET_TIME = 5.
class GpioEvent(GpioBase):
def __init__(
self,
event_loop: EventLoop,
gpio: periphery.GPIO,
pin_params: Dict[str, Any],
callback: GpioEventCallback
) -> None:
super().__init__(gpio, pin_params)
self.event_loop = event_loop
self.callback = callback
self.on_error: Optional[Callable[[str], None]] = None
self.debounce_period: float = 0
self.last_event_time: float = 0.
self.error_count = 0
self.last_error_reset = 0.
self.started = False
self.debounce_task: Optional[asyncio.Task] = None
os.set_blocking(self.gpio.fd, False)
def fileno(self) -> int:
return self.gpio.fd
def setup_debounce(
self, debounce_period: float, err_callback: Optional[Callable[[str], None]]
) -> None:
self.debounce_period = max(debounce_period, 0)
self.on_error = err_callback
def start(self) -> None:
if not self.started:
self.value = int(self.gpio.read())
self.last_event_time = self.event_loop.get_loop_time()
self.event_loop.add_reader(self.gpio.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.debounce_task is not None:
self.debounce_task.cancel()
self.debounce_task = None
if self.started:
self.event_loop.remove_reader(self.gpio.fd)
self.started = False
def close(self) -> None:
self.stop()
self.gpio.close()
def _on_event_trigger(self) -> None:
evt = self.gpio.read_event()
last_value = self.value
if evt.edge == "rising": # type: ignore
self.value = 1
elif evt.edge == "falling": # type: ignore
self.value = 0
else:
return
if self.debounce_period:
if self.debounce_task is None:
coro = self._debounce(last_value)
self.debounce_task = self.event_loop.create_task(coro)
else:
self._increment_error()
elif last_value != self.value:
# No debounce period and change detected
self._run_callback()
async def _debounce(self, last_value: int) -> None:
await asyncio.sleep(self.debounce_period)
self.debounce_task = None
if last_value != self.value:
self._run_callback()
def _run_callback(self) -> None:
eventtime = self.event_loop.get_loop_time()
evt_duration = eventtime - self.last_event_time
self.last_event_time = eventtime
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) -> None:
eventtime = self.event_loop.get_loop_time()
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(
f"Too Many Consecutive Errors, GPIO Event Disabled on {self.name}"
)
def load_component(config: ConfigHelper) -> GpioFactory:
return GpioFactory(config)
+654
View File
@@ -0,0 +1,654 @@
# History cache for printer jobs
#
# Copyright (C) 2024 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import time
import logging
from asyncio import Lock
from ..common import (
JobEvent,
RequestType,
HistoryFieldData,
FieldTracker,
SqlTableDefinition
)
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
Tuple
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest, UserInfo
from .database import MoonrakerDatabase as DBComp
from .job_state import JobState
from .file_manager.file_manager import FileManager
from .database import DBProviderWrapper
Totals = Dict[str, Union[float, int]]
AuxTotals = List[Dict[str, Any]]
BASE_TOTALS = {
"total_jobs": 0,
"total_time": 0.,
"total_print_time": 0.,
"total_filament_used": 0.,
"longest_job": 0.,
"longest_print": 0.
}
HIST_TABLE = "job_history"
TOTALS_TABLE = "job_totals"
def _create_totals_list(
job_totals: Dict[str, Any],
aux_totals: List[Dict[str, Any]],
instance: str = "default"
) -> List[Tuple[str, str, Any, Any, str]]:
"""
Returns a list of Tuples formatted for SQL Database insertion.
Fields of each tuple are in the following order:
provider, field, maximum, total, instance_id
"""
totals_list: List[Tuple[str, str, Any, Any, str]] = []
for key, value in job_totals.items():
total = value if key.startswith("total_") else None
maximum = value if total is None else None
totals_list.append(("history", key, maximum, total, instance))
for item in aux_totals:
if not isinstance(item, dict):
continue
totals_list.append(
(
item["provider"],
item["field"],
item["maximum"],
item["total"],
instance
)
)
return totals_list
class TotalsSqlDefinition(SqlTableDefinition):
name = TOTALS_TABLE
prototype = (
f"""
{TOTALS_TABLE} (
provider TEXT NOT NULL,
field TEXT NOT NULL,
maximum REAL,
total REAL,
instance_id TEXT NOT NULL,
PRIMARY KEY (provider, field, instance_id)
)
"""
)
version = 1
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
if last_version == 0:
# Migrate from "moonraker" namespace to a table
logging.info("Migrating history totals from moonraker namespace...")
hist_ns: Dict[str, Any] = db_provider.get_item("moonraker", "history", {})
job_totals: Dict[str, Any] = hist_ns.get("job_totals", BASE_TOTALS)
aux_totals: List[Dict[str, Any]] = hist_ns.get("aux_totals", [])
if not isinstance(job_totals, dict):
job_totals = dict(BASE_TOTALS)
if not isinstance(aux_totals, list):
aux_totals = []
totals_list = _create_totals_list(job_totals, aux_totals)
sql_conn = db_provider.connection
with sql_conn:
sql_conn.executemany(
f"INSERT OR IGNORE INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)",
totals_list
)
try:
db_provider.delete_item("moonraker", "history")
except Exception:
pass
class HistorySqlDefinition(SqlTableDefinition):
name = HIST_TABLE
prototype = (
f"""
{HIST_TABLE} (
job_id INTEGER PRIMARY KEY ASC,
user TEXT NOT NULL,
filename TEXT,
status TEXT NOT NULL,
start_time REAL NOT NULL,
end_time REAL,
print_duration REAL NOT NULL,
total_duration REAL NOT NULL,
filament_used REAL NOT NULL,
metadata pyjson,
auxiliary_data pyjson NOT NULL,
instance_id TEXT NOT NULL
)
"""
)
version = 1
def _get_entry_item(
self, entry: Dict[str, Any], name: str, default: Any = 0.
) -> Any:
val = entry.get(name)
if val is None:
return default
return val
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
if last_version == 0:
conn = db_provider.connection
for batch in db_provider.iter_namespace("history", 1000):
conv_vals: List[Tuple[Any, ...]] = []
entry: Dict[str, Any]
for key, entry in batch.items():
if not isinstance(entry, dict):
logging.info(
f"History migration, skipping invalid value: {key} {entry}"
)
continue
try:
conv_vals.append(
(
None,
self._get_entry_item(entry, "user", "No User"),
self._get_entry_item(entry, "filename", "unknown"),
self._get_entry_item(entry, "status", "error"),
self._get_entry_item(entry, "start_time"),
self._get_entry_item(entry, "end_time"),
self._get_entry_item(entry, "print_duration"),
self._get_entry_item(entry, "total_duration"),
self._get_entry_item(entry, "filament_used"),
self._get_entry_item(entry, "metadata", {}),
self._get_entry_item(entry, "auxiliary_data", []),
"default"
)
)
except KeyError:
continue
if not conv_vals:
continue
placeholders = ",".join("?" * len(conv_vals[0]))
with conn:
conn.executemany(
f"INSERT INTO {HIST_TABLE} VALUES({placeholders})",
conv_vals
)
db_provider.wipe_local_namespace("history")
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()
FieldTracker.class_init(self)
self.auxiliary_fields: List[HistoryFieldData] = []
database: DBComp = self.server.lookup_component("database")
self.history_table = database.register_table(HistorySqlDefinition())
self.totals_table = database.register_table(TotalsSqlDefinition())
self.job_totals: Totals = dict(BASE_TOTALS)
self.aux_totals: AuxTotals = []
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:state_changed", self._on_job_state_changed)
self.server.register_event_handler(
"klippy_apis:job_start_complete", self._on_job_requested)
self.server.register_notification("history:history_changed")
self.server.register_endpoint(
"/server/history/job", RequestType.GET | RequestType.DELETE,
self._handle_job_request
)
self.server.register_endpoint(
"/server/history/list", RequestType.GET, self._handle_jobs_list
)
self.server.register_endpoint(
"/server/history/totals", RequestType.GET, self._handle_job_totals
)
self.server.register_endpoint(
"/server/history/reset_totals", RequestType.POST,
self._handle_job_total_reset
)
self.current_job: Optional[PrinterJob] = None
self.current_job_id: Optional[int] = None
self.job_user: str = "No User"
self.job_paused: bool = False
async def component_init(self) -> None:
# Popluate totals
valid_aux_totals = [
(item.provider, item.name) for item in self.auxiliary_fields
if item.has_totals()
]
cursor = await self.totals_table.execute(f"SELECT * from {TOTALS_TABLE}")
await cursor.set_arraysize(200)
for row in await cursor.fetchall():
provider, field, maximum, total, _ = tuple(row)
if provider == "history":
self.job_totals[field] = total if maximum is None else maximum
elif (provider, field) in valid_aux_totals:
item = dict(row)
item.pop("instance_id", None)
self.aux_totals.append(item)
# Check for interrupted jobs
cursor = await self.history_table.execute(
f"SELECT job_id FROM {HIST_TABLE} WHERE status = 'in_progress'"
)
interrupted_jobs: List[int] = [row[0] for row in await cursor.fetchall()]
if interrupted_jobs:
async with self.history_table as tx:
await tx.execute(
f"UPDATE {HIST_TABLE} SET status = 'interrupted' "
"WHERE status = 'in_progress'"
)
self.server.add_log_rollover_item(
"interrupted_history",
"The following jobs were detected as interrupted: "
f"{interrupted_jobs}"
)
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
req_type = web_request.get_request_type()
if req_type == RequestType.GET:
job_id = web_request.get_str("uid")
cursor = await self.history_table.execute(
f"SELECT * FROM {HIST_TABLE} WHERE job_id = ?", (int(job_id, 16),)
)
result = await cursor.fetchone()
if result is None:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
job = dict(result)
return {"job": self._prep_requested_job(job, job_id)}
if req_type == RequestType.DELETE:
all = web_request.get_boolean("all", False)
if all:
cursor = await self.history_table.execute(
f"SELECT job_id FROM {HIST_TABLE} WHERE instance_id = ?",
("default",)
)
await cursor.set_arraysize(1000)
deljobs = [f"{row[0]:06X}" for row in await cursor.fetchall()]
async with self.history_table as tx:
await tx.execute(
f"DELETE FROM {HIST_TABLE} WHERE instance_id = ?",
("default",)
)
return {'deleted_jobs': deljobs}
job_id = web_request.get_str("uid")
async with self.history_table as tx:
cursor = await tx.execute(
f"DELETE FROM {HIST_TABLE} WHERE job_id = ?", (int(job_id, 16),)
)
if cursor.rowcount < 1:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
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:
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").upper()
if order not in ["ASC", "DESC"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
# Build SQL Select Statement
values: List[Any] = ["default"]
sql_statement = f"SELECT * FROM {HIST_TABLE} WHERE instance_id = ?"
if before != -1:
sql_statement += " and end_time < ?"
values.append(before)
if since != -1:
sql_statement += " and start_time > ?"
values.append(since)
sql_statement += f" ORDER BY job_id {order}"
if limit > 0:
sql_statement += " LIMIT ? OFFSET ?"
values.append(limit)
values.append(start)
cursor = await self.history_table.execute(sql_statement, values)
await cursor.set_arraysize(1000)
jobs: List[Dict[str, Any]] = []
for row in await cursor.fetchall():
job = dict(row)
job_id = f"{row['job_id']:06X}"
jobs.append(self._prep_requested_job(job, job_id))
return {"count": len(jobs), "jobs": jobs}
async def _handle_job_totals(
self, web_request: WebRequest
) -> Dict[str, Union[Totals, AuxTotals]]:
return {
"job_totals": self.job_totals,
"auxiliary_totals": self.aux_totals
}
async def _handle_job_total_reset(
self, web_request: WebRequest
) -> Dict[str, Union[Totals, AuxTotals]]:
if self.current_job is not None:
raise self.server.error("Job in progress, cannot reset totals")
last_totals = self.job_totals
self.job_totals = dict(BASE_TOTALS)
last_aux_totals = self.aux_totals
self._update_aux_totals(reset=True)
totals_list = _create_totals_list(self.job_totals, self.aux_totals)
async with self.totals_table as tx:
await tx.execute(
f"DELETE FROM {TOTALS_TABLE} WHERE instance_id = ?", ("default",)
)
await tx.executemany(
f"INSERT INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)", totals_list
)
return {
"last_totals": last_totals,
"last_auxiliary_totals": last_aux_totals
}
async def _on_job_state_changed(
self,
job_event: JobEvent,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.job_paused = job_event == JobEvent.PAUSED
if job_event == JobEvent.STARTED:
if self.current_job is not None:
# Finish with the previous state
await self.finish_job("cancelled", prev_stats)
await self.add_job(PrinterJob(new_stats))
elif job_event == JobEvent.COMPLETE:
await self.finish_job("completed", new_stats)
elif job_event == JobEvent.ERROR:
await self.finish_job("error", new_stats)
elif job_event in (JobEvent.CANCELLED, JobEvent.STANDBY):
# Cancel on "standby" for backward compatibility with
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
await self.finish_job("cancelled", prev_stats)
def _on_job_requested(self, user: Optional[UserInfo]) -> None:
username = user.username if user is not None else "No User"
self.job_user = username
if self.current_job is not None:
self.current_job.user = username
async def _handle_shutdown(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
await self.finish_job("klippy_shutdown", last_ps)
async def _handle_disconnect(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
await self.finish_job("klippy_disconnect", last_ps)
async def add_job(self, job: PrinterJob) -> None:
async with self.request_lock:
self.current_job = job
self.current_job_id = None
self.current_job.user = self.job_user
self.grab_job_metadata()
for field in self.auxiliary_fields:
field.tracker.reset()
self.current_job.set_aux_data(self.auxiliary_fields)
new_id = await self.save_job(job, None)
if new_id is None:
logging.info(f"Error saving job, filename '{job.filename}'")
return
self.current_job_id = new_id
job_id = f"{new_id:06X}"
self.update_metadata(job_id)
logging.debug(
f"History Job Added - Id: {job_id}, File: {job.filename}"
)
self.send_history_event("added")
async def save_job(self, job: PrinterJob, job_id: Optional[int]) -> Optional[int]:
values: List[Any] = [
job_id,
job.user,
job.filename,
job.status,
job.start_time,
job.end_time,
job.print_duration,
job.total_duration,
job.filament_used,
job.metadata,
job.auxiliary_data,
"default"
]
placeholders = ",".join("?" * len(values))
async with self.history_table as tx:
cursor = await tx.execute(
f"REPLACE INTO {HIST_TABLE} VALUES({placeholders})", values
)
return cursor.lastrowid
async def delete_job(self, job_id: Union[int, str]) -> None:
if isinstance(job_id, str):
job_id = int(job_id, 16)
async with self.history_table as tx:
tx.execute(
f"DELETE FROM {HIST_TABLE} WHERE job_id = ?", (job_id,)
)
async def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
async with self.request_lock:
if self.current_job is None or self.current_job_id is None:
self._reset_current_job()
return
if (
pstats.get('filename') != self.current_job.filename or
pstats.get('total_duration', 0.) < self.current_job.total_duration
):
# Print stats have been reset, do not update this job with them
pstats = {}
self.current_job.user = self.job_user
self.current_job.finish(status, pstats)
# Regrab metadata incase metadata wasn't parsed yet due to file upload
self.grab_job_metadata()
self.current_job.set_aux_data(self.auxiliary_fields)
job_id = f"{self.current_job_id:06X}"
await self.save_job(self.current_job, self.current_job_id)
self.update_metadata(job_id)
await self._update_job_totals()
logging.debug(
f"History Job Finished - Id: {job_id}, "
f"File: {self.current_job.filename}, "
f"Status: {status}"
)
self.send_history_event("finished")
self._reset_current_job()
def _reset_current_job(self) -> None:
self.current_job = None
self.current_job_id = None
self.job_user = "No User"
async def get_job(
self, job_id: Union[int, str]
) -> Optional[Dict[str, Any]]:
if isinstance(job_id, str):
job_id = int(job_id, 16)
cursor = await self.history_table.execute(
f"SELECT * FROM {HIST_TABLE} WHERE job_id = ?", (job_id,)
)
result = await cursor.fetchone()
return dict(result) if result is not None else result
def grab_job_metadata(self) -> None:
if self.current_job is None:
return
filename: str = self.current_job.filename
mdst = self.file_manager.get_metadata_storage()
metadata: Dict[str, Any] = mdst.get(filename, {})
# 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.metadata = metadata
def update_metadata(self, job_id: str) -> None:
if self.current_job is None:
return
mdst = self.file_manager.get_metadata_storage()
filename: str = self.current_job.filename
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': job_id
})
mdst.insert(filename, metadata)
async def _update_job_totals(self) -> None:
if self.current_job is None:
return
job = self.current_job
self._accumulate_total("total_jobs", 1)
self._accumulate_total("total_time", job.total_duration)
self._accumulate_total("total_print_time", job.print_duration)
self._accumulate_total("total_filament_used", job.filament_used)
self._maximize_total("longest_job", job.total_duration)
self._maximize_total("longest_print", job.print_duration)
self._update_aux_totals()
totals_list = _create_totals_list(self.job_totals, self.aux_totals)
async with self.totals_table as tx:
await tx.executemany(
f"REPLACE INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)", totals_list
)
def _accumulate_total(self, field: str, val: Union[int, float]) -> None:
self.job_totals[field] += val
def _maximize_total(self, field: str, val: Union[int, float]) -> None:
self.job_totals[field] = max(self.job_totals[field], val)
def _update_aux_totals(self, reset: bool = False) -> None:
last_totals = self.aux_totals
self.aux_totals = [
field.get_totals(last_totals, reset)
for field in self.auxiliary_fields
if field.has_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_id = f"{self.current_job_id:06X}"
job = self._prep_requested_job(self.current_job.get_stats(), 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]:
fm = self.file_manager
mtime = job.get("metadata", {}).get("modified", None)
job["exists"] = fm.check_file_exists("gcodes", job['filename'], mtime)
job["job_id"] = job_id
job.pop("instance_id", None)
return job
def register_auxiliary_field(self, new_field: HistoryFieldData) -> None:
if new_field.provider == "history":
raise self.server.error("Provider name 'history' is reserved")
for field in self.auxiliary_fields:
if field == new_field:
raise self.server.error(
f"Field {field.name} already registered by "
f"provider {field.provider}."
)
self.auxiliary_fields.append(new_field)
def tracking_enabled(self, check_paused: bool) -> bool:
if self.current_job is None:
return False
return not self.job_paused if check_paused else True
async def on_exit(self) -> None:
if self.current_job is None:
return
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
await 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: str = ""
self.metadata: Dict[str, Any] = {}
self.print_duration: float = 0.
self.status: str = "in_progress"
self.start_time = time.time()
self.total_duration: float = 0.
self.auxiliary_data: List[Dict[str, Any]] = []
self.user: str = "No User"
self.update_from_ps(data)
def finish(self,
status: str,
print_stats: Dict[str, Any] = {}
) -> None:
self.end_time = time.time()
self.status = status if status is not None else "error"
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 set_aux_data(self, fields: List[HistoryFieldData]) -> None:
self.auxiliary_data = [field.as_dict() for field in fields]
def update_from_ps(self, data: Dict[str, Any]) -> None:
for i in data:
if hasattr(self, i) and data[i] is not None:
setattr(self, i, data[i])
def load_component(config: ConfigHelper) -> History:
return History(config)
+531
View File
@@ -0,0 +1,531 @@
# 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 time
import asyncio
import pathlib
import tempfile
import logging
import copy
from ..utils import ServerError
from ..utils import json_wrapper as jsonw
from tornado.escape import 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[bytes, 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,
basic_auth_user: Optional[str] = None,
basic_auth_pass: Optional[str] = None
) -> 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 = jsonw.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
req_args: Dict[str, Any] = dict(
body=body,
request_timeout=request_timeout,
connect_timeout=connect_timeout
)
if basic_auth_user is not None:
assert basic_auth_pass is not None
req_args["auth_username"] = basic_auth_user
req_args["auth_password"] = basic_auth_pass
req_args["auth_mode"] = "basic"
request = HTTPRequest(url, method, headers, **req_args)
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 wrap_request(self, default_url: str, **kwargs) -> HttpRequestWrapper:
return HttpRequestWrapper(self, default_url, **kwargs)
def close(self):
self.client.close()
class HttpRequestWrapper:
def __init__(
self, client: HttpClient, default_url: str, **kwargs
) -> None:
self._do_request = client.request
self._last_response: Optional[HttpResponse] = None
self.default_request_args: Dict[str, Any] = {
"method": "GET",
"url": default_url,
}
self.default_request_args.update(kwargs)
self.request_args = copy.deepcopy(self.default_request_args)
self.reset()
async def send(self, **kwargs) -> HttpResponse:
req_args = copy.deepcopy(self.request_args)
req_args.update(kwargs)
method = req_args.pop("method", self.default_request_args["method"])
url = req_args.pop("url", self.default_request_args["url"])
self._last_response = await self._do_request(method, url, **req_args)
return self._last_response
def set_method(self, method: str) -> None:
self.request_args["method"] = method
def set_url(self, url: str) -> None:
self.request_args["url"] = url
def set_body(
self, body: Optional[Union[str, List[Any], Dict[str, Any]]]
) -> None:
self.request_args["body"] = body
def add_header(self, name: str, value: str) -> None:
headers = self.request_args.get("headers", {})
headers[name] = value
self.request_args["headers"] = headers
def set_headers(self, headers: Dict[str, str]) -> None:
self.request_args["headers"] = headers
def reset(self) -> None:
self.request_args = copy.deepcopy(self.default_request_args)
def last_response(self) -> Optional[HttpResponse]:
return self._last_response
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) -> Union[List[Any], Dict[str, Any]]:
return jsonw.loads(self._result)
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)
+357
View File
@@ -0,0 +1,357 @@
# 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
from ..common import JobEvent, RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Union,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest, UserInfo
from .klippy_apis import KlippyAPI
from .file_manager.file_manager import FileManager
from .job_state import JobState
class JobQueue:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.queued_jobs: Dict[str, QueuedJob] = {}
self.lock = asyncio.Lock()
self.pause_requested: bool = False
self.load_on_start = config.getboolean("load_on_startup", False)
self.automatic = config.getboolean("automatic_transition", False)
self.queue_state: str = "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:state_changed", self._on_job_state_changed
)
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", RequestType.POST | RequestType.DELETE,
self._handle_job_request
)
self.server.register_endpoint(
"/server/job_queue/pause", RequestType.POST, self._handle_pause_queue
)
self.server.register_endpoint(
"/server/job_queue/start", RequestType.POST, self._handle_start_queue
)
self.server.register_endpoint(
"/server/job_queue/status", RequestType.GET, self._handle_queue_status
)
self.server.register_endpoint(
"/server/job_queue/jump", RequestType.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:
has_requested_pause = self.pause_requested
await self.pause_queue()
self.pause_requested = has_requested_pause
async def _on_job_state_changed(self, job_event: JobEvent, *args) -> None:
if job_event == JobEvent.COMPLETE:
await self._on_job_complete()
elif job_event.aborted:
await self._on_job_abort()
async def _on_job_complete(self) -> None:
if not self.automatic:
return
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) -> 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:
self._set_queue_state("paused")
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":
self._set_queue_state("paused")
raise self.server.error(
"Queue State Changed during Transition Gcode")
self._set_queue_state("starting")
await kapis.start_print(
filename, wait_klippy_started=True, user=job.user
)
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":
# Set the queue to ready if items are in the queue
# and auto transition is enabled
set_ready = len(self.queued_jobs) > 0 and 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,
user: Optional[UserInfo] = None
) -> 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, user)
self.queued_jobs[queued_job.job_id] = queued_job
self._send_queue_event(action="jobs_added")
if self.automatic and not self.pause_requested:
jstate: JobState = self.server.lookup_component("job_state")
last_evt = jstate.get_last_job_event()
if last_evt.is_printing or last_evt == JobEvent.PAUSED:
self._set_queue_state("ready")
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
async with self.lock:
self.pause_requested = True
async def start_queue(self) -> None:
async with self.lock:
self.pause_requested = False
if self.queue_state in ("ready", "paused"):
if not self.queued_jobs:
self._set_queue_state("paused")
elif 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, False
)
else:
self._set_queue_state("ready" if self.automatic else "paused")
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]:
req_type = web_request.get_request_type()
if req_type == RequestType.POST:
files = web_request.get_list('filenames')
reset = web_request.get_boolean("reset", False)
# Validate that all files exist before queueing
user = web_request.get_current_user()
await self.queue_job(files, reset=reset, user=user)
elif req_type == RequestType.DELETE:
if web_request.get_boolean("all", False):
await self.delete_job([], all=True)
else:
job_ids = web_request.get_list('job_ids')
await self.delete_job(job_ids)
else:
raise self.server.error(f"Invalid request type: {req_type}")
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, user: Optional[UserInfo] = None) -> None:
self.filename = filename
self.job_id = f"{id(self):016X}"
self.time_added = time.time()
self._user = user
def __str__(self) -> str:
return self.filename
@property
def user(self) -> Optional[UserInfo]:
return self._user
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)
+135
View File
@@ -0,0 +1,135 @@
# 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,
)
from ..common import JobEvent, KlippyState
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.last_event: JobEvent = JobEvent.STANDBY
self.server.register_event_handler(
"server:klippy_started", self._handle_started
)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_disconnect
)
def _handle_disconnect(self):
state = self.last_print_stats.get("state", "")
if state in ("printing", "paused"):
# set error state
self.last_print_stats["state"] = "error"
self.last_event = JobEvent.ERROR
async def _handle_started(self, state: KlippyState) -> None:
if state != KlippyState.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, self._status_update)
except self.server.error:
logging.info("Error subscribing to print_stats")
return
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], _: float) -> 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 != old_state:
if self._check_idle(old_state):
if new_state == "printing":
new_state = "started"
elif new_state != "standby":
# send a started event prior to the detected event
logging.info(
f"Job started event inferred: transition from "
f"{old_state} to {new_state} state"
)
self._send_job_event("started", prev_ps, new_ps)
elif 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:
new_state = "started"
logging.debug(
f"Job State Changed - Prev State: {old_state}, "
f"New State: {new_state}"
)
self._send_job_event(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 _check_idle(self, state: str) -> bool:
return state in ("standby", "complete", "cancelled", "error")
def _send_job_event(
self, state: str, prev_ps: Dict[str, Any], new_ps: Dict[str, Any]
) -> None:
if state == "started":
logging.info(f"Job Started: {new_ps['filename']}")
# NOTE: Individual job_state events are DEPRECATED. New modules
# should register handlers for "job_state: status_changed" and
# match against the JobEvent object provided.
self.server.send_event(f"job_state:{state}", prev_ps, new_ps)
self.last_event = JobEvent.from_string(state)
self.server.send_event(
"job_state:state_changed",
self.last_event,
prev_ps,
new_ps
)
def get_last_stats(self) -> Dict[str, Any]:
return dict(self.last_print_stats)
def get_last_job_event(self) -> JobEvent:
return self.last_event
def load_component(config: ConfigHelper) -> JobState:
return JobState(config)
+302
View File
@@ -0,0 +1,302 @@
# 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
import logging
from ..utils import Sentinel
from ..common import WebRequest, APITransport, RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
TypeVar,
Mapping,
Callable,
Coroutine
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import UserInfo
from .klippy_connection import KlippyConnection as Klippy
Subscription = Dict[str, Optional[List[Any]]]
SubCallback = Callable[[Dict[str, Dict[str, Any]], float], Optional[Coroutine]]
_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(APITransport):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
self.eventloop = self.server.get_event_loop()
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 = {}
self.subscription_callbacks: List[SubCallback] = []
# Register GCode Aliases
self.server.register_endpoint(
"/printer/print/pause", RequestType.POST, self._gcode_pause
)
self.server.register_endpoint(
"/printer/print/resume", RequestType.POST, self._gcode_resume
)
self.server.register_endpoint(
"/printer/print/cancel", RequestType.POST, self._gcode_cancel
)
self.server.register_endpoint(
"/printer/print/start", RequestType.POST, self._gcode_start_print
)
self.server.register_endpoint(
"/printer/restart", RequestType.POST, self._gcode_restart
)
self.server.register_endpoint(
"/printer/firmware_restart", RequestType.POST, self._gcode_firmware_restart
)
self.server.register_event_handler(
"server:klippy_disconnect", self._on_klippy_disconnect
)
def _on_klippy_disconnect(self) -> None:
self.host_subscription.clear()
self.subscription_callbacks.clear()
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')
user = web_request.get_current_user()
return await self.start_print(filename, user=user)
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,
transport: Optional[APITransport] = None
) -> Any:
try:
req = WebRequest(method, params, transport=transport or 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,
user: Optional[UserInfo] = None
) -> 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 specified
# 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()
logging.info(f"Requesting Job Start, filename = {filename}")
ret = await self.run_gcode(script)
self.server.send_event("klippy_apis:job_start_complete", user)
return ret
async def pause_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:pause_requested")
logging.info("Requesting job pause...")
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")
logging.info("Requesting job resume...")
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")
logging.info("Requesting job cancel...")
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 specified
# 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']
if default is not Sentinel.MISSING:
return default
raise self.server.error("Invalid response received from Klippy", 500)
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"]
if default is not Sentinel.MISSING:
return default
raise self.server.error("Invalid response received from Klippy", 500)
async def subscribe_objects(
self,
objects: Mapping[str, Optional[List[str]]],
callback: Optional[SubCallback] = None,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
# The host transport shares subscriptions amongst all components
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": dict(self.host_subscription)}
result = await self._send_klippy_request(SUBSCRIPTION_ENDPOINT, params, default)
if isinstance(result, dict) and "status" in result:
if callback is not None:
self.subscription_callbacks.append(callback)
return result["status"]
if default is not Sentinel.MISSING:
return default
raise self.server.error("Invalid response received from Klippy", 500)
async def subscribe_from_transport(
self,
objects: Mapping[str, Optional[List[str]]],
transport: APITransport,
default: Union[Sentinel, _T] = Sentinel.MISSING,
full_response: bool = False
) -> Union[_T, Dict[str, Any]]:
params = {"objects": dict(objects)}
result = await self._send_klippy_request(
SUBSCRIPTION_ENDPOINT, params, default, transport
)
if isinstance(result, dict) and "status" in result:
if full_response:
return result
return result["status"]
if default is not Sentinel.MISSING:
return default
raise self.server.error("Invalid response received from Klippy", 500)
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:
for cb in self.subscription_callbacks:
self.eventloop.register_callback(cb, status, eventtime)
self.server.send_event("server:status_update", status)
def load_component(config: ConfigHelper) -> KlippyAPI:
return KlippyAPI(config)
+852
View File
@@ -0,0 +1,852 @@
# 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 getpass
import asyncio
import pathlib
from ..utils import ServerError, get_unix_peer_credentials
from ..utils import json_wrapper as jsonw
from ..common import KlippyState, RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Optional,
Callable,
Coroutine,
Dict,
List,
Set,
Tuple,
Union
)
if TYPE_CHECKING:
from ..common import WebRequest, APITransport, BaseRemoteConnection
from ..confighelper import ConfigHelper
from .klippy_apis import KlippyAPI
from .file_manager.file_manager import FileManager
from .machine import Machine
from .job_state import JobState
from .database import MoonrakerDatabase as Database
FlexCallback = Callable[..., Optional[Coroutine]]
Subscription = Dict[str, Optional[List[str]]]
# 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",
]
# Items to exclude from the subscription cache. They never change and can be
# quite large.
CACHE_EXCLUSIONS = {
"configfile": ["config", "settings"]
}
INIT_TIME = .25
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
SVC_INFO_KEY = "klippy_connection.service_info"
SRC_PATH_KEY = "klippy_connection.path"
PY_EXEC_KEY = "klippy_connection.executable"
class KlippyConnection:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.uds_address = config.getpath(
"klippy_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.subscription_lock = asyncio.Lock()
self._klippy_info: Dict[str, Any] = {}
self._klippy_identified: bool = False
self._klippy_initializing: bool = False
self._klippy_started: bool = False
self._methods_registered: 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._path = pathlib.Path("~/klipper").expanduser()
self._executable = pathlib.Path("~/klippy-env/bin/python").expanduser()
self.init_attempts: int = 0
self._state: KlippyState = KlippyState.DISCONNECTED
self._state.set_message("Klippy Disconnected")
self.subscriptions: Dict[APITransport, Subscription] = {}
self.subscription_cache: Dict[str, Dict[str, Any]] = {}
# Setup remote methods accessible 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)
@property
def klippy_apis(self) -> KlippyAPI:
return self.server.lookup_component("klippy_apis")
@property
def state(self) -> KlippyState:
if self.is_connected() and not self._klippy_started:
return KlippyState.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]
@property
def path(self) -> pathlib.Path:
return self._path
@property
def executable(self) -> pathlib.Path:
return self._executable
def load_saved_state(self) -> None:
db: Database = self.server.lookup_component("database")
sync_provider = db.get_provider_wrapper()
kc_info: Dict[str, Any]
kc_info = sync_provider.get_item("moonraker", "klippy_connection", {})
self._path = pathlib.Path(kc_info.get("path", str(self._path)))
self._executable = pathlib.Path(kc_info.get("executable", str(self.executable)))
self._service_info = kc_info.get("service_info", {})
async def component_init(self) -> None:
machine: Machine = self.server.lookup_component("machine")
if self._service_info:
machine.log_service_info(self._service_info)
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 = jsonw.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:
request.set_exception(ServerError("Klippy Host not connected", 503))
return
data = jsonw.dumps(request.to_dict()) + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
request.set_exception(ServerError("Klippy Write Request Cancelled", 503))
raise
except Exception:
request.set_exception(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 register_method_from_agent(
self, connection: BaseRemoteConnection, method_name: str
) -> Optional[Awaitable]:
if connection.client_data["type"] != "agent":
raise self.server.error(
"Only connections of the 'agent' type can register methods"
)
if method_name in self.remote_methods:
raise self.server.error(
f"Remote method ({method_name}) already registered"
)
def _on_agent_method_received(**kwargs) -> None:
connection.call_method(method_name, kwargs)
self.remote_methods[method_name] = _on_agent_method_received
self.klippy_reg_methods.append(method_name)
if self._methods_registered and self._state != KlippyState.DISCONNECTED:
coro = self.klippy_apis.register_method(method_name)
return self.event_loop.create_task(coro)
return None
def unregister_method(self, method_name: str):
self.remote_methods.pop(method_name, None)
try:
self.klippy_reg_methods.remove(method_name)
except ValueError:
pass
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 # type: ignore
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):
await self._get_service_info(self._peer_cred["process_id"])
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:
peer_cred = get_unix_peer_credentials(writer, "Klippy")
if not peer_cred:
return False
if peer_cred.get("process_id") == 1:
logging.debug("Klipper Unix Socket created via Systemd Socket Activation")
return False
self._peer_cred = peer_cred
logging.debug(
f"Klippy Connection: Received Peer Credentials: {self._peer_cred}"
)
return True
async def _get_service_info(self, process_id: int) -> None:
machine: Machine = self.server.lookup_component("machine")
provider = machine.get_system_provider()
svc_info = await provider.extract_service_info("klipper", process_id)
if svc_info != self._service_info:
db: Database = self.server.lookup_component('database')
db.insert_item("moonraker", SVC_INFO_KEY, svc_info)
self._service_info = svc_info
machine.log_service_info(svc_info)
def _save_path_info(self) -> None:
kpath = pathlib.Path(self._klippy_info["klipper_path"])
kexec = pathlib.Path(self._klippy_info["python_path"])
db: Database = self.server.lookup_component("database")
if kpath != self.path:
self._path = kpath
db.insert_item("moonraker", SRC_PATH_KEY, str(kpath))
logging.info(f"Updated Stored Klipper Source Path: {kpath}")
if kexec != self.executable:
self._executable = kexec
db.insert_item("moonraker", PY_EXEC_KEY, str(kexec))
logging.info(f"Updated Stored Klipper Python Path: {kexec}")
async def _init_klippy_connection(self) -> bool:
self._klippy_identified = False
self._klippy_started = False
self._klippy_initializing = True
self._methods_registered = False
self._missing_reqs.clear()
self.init_attempts = 0
self._state = KlippyState.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', [])
for ep in endpoints:
if ep not in RESERVED_ENDPOINTS:
self.server.register_endpoint(
ep, RequestType.GET | RequestType.POST, self.request,
is_remote=True
)
async def _request_initial_subscriptions(self) -> None:
try:
await self.klippy_apis.subscribe_objects({'webhooks': None})
except ServerError:
logging.exception("Unable to subscribe to webhooks object")
else:
logging.info("Webhooks Subscribed")
try:
await self.klippy_apis.subscribe_gcode_output()
except ServerError:
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)
klipper_pid: Optional[int] = result.get("process_id")
if klipper_pid is not None:
cur_pid: Optional[int] = self._peer_cred.get("process_id")
if cur_pid is None or klipper_pid != cur_pid:
self._peer_cred = dict(
process_id=klipper_pid,
group_id=result.get("group_id", -1),
user_id=result.get("user_id", -1)
)
await self._get_service_info(klipper_pid)
self._klippy_info = dict(result)
state_message: str = self._state.message
if "state_message" in self._klippy_info:
state_message = self._klippy_info["state_message"]
self._state.set_message(state_message)
if "state" not in result:
return
if send_id:
self._klippy_identified = True
self._save_path_info()
await self.server.send_event("server:klippy_identified")
# Request initial endpoints to register info, emergency stop APIs
await self._request_endpoints()
self._state = KlippyState.from_string(result["state"], state_message)
if self._state != KlippyState.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 != KlippyState.READY:
logging.info("\n" + self._state.message)
if (
self._state == KlippyState.SHUTDOWN and
startup_state != KlippyState.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}'")
self._methods_registered = True
if self._state == KlippyState.READY:
logging.info("Klippy ready")
await self.server.send_event("server:klippy_ready")
if self._state == KlippyState.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("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("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"
request.set_result(result)
else:
err: Union[str, Dict[str, str]]
err = cmd.get('error', "Malformed Klippy Response")
if isinstance(err, dict):
err = err.get("message", "Malformed Klippy Response")
request.set_exception(ServerError(err, 400))
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, Dict[str, Any]]
) -> None:
for field, item in status.items():
self.subscription_cache.setdefault(field, {}).update(item)
if 'webhooks' in status:
wh: Dict[str, str] = status['webhooks']
state_message: str = self._state.message
if "state_message" in wh:
state_message = wh["state_message"]
self._state.set_message(state_message)
# XXX - process other states (startup, ready, error, etc)?
if "state" in wh:
new_state = KlippyState.from_string(wh["state"], state_message)
if (
new_state == KlippyState.SHUTDOWN and
not self._klippy_initializing and
self._state != KlippyState.SHUTDOWN
):
# 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 = new_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]:
async with self.subscription_lock:
args = web_request.get_args()
conn = web_request.get_subscribable()
if conn is None:
raise self.server.error(
"No connection associated with subscription request"
)
# if the connection has an existing subscription pop it off
self.subscriptions.pop(conn, None)
requested_sub: Subscription = args.get('objects', {})
all_subs: Subscription = dict(requested_sub)
# Build the subscription request from a superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
if obj in all_subs:
prev_items = all_subs[obj]
if items is None or prev_items is None:
all_subs[obj] = None
else:
uitems = list(set(prev_items) | 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, 20.0)
# prune the status response
pruned_status: Dict[str, Dict[str, Any]] = {}
status_diff: Dict[str, Dict[str, Any]] = {}
all_status: Dict[str, Dict[str, Any]] = result['status']
for obj, fields in all_status.items():
# Diff the current cache, then update the cache
if obj in self.subscription_cache:
cached_status = self.subscription_cache[obj]
for field_name, value in fields.items():
if field_name not in cached_status:
continue
if value != cached_status[field_name]:
status_diff.setdefault(obj, {})[field_name] = value
if obj in CACHE_EXCLUSIONS:
# Make a shallow copy so we can pop off fields we want to
# exclude from the cache without modifying the return value
fields_to_cache = dict(fields)
removed: List[str] = []
for excluded_field in CACHE_EXCLUSIONS[obj]:
if excluded_field in fields_to_cache:
removed.append(excluded_field)
del fields_to_cache[excluded_field]
if removed:
logging.debug(
"Removed excluded fields from subscription cache: "
f"{obj}: {removed}"
)
self.subscription_cache[obj] = fields_to_cache
else:
self.subscription_cache[obj] = fields
# Prune Response
if obj in requested_sub:
valid_fields = requested_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
}
if status_diff:
# The response to the status request contains changed data, so it
# is necessary to manually push the status update to existing
# subscribers
logging.debug(
f"Detected status difference during subscription: {status_diff}"
)
self._process_status_update(result["eventtime"], status_diff)
for obj_name in list(self.subscription_cache.keys()):
# Prune the cache to match the current status response
if obj_name not in all_status:
del self.subscription_cache[obj_name]
result['status'] = pruned_status
if requested_sub:
self.subscriptions[conn] = requested_sub
return result
async def _request_standard(
self, web_request: WebRequest, timeout: Optional[float] = None
) -> 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)
try:
return await base_request.wait(timeout)
finally:
self.pending_requests.pop(base_request.id, None)
def remove_subscription(self, conn: APITransport) -> 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 == KlippyState.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"
def get_subscription_cache(self) -> Dict[str, Dict[str, Any]]:
return self.subscription_cache
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._methods_registered = False
self._state = KlippyState.DISCONNECTED
self._state.set_message("Klippy Disconnected")
for request in self.pending_requests.values():
request.set_exception(ServerError("Klippy Disconnected", 503))
self.pending_requests = {}
self.subscriptions = {}
self.subscription_cache.clear()
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._fut = asyncio.get_running_loop().create_future()
async def wait(self, timeout: Optional[float] = None) -> Any:
start_time = time.time()
to = timeout or 60.
while True:
try:
return await asyncio.wait_for(asyncio.shield(self._fut), to)
except asyncio.TimeoutError:
if timeout is not None:
self._fut.cancel()
raise ServerError("Klippy request timed out", 500) from None
pending_time = time.time() - start_time
logging.info(
f"Request '{self.rpc_method}' pending: "
f"{pending_time:.2f} seconds"
)
def set_exception(self, exc: Exception) -> None:
if not self._fut.done():
self._fut.set_exception(exc)
def set_result(self, result: Any) -> None:
if not self._fut.done():
self._fut.set_result(result)
def to_dict(self) -> Dict[str, Any]:
return {
'id': self.id,
'method': self.rpc_method,
'params': self.params
}
def load_component(config: ConfigHelper) -> KlippyConnection:
return KlippyConnection(config)
+147
View File
@@ -0,0 +1,147 @@
# 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
from ldap3.utils.conv import escape_filter_chars
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ldap3.abstract.entry import Entry
VALID_MEMBERSHIP_ATTRS = ["memberOf", "isMemberOf"]
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)
self.membership_attr = config.getchoice(
"membership_attribute", VALID_MEMBERSHIP_ATTRS, "memberOf"
)
self.check_dn_case = config.getboolean("check_dn_case", True)
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: str, password: str) -> 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: str, password: str) -> 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"
escaped_user = escape_filter_chars(username)
ldfilt = f"(&(objectClass=Person)({attr_name}={escaped_user}))"
if self.user_filter:
ldfilt = self.user_filter.replace("USERNAME", escaped_user)
try:
with ldap3.Connection(server, **conn_args) as conn:
search_attrs = None if self.group_dn is None else [self.membership_attr]
ret = conn.search(
self.base_dn, ldfilt, attributes=search_attrs
)
if not ret:
logging.info(f"LDAP User '{username}' Not Found")
raise self.server.error("Unauthorized", 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:
logging.exception("LDAP authentication failed")
else:
logging.info("Invalid LDAP Username or Password")
raise self.server.error("Unauthorized", 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
member_attr = getattr(user, self.membership_attr, None)
if member_attr is None:
logging.info(
f"Membership attribute {self.membership_attr} not present "
"in user entry"
)
return False
groups: list[str] = getattr(member_attr, "values", [])
req_dn = self.group_dn
logging.debug(f"Required Group DN: {req_dn}, User Group DNs: {groups}")
if not self.check_dn_case:
groups = [grp.lower() for grp in groups]
req_dn = req_dn.lower()
if req_dn in groups:
logging.debug(
f"LDAP User {username} group match success, login successful"
)
return True
logging.info(f"User '{username}' is not a member of configured group_dn.")
return False
def load_component(config: ConfigHelper) -> MoonrakerLDAP:
return MoonrakerLDAP(config)
File diff suppressed because it is too large. Load diff
+883
View File
@@ -0,0 +1,883 @@
# 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 pathlib
import ssl
from collections import deque
import paho.mqtt.client as paho_mqtt
import paho.mqtt
from ..common import (
TransportType,
RequestType,
WebRequest,
APITransport,
KlippyState
)
from ..utils import json_wrapper as jsonw
try:
from paho.mqtt.reasoncodes import ReasonCode
except ImportError:
from paho.mqtt.reasoncodes import ReasonCodes as ReasonCode
# Annotation imports
from typing import (
List,
Optional,
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Union,
Tuple,
Awaitable,
Deque,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import JsonRPC, APIDefinition
from ..eventloop import FlexTimer
from .klippy_apis import KlippyAPI
from paho.mqtt.properties import Properties
FlexCallback = Callable[[bytes], Optional[Coroutine]]
RPCCallback = Callable[..., Coroutine]
PAHO_MQTT_VERSION = tuple([int(p) for p in paho.mqtt.__version__.split(".")])
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 PAHO_MQTT_VERSION >= (2, 0):
return self._v2_reconnect(sock)
if PAHO_MQTT_VERSION < (1, 6):
# Paho Mqtt Version < 1.6.x
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"", # type: ignore
"to_process": 0,
"pos": 0
}
with self._out_packet_mutex: # type: ignore
self._out_packet = deque() # type: ignore
with self._current_out_packet_mutex: # type: ignore
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 # type: ignore
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( # type: ignore
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( # type: ignore
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): # type: ignore
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) # type: ignore
if self._transport == "websockets":
sock.settimeout(self._keepalive)
sock = paho_mqtt.WebsocketWrapper( # type: ignore
sock, self._host, self._port, self._ssl,
self._websocket_path, self._websocket_extra_headers
) # type: ignore
self._sock = sock # type: ignore
assert self._sock is not None
self._sock.setblocking(False)
self._registered_write = False
self._call_socket_open() # type: ignore
return self._send_connect(self._keepalive)
def _v2_reconnect(self, sock: Optional[socket.socket] = None):
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._ping_t = 0.0 # type: ignore
self._state = paho_mqtt._ConnectionState.MQTT_CS_CONNECTING # type: ignore
self._sock_close()
# Mark all currently outgoing QoS = 0 packets as lost,
# or `wait_for_publish()` could hang forever
for pkt in self._out_packet:
if (
pkt["command"] & 0xF0 == paho_mqtt.PUBLISH and
pkt["qos"] == 0 and pkt["info"] is not None
):
pkt["info"].rc = paho_mqtt.MQTT_ERR_CONN_LOST
pkt["info"]._set_as_published()
self._out_packet.clear()
with self._msgtime_mutex:
self._last_msg_in = paho_mqtt.time_func()
self._last_msg_out = paho_mqtt.time_func()
# Put messages in progress in a valid state.
self._messages_reconnect_reset()
with self._callback_mutex:
on_pre_connect = self.on_pre_connect # type: ignore
if on_pre_connect:
try:
on_pre_connect(self, self._userdata)
except Exception as err:
self._easy_log(
paho_mqtt.MQTT_LOG_ERR,
'Caught exception in on_pre_connect: %s', err
)
if not self.suppress_exceptions:
raise
if sock is None:
self._sock = self._create_socket() # type: ignore
elif self._ssl:
self._sock = self._ssl_wrap_socket(sock)
else:
self._sock = sock # type: ignore
self._sock.setblocking(False) # type: ignore[attr-defined]
self._registered_write = False
self._call_socket_open(self._sock) # type: ignore
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[ReasonCode]]
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, ReasonCode):
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 | paho_mqtt.SocketLike
) -> 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 | paho_mqtt.SocketLike
) -> 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 | paho_mqtt.SocketLike
) -> None:
self.loop.add_writer(sock, client.loop_write)
def _on_socket_unregister_write(
self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket | paho_mqtt.SocketLike
) -> None:
self.loop.remove_writer(sock)
async def misc_loop(self) -> None:
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break
logging.info("MQTT Misc Loop Complete")
class MQTTClient(APITransport):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.eventloop = self.server.get_event_loop()
self.address: str = config.get('address')
self.port: int = config.getint('port', 1883)
self.tls_enabled: bool = config.getboolean("enable_tls", False)
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)
client_id: str = config.get("client_id", "")
if PAHO_MQTT_VERSION < (2, 0):
self.client = ExtPahoClient(
client_id, protocol=self.protocol # type: ignore
)
else:
self.client = ExtPahoClient(
paho_mqtt.CallbackAPIVersion.VERSION1, client_id, # type: ignore
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] = {}
# We don't need to register these endpoints over the MQTT transport as they
# are redundant. MQTT clients can already publish and subscribe.
ep_transports = TransportType.all() & ~TransportType.MQTT
self.server.register_endpoint(
"/server/mqtt/publish", RequestType.POST, self._handle_publish_request,
transports=ep_transports
)
self.server.register_endpoint(
"/server/mqtt/subscribe", RequestType.POST,
self._handle_subscription_request,
transports=ep_transports
)
# Subscribe to API requests
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, str] = config.getdict(
"status_objects", {}, allow_empty_fields=True
)
self.status_interval = config.getfloat("status_interval", 0, above=.25)
self.status_cache: Dict[str, Dict[str, Any]] = {}
self.status_update_timer: Optional[FlexTimer] = None
self.last_status_time = 0.
self.status_objs: Dict[str, Optional[List[str]]] = {}
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.server.register_event_handler(
"server:klippy_disconnect", self._handle_klippy_disconnect
)
if self.status_interval:
self.status_update_timer = self.eventloop.register_timer(
self._handle_timed_status_update
)
self.timestamp_deque: Deque = deque(maxlen=20)
self.api_qos = config.getint('api_qos', self.qos)
if config.getboolean("enable_moonraker_api", True):
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=jsonw.dumps({'server': 'offline'}),
qos=self.qos, retain=True)
if self.tls_enabled:
self.client.tls_set()
self.client.connect_async(self.address, self.port)
self.connect_task = self.eventloop.create_task(
self._do_reconnect(first=True)
)
async def _handle_klippy_started(self, state: KlippyState) -> None:
if self.status_objs:
kapi: KlippyAPI = self.server.lookup_component("klippy_apis")
result = await kapi.subscribe_from_transport(
self.status_objs, self, default=None, full_response=True
)
if result is not None:
status: Dict[str, Any] = result["status"]
eventtime: float = result["eventtime"]
self.send_status(status, eventtime)
if self.status_update_timer is not None:
self.status_update_timer.start(delay=self.status_interval)
def _handle_klippy_disconnect(self):
if self.status_update_timer is not None:
self.status_update_timer.stop()
if self.status_cache:
payload = self.status_cache
self.status_cache = {}
self._publish_status_update(payload, self.last_status_time)
def _on_message(self,
client: str | paho_mqtt.Client,
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.eventloop.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, ReasonCode],
properties: Optional[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:
_, msg_id = client.subscribe(subs)
if msg_id is not None:
sub_fut: asyncio.Future = self.eventloop.create_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[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 = self.eventloop.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[ReasonCode]],
properties: Optional[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[Properties] = None,
reasoncodes: Optional[ReasonCode] = 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.eventloop.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) is not type(e) or last_err.args != e.args:
logging.exception("MQTT Connection Error")
last_err = e
continue
sock.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:
_, msg_id = self.client.subscribe(topic, qos)
if msg_id is not None:
sub_fut: asyncio.Future = self.eventloop.create_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]
_, msg_id = self.client.unsubscribe(topic)
if msg_id is not None:
unsub_fut: asyncio.Future = self.eventloop.create_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 = self.eventloop.create_future()
if isinstance(payload, (dict, list)):
try:
payload = jsonw.dumps(payload)
except jsonw.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 = self.eventloop.create_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 = self.eventloop.create_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 = jsonw.loads(ret)
except jsonw.JSONDecodeError:
payload = ret.decode()
return {
'topic': topic,
'payload': payload
}
async def _process_api_request(self, payload: bytes) -> None:
rpc: JsonRPC = self.server.lookup_component("jsonrpc")
response = await rpc.dispatch(payload, self)
if response is not None:
await self.publish_topic(self.api_resp_topic, response,
self.api_qos)
@property
def transport_type(self) -> TransportType:
return TransportType.MQTT
def screen_rpc_request(
self, api_def: APIDefinition, req_type: RequestType, 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 not self.status_interval:
self._publish_status_update(status, eventtime)
else:
for key, val in status.items():
self.status_cache.setdefault(key, {}).update(val)
self.last_status_time = eventtime
def _handle_timed_status_update(self, eventtime: float) -> float:
if self.status_cache:
payload = self.status_cache
self.status_cache = {}
self._publish_status_update(payload, self.last_status_time)
return eventtime + self.status_interval
def _publish_status_update(self, status: Dict[str, Any], eventtime: float) -> None:
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.status_update_timer is not None:
self.status_update_timer.stop()
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)
+217
View File
@@ -0,0 +1,217 @@
# 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
import pathlib
import re
from ..common import JobEvent, RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Dict,
Any,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .file_manager.file_manager import FileManager
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, List[NotifierInstance]] = {}
prefix_sections = config.get_prefix_sections("notifier")
self.register_remote_actions()
logging.info(f"Loading notifiers, Apprise version {apprise.__version__}")
for section in prefix_sections:
cfg = config[section]
try:
notifier = NotifierInstance(cfg)
for job_event in list(JobEvent):
if job_event == JobEvent.STANDBY:
continue
evt_name = str(job_event)
if "*" in notifier.events or evt_name in notifier.events:
self.events.setdefault(evt_name, []).append(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, exc_info=e)
continue
self.notifiers[notifier.get_name()] = notifier
self.register_endpoints(config)
self.server.register_event_handler(
"job_state:state_changed", self._on_job_state_changed
)
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)
async def _on_job_state_changed(
self,
job_event: JobEvent,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
evt_name = str(job_event)
for notifier in self.events.get(evt_name, []):
await notifier.notify(evt_name, [prev_stats, new_stats])
def register_endpoints(self, config: ConfigHelper):
self.server.register_endpoint(
"/server/notifiers/list", RequestType.GET, self._handle_notifier_list
)
self.server.register_debug_endpoint(
"/debug/notifiers/test", RequestType.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)
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 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.attach = config.gettemplate("attach", None)
url_template = config.gettemplate("url")
self.url = url_template.render()
if re.match(r"\w+?://", self.url) is None:
raise config.error(f"Invalid url for: {config.get_name()}")
self.title = config.gettemplate("title", None)
self.body = config.gettemplate("body", None)
upper_body_format = config.get("body_format", 'text').upper()
if not hasattr(apprise.NotifyFormat, upper_body_format):
raise config.error(f"Invalid body_format for {config.get_name()}")
self.body_format = getattr(apprise.NotifyFormat, upper_body_format)
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),
"body_format": self.config.get("body_format", 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
attachments: List[str] = []
if self.attach is not None:
fm: FileManager = self.server.lookup_component("file_manager")
try:
rendered = self.attach.render(context)
except self.server.error as e:
self.server.add_warning(
f"[notifier {self.name}]: The attachment is not valid. The "
"template failed to render.",
f"notifier {self.name}",
exc_info=e
)
self.attach = None
else:
for item in rendered.splitlines():
item = item.strip()
if not item:
continue
if re.match(r"https?://", item) is not None:
# Attachment is a url, system check not necessary
attachments.append(item)
continue
attach_path = pathlib.Path(item).expanduser().resolve()
if not attach_path.is_file():
self.server.add_warning(
f"[notifier {self.name}]: Invalid attachment detected, "
f"file does not exist: {attach_path}.",
f"notifier {self.name}"
)
elif not fm.can_access_path(attach_path):
self.server.add_warning(
f"[notifier {self.name}]: Invalid attachment detected, "
f"no read permission for the file {attach_path}.",
f"notifier {self.name}"
)
else:
attachments.append(str(attach_path))
await self.apprise.async_notify(
rendered_body.strip(), rendered_title.strip(),
body_format=self.body_format,
attach=None if not attachments else attachments
)
def get_name(self) -> str:
return self.name
def load_component(config: ConfigHelper) -> Notifier:
return Notifier(config)
+413
View File
@@ -0,0 +1,413 @@
# 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
from ..common import RequestType, TransportType, KlippyState
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
)
if TYPE_CHECKING:
from .klippy_connection import KlippyConnection
from ..confighelper import ConfigHelper
from ..common 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', RequestType.GET, self._get_version,
transports=TransportType.HTTP, wrap_result=False
)
self.server.register_endpoint(
'/api/server', RequestType.GET, self._get_server,
transports=TransportType.HTTP, wrap_result=False
)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', RequestType.POST, self._post_login_user,
transports=TransportType.HTTP, wrap_result=False
)
self.server.register_endpoint(
'/api/currentuser', RequestType.GET, self._post_login_user,
transports=TransportType.HTTP, wrap_result=False
)
self.server.register_endpoint(
'/api/settings', RequestType.GET, self._get_settings,
transports=TransportType.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', RequestType.GET, self._get_job,
transports=TransportType.HTTP, wrap_result=False
)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', RequestType.GET, self._get_printer,
transports=TransportType.HTTP, wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', RequestType.POST, self._post_command,
transports=TransportType.HTTP, wrap_result=False
)
# TODO: head/tool/bed/chamber specific read/issue
# Printer profiles
self.server.register_endpoint(
'/api/printerprofiles', RequestType.GET, self._get_printerprofiles,
transports=TransportType.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>.+)", RequestType.POST,
self._select_file, transports=TransportType.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:
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
klippy_state = kconn.state
if not klippy_state.startup_complete():
return 'Offline'
elif klippy_state != KlippyState.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
"""
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
klippy_state = kconn.state
return {
'server': OCTO_VERSION,
'safemode': None if klippy_state == KlippyState.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_str('command')
rel_path: str = web_request.get_str('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_boolean('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
user = web_request.get_current_user()
if pstate not in ["printing", "paused", "not_avail"]:
try:
await self.klippy_apis.start_print(filename, user=user)
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, user=user)
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)
@@ -3,17 +3,33 @@
# 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
from __future__ import annotations
import time
import json
import errno
import logging
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
from ..utils import ServerError, async_serial
from ..utils import json_wrapper as jsonw
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
List,
Callable,
Coroutine,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .klippy_connection import KlippyConnection
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.
@@ -24,197 +40,79 @@ class PanelDueError(ServerError):
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self, config, paneldue):
self.ioloop = IOLoop.current()
self.paneldue = paneldue
self.port = config.get('serial')
self.baud = config.getint('baud', 57600)
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
self.send_busy = False
self.send_buffer = b""
self.attempting_connect = True
self.ioloop.spawn_callback(self._connect)
def disconnect(self, reconnect=False):
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
self.partial_input = b""
self.send_buffer = b""
self.paneldue.initialized = False
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.ioloop.call_later(1., self._connect)
async def _connect(self):
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
logging.info("Unable to connect, aborting")
break
logging.info(f"Attempting to connect to: {self.port}")
try:
# XXX - sometimes the port cannot be exclusively locked, this
# would likely be due to a restart where the serial port was
# not correctly closed. Maybe don't use exclusive mode?
self.ser = serial.Serial(
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception(f"Unable to open port: {self.port}")
await gen.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
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")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect(reconnect=True)
return
# Process incoming data using same method as gcode.py
try:
data = os.read(fd, 4096)
except os.error:
return
if not data:
# possibly an error, disconnect
self.disconnect(reconnect=True)
logging.info("serial_display: No data received, disconnecting")
return
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
try:
line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(line)
except ServerError:
logging.exception(
f"GCode Processing Error: {line}")
self.paneldue.handle_gcode_response(
f"!! GCode Processing Error: {line}")
except Exception:
logging.exception("Error during gcode processing")
def send(self, data):
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.ioloop.spawn_callback(self._do_send)
async def _do_send(self):
while self.send_buffer:
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect(reconnect=True)
return
self.send_busy = False
class PanelDue:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.ser_conn = SerialConnection(config, self)
self.file_manager = self.server.lookup_plugin('file_manager')
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
self.kinematics = "none"
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 = "Repetier | Klipper"
self.last_message = None
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
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(maxlen=100)
self.debug_queue: Deque[str] = deque(maxlen=100)
self.enabled: bool = True
# Initialize tracked state.
self.printer_state = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
self.extruder_count = 0
self.heaters = []
self.is_ready = False
self.is_shutdown = False
self.initialized = False
self.cq_busy = self.gq_busy = False
self.command_queue = []
self.gc_queue = []
self.last_printer_state = 'O'
self.last_update_time = 0.
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
self.printer_state: Dict[str, Dict[str, Any]] = kconn.get_subscription_cache()
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 = ""
self.mbox_sequence = 0
self.available_macros = {}
self.confirmed_gcode: str = ""
self.mbox_sequence: int = 0
self.available_macros: Dict[str, str] = {}
self.confirmed_macros = {
"RESTART": "RESTART",
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
macros = config.get('macros', None)
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
macros = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macros}
conf_macros = config.get('confirmed_macros', None)
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
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
self.available_macros.update(self.confirmed_macros)
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.non_trivial_keys = config.getlist('non_trivial_keys', ["Klipper state"])
self.ser_conn = async_serial.AsyncSerialConnection.from_config(config)
logging.info("PanelDue Configured")
# Register server events
self.server.register_event_handler(
"server:klippy_ready", self._process_klippy_ready)
"server:klippy_ready", self._process_klippy_ready
)
self.server.register_event_handler(
"server:klippy_shutdown", self._process_klippy_shutdown)
"server:klippy_shutdown", self._process_klippy_shutdown
)
self.server.register_event_handler(
"server:klippy_disconnect", self._process_klippy_disconnect)
"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)
"server:gcode_response", self.handle_gcode_response
)
self.server.register_remote_method("paneldue_beep", self.paneldue_beep)
self.server.register_remote_method(
"paneldue_beep", self.paneldue_beep)
# These commands are directly executued on the server and do not to
# These commands are directly executed on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
self.direct_gcodes: Dict[str, FlexCallback] = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
@@ -223,7 +121,7 @@ class PanelDue:
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes = {
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
@@ -237,28 +135,60 @@ class PanelDue:
'M999': lambda args: "FIRMWARE_RESTART"
}
async def _process_klippy_ready(self):
async def run_serial(self) -> None:
last_exc = Exception()
while self.enabled:
try:
self.ser_conn.open()
except (self.ser_conn.error, OSError) as e:
if type(last_exc) is not type(e) and last_exc.args != e.args:
logging.exception("PanelDue Serial Open Error")
last_exc = e
await asyncio.sleep(2.)
continue
reader = self.ser_conn.reader
decoded_line: str = ""
async for line in reader:
try:
decoded_line = line.strip().decode('utf-8', 'ignore')
self.process_line(decoded_line)
except asyncio.CancelledError:
raise
except ServerError:
msg = f"GCode Processing Error: {decoded_line}"
logging.exception(msg)
self.handle_gcode_response(f"!! {msg}")
except Exception:
logging.exception("Error during gcode processing")
if self.enabled:
await asyncio.sleep(2.)
last_exc = Exception()
self.initialized = False
async def component_init(self) -> None:
self.serial_task = self.event_loop.create_task(self.run_serial())
async def _process_klippy_ready(self) -> None:
# Request "info" and "configfile" status
retries = 10
printer_info = cfg_status = {}
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})
cfg_status = await self.klippy_apis.query_objects({'configfile': None})
except self.server.error:
logging.exception("PanelDue initialization request failed")
retries -= 1
if not retries:
raise
await gen.sleep(1.)
await asyncio.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + \
printer_info['software_version']
config = cfg_status.get('configfile', {}).get('config', {})
printer_cfg = config.get('printer', {})
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(
@@ -267,66 +197,65 @@ class PanelDue:
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()}
# Make subscription request
sub_args: Dict[str, Optional[List[str]]] = {
"motion_report": None,
"gcode_move": None,
"toolhead": None,
"virtual_sdcard": None,
"fan": None,
"display_status": None,
"print_stats": None,
"idle_timeout": None,
"gcode_macro PANELDUE_BEEP": None
}
self.extruder_count = 0
self.heaters = []
extruders = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(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 = await self.klippy_apis.subscribe_objects(sub_args)
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):
def _process_klippy_shutdown(self) -> None:
self.is_shutdown = True
def _process_klippy_disconnect(self):
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_ready = False
self.is_shutdown = self.is_shutdown = False
def handle_status_update(self, status):
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
def paneldue_beep(self, frequency, duration):
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):
def process_line(self, line: str) -> None:
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
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 = int(line[1:line_index])
line_no: Optional[int] = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
@@ -368,7 +297,7 @@ class PanelDue:
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params = {}
params: Dict[str, Any] = {}
for p in parts[1:]:
if p[0] not in "PSR":
params["arg_p"] = p.strip(" \"\t\n")
@@ -389,20 +318,20 @@ class PanelDue:
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
func = self.special_gcodes[cmd]
script = func(parts[1:])
sgc_func = self.special_gcodes[cmd]
script = sgc_func(parts[1:])
if not script:
return
self.queue_gcode(script)
def queue_gcode(self, script):
def queue_gcode(self, script: str) -> None:
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.ioloop.spawn_callback(self._process_gcode_queue)
self.event_loop.register_callback(self._process_gcode_queue)
async def _process_gcode_queue(self):
async def _process_gcode_queue(self) -> None:
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
@@ -416,24 +345,24 @@ class PanelDue:
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd, *args, **kwargs):
def queue_command(self, cmd: FlexCallback, *args, **kwargs) -> None:
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.ioloop.spawn_callback(self._process_command_queue)
self.event_loop.register_callback(self._process_command_queue)
async def _process_command_queue(self):
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 asyncio.iscoroutine(ret):
if ret is not None:
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename):
def _clean_filename(self, filename: str) -> str:
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
@@ -451,17 +380,17 @@ class PanelDue:
filename = "/" + filename
return filename
def _prepare_M23(self, args):
def _prepare_M23(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args):
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):
def _prepare_M98(self, args: List[str]) -> str:
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
@@ -473,12 +402,12 @@ class PanelDue:
cmd = ""
return cmd
def _prepare_M290(self, args):
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):
def _prepare_M292(self, args: List[str]) -> str:
p_val = int(args[0][1])
if p_val == 0:
cmd = self.confirmed_gcode
@@ -486,13 +415,13 @@ class PanelDue:
return cmd
return ""
def _create_confirmation(self, name, gcode):
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 = {}
mbox: Dict[str, Any] = {}
mbox['msgBox.mode'] = 3
mbox['msgBox.msg'] = msg
mbox['msgBox.seq'] = self.mbox_sequence
@@ -502,7 +431,7 @@ class PanelDue:
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response):
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 \
@@ -514,11 +443,11 @@ class PanelDue:
self.last_gcode_response = response
return
def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
self.ser_conn.send(byte_resp.encode())
def write_response(self, response: Dict[str, Any]) -> None:
byte_resp = jsonw.dumps(response) + b"\r\n"
self.ser_conn.send(byte_resp)
def _get_printer_status(self):
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,
@@ -526,8 +455,9 @@ class PanelDue:
if self.is_shutdown:
return 'S'
printer_state = self.printer_state
sd_state = printer_state['print_stats'].get('state', "standby")
p_state = self.printer_state
sd_state: str
sd_state = p_state.get("print_stats", {}).get("state", "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
# Resuming
@@ -535,8 +465,9 @@ class PanelDue:
# Printing
return 'P'
elif sd_state == "paused":
p_active = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
p_active = (
p_state.get("idle_timeout", {}).get("state", 'Idle') == "Printing"
)
if p_active and self.last_printer_state != 'A':
# Pausing
return 'D'
@@ -546,12 +477,15 @@ class PanelDue:
return 'I'
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
def _run_paneldue_M408(self,
arg_r: Optional[int] = None,
arg_s: int = 1
) -> None:
response: Dict[str, Any] = {}
sequence = arg_r
response_type = arg_s
curtime = self.ioloop.time()
curtime = self.event_loop.get_loop_time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
@@ -579,54 +513,64 @@ class PanelDue:
response['axes'] = 3
p_state = self.printer_state
toolhead = p_state.get("toolhead", {})
gcode_move = p_state.get("gcode_move", {})
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)
response['babystep'] = round(
gcode_move.get('homing_origin', [0., 0., 0., 0.])[2], 3
)
# Current position
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
pos: List[float]
homed_pos: str
sfactor: float
pos = p_state.get("motion_report", {}).get('live_position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
homed_pos = 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)
sfactor = round(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 = print_stats.get('filename', "")
sd_print_state = print_stats.get('state')
sd_status = p_state.get('virtual_sdcard', {})
print_stats = p_state.get('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 = sd_status.get('progress', 0)
progress: float = sd_status.get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time = self.file_metadata.get('estimated_time', 0)
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 = print_stats.get('filament_used', 0.)
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 = p_state['gcode_move'].get(
'gcode_position', [0., 0., 0., 0.])[2]
cur_height: float = 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 = print_stats.get('print_duration', 0.)
duration: float = print_stats.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
@@ -634,35 +578,39 @@ class PanelDue:
self.current_file = ""
self.file_metadata = {}
fan_speed = p_state['fan'].get('speed')
fan_speed: Optional[float] = p_state.get('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 is not None:
extruder_name = toolhead.get('extruder', "")
if extruder_name:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor = round(p_state['gcode_move'].get(
'extrude_factor', 1.) * 100., 2)
efactor: float = round(gcode_move.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)
htr_state = p_state.get(name, {})
temp: float = round(htr_state.get('temperature', 0.0), 1)
target: float = round(htr_state.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'):
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 = p_state['display_status'].get('message')
msg: str = p_state.get('display_status', {}).get('message', "")
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
@@ -671,7 +619,7 @@ class PanelDue:
self.last_message = msg
self.write_response(response)
def _run_paneldue_M20(self, arg_p, arg_s=0):
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
response_type = arg_s
if response_type != 2:
logging.info(
@@ -687,7 +635,7 @@ class PanelDue:
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response = {'dir': path}
response: Dict[str, Any] = {'dir': path}
response['files'] = []
if path == "/macros":
@@ -711,7 +659,7 @@ class PanelDue:
response['files'] = flist
self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
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
@@ -725,9 +673,9 @@ class PanelDue:
path = "gcodes/" + path
await self.file_manager.delete_file(path)
def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
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:
@@ -754,37 +702,41 @@ class PanelDue:
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata = self.file_manager.get_file_metadata(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 = metadata.get('slicer')
slicer: Optional[str] = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height = metadata.get('object_height')
height: Optional[float] = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height = metadata.get('layer_height')
layer_height: Optional[float] = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament = metadata.get('filament_total')
filament: Optional[float] = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time = metadata.get('estimated_time')
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):
self.ser_conn.disconnect()
async def close(self) -> None:
self.enabled = False
await self.ser_conn.close()
if hasattr(self, "serial_task"):
await self.serial_task
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
msg += f"\nSequence {i}: {gc}"
logging.debug(msg)
def load_plugin(config):
def load_component(config: ConfigHelper) -> PanelDue:
return PanelDue(config)
File diff suppressed because it is too large. Load diff
+418
View File
@@ -0,0 +1,418 @@
# 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 struct
import fcntl
import time
import re
import os
import pathlib
import logging
from collections import deque
from ..utils import ioctl_macros
from ..common import RequestType
# Annotation imports
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Deque,
Any,
List,
Tuple,
Optional,
Dict,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .websockets import WebsocketManager
STAT_CALLBACK = Callable[[int], Optional[Awaitable]]
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
VCIO_PATH = "/dev/vcio"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
NET_DEV_PATH = "/proc/net/dev"
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
HWMON_ROOT_PATH = "/sys/class/hwmon/"
HWMON_PLATFORMS = {
"coretemp": "Intel",
"k10temp": "AMD",
"cpu_thermal": "Raspberry Pi"
}
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[VCGenCmd] = None
if os.path.exists(VC_GEN_CMD_FILE) and os.path.exists(VCIO_PATH):
logging.info("Detected 'vcgencmd', throttle checking enabled")
self.vcgencmd = VCGenCmd()
self.server.register_notification("proc_stats:cpu_throttled")
else:
logging.info("Unable to find 'vcgencmd', throttle checking "
"disabled")
self.temp_file = pathlib.Path(self._get_cpu_thermal_file())
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", RequestType.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
and 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]:
ret = {'bits': 0, 'flags': ["?"]}
if self.vcgencmd is not None:
async with self.throttle_check_lock:
try:
resp = await self.event_loop.run_in_thread(self.vcgencmd.run)
ret["bits"] = tstate = int(resp.strip().split("=")[-1], 16)
ret["flags"] = [
desc for flag, desc in THROTTLED_FLAGS.items() if flag & tstate
]
except Exception:
pass
return ret
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 _get_cpu_thermal_file(self) -> str:
if os.path.isdir(HWMON_ROOT_PATH):
for hwmon in os.scandir(HWMON_ROOT_PATH):
if not hwmon.is_dir():
continue
hwmon_name = pathlib.Path(hwmon.path + "/name")
try:
name = hwmon_name.read_text().strip()
if name in HWMON_PLATFORMS:
pf = HWMON_PLATFORMS[name]
logging.info(f"Monitoring temperature for {pf} CPU")
return hwmon.path + "/temp1_input"
except Exception:
pass
logging.info("Monitoring temperature using default thermal zone")
return TEMPERATURE_PATH
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()
class VCGenCmd:
"""
This class uses the BCM2835 Mailbox to directly query the throttled
state. This should be less resource intensive than calling "vcgencmd"
in a subprocess.
"""
MAX_STRING_SIZE = 1024
GET_RESULT_CMD = 0x00030080
UINT_SIZE = struct.calcsize("@I")
def __init__(self) -> None:
self.cmd_struct = struct.Struct(f"@6I{self.MAX_STRING_SIZE}sI")
self.cmd_buf = bytearray(self.cmd_struct.size)
self.mailbox_req = ioctl_macros.IOWR(100, 0, "c_char_p")
self.err_logged: bool = False
def run(self, cmd: str = "get_throttled") -> str:
try:
fd = os.open(VCIO_PATH, os.O_RDWR)
self.cmd_struct.pack_into(
self.cmd_buf, 0,
self.cmd_struct.size,
0x00000000,
self.GET_RESULT_CMD,
self.MAX_STRING_SIZE,
0,
0,
cmd.encode("utf-8"),
0x00000000
)
fcntl.ioctl(fd, self.mailbox_req, self.cmd_buf)
except OSError:
if not self.err_logged:
logging.exception("VCIO vcgencmd failed")
self.err_logged = True
return ""
finally:
os.close(fd)
result = self.cmd_struct.unpack_from(self.cmd_buf)
ret: int = result[5]
if ret:
logging.info(f"vcgencmd returned {ret}")
resp: bytes = result[6]
null_index = resp.find(b'\x00')
if null_index <= 0:
return ""
return resp[:null_index].decode()
def load_component(config: ConfigHelper) -> ProcStats:
return ProcStats(config)
+90
View File
@@ -0,0 +1,90 @@
# 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
from ..utils import json_wrapper as jsonw
from typing import (
TYPE_CHECKING,
Dict,
Optional,
Any
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
class Secrets:
def __init__(self, config: ConfigHelper) -> None:
server = config.get_server()
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] = {}
self.secrets_file = fpath
if fpath.is_file():
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 get_secrets_file(self) -> pathlib.Path:
return self.secrets_file
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 jsonw.loads(data)
except jsonw.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)
+345
View File
@@ -0,0 +1,345 @@
# 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 functools import partial
from ..common import RequestType, HistoryFieldData
# Annotation imports
from typing import (
Any,
DefaultDict,
Deque,
Dict,
List,
Optional,
Type,
TYPE_CHECKING,
Union,
Callable
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .mqtt import MQTTClient
from .history import History
SENSOR_UPDATE_TIME = 1.0
SENSOR_EVENT_NAME = "sensors:sensor_update"
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
class BaseSensor:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.error_state: Optional[str] = None
self.id = config.get_name().split(maxsplit=1)[-1]
self.type = config.get("type")
self.name = config.get("name", self.id)
self.last_measurements: Dict[str, Union[int, float]] = {}
self.last_value: Dict[str, Union[int, float]] = {}
store_size = config.getint("sensor_store_size", 1200)
self.values: DefaultDict[str, Deque[Union[int, float]]] = defaultdict(
lambda: deque(maxlen=store_size)
)
self.param_info: List[Dict[str, str]] = []
history: History = self.server.lookup_component("history")
self.field_info: Dict[str, List[HistoryFieldData]] = {}
all_opts = list(config.get_options().keys())
cfg_name = config.get_name()
param_prefix = "parameter_"
hist_field_prefix = "history_field_"
for opt in all_opts:
if opt.startswith(param_prefix):
name = opt[len(param_prefix):]
data = config.getdict(opt)
data["name"] = opt[len(param_prefix):]
self.param_info.append(data)
continue
if not opt.startswith(hist_field_prefix):
continue
name = opt[len(hist_field_prefix):]
field_cfg: Dict[str, str] = config.getdict(opt)
ident: Optional[str] = field_cfg.pop("parameter", None)
if ident is None:
raise config.error(
f"[{cfg_name}]: option '{opt}', key 'parameter' must be"
f"specified"
)
do_init: str = field_cfg.pop("init_tracker", "false").lower()
reset_cb = self._gen_reset_callback(ident) if do_init == "true" else None
excl_paused: str = field_cfg.pop("exclude_paused", "false").lower()
report_total: str = field_cfg.pop("report_total", "false").lower()
report_max: str = field_cfg.pop("report_maximum", "false").lower()
precision: Optional[str] = field_cfg.pop("precision", None)
try:
fdata = HistoryFieldData(
name,
cfg_name,
field_cfg.pop("desc", f"{ident} tracker"),
field_cfg.pop("strategy", "basic"),
units=field_cfg.pop("units", None),
reset_callback=reset_cb,
exclude_paused=excl_paused == "true",
report_total=report_total == "true",
report_maximum=report_max == "true",
precision=int(precision) if precision is not None else None,
)
except Exception as e:
raise config.error(
f"[{cfg_name}]: option '{opt}', error encountered during "
f"sensor field configuration: {e}"
) from e
for key in field_cfg.keys():
self.server.add_warning(
f"[{cfg_name}]: Option '{opt}' contains invalid key '{key}'"
)
self.field_info.setdefault(ident, []).append(fdata)
history.register_auxiliary_field(fdata)
def _gen_reset_callback(self, param_name: str) -> Callable[[], float]:
def on_reset() -> float:
return self.last_measurements.get(param_name, 0)
return on_reset
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.name)
return True
def get_sensor_info(self, extended: bool = False) -> Dict[str, Any]:
ret: Dict[str, Any] = {
"id": self.id,
"friendly_name": self.name,
"type": self.type,
"values": self.last_measurements,
}
if extended:
ret["parameter_info"] = self.param_info
history_fields: List[Dict[str, Any]] = []
for parameter, field_list in self.field_info.items():
for field_data in field_list:
field_config = field_data.get_configuration()
field_config["parameter"] = parameter
history_fields.append(field_config)
ret["history_fields"] = history_fields
return ret
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.name
def close(self) -> None:
pass
class MQTTSensor(BaseSensor):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config=config)
self.mqtt: MQTTClient = self.server.load_component(config, "mqtt")
self.state_topic: str = config.get("state_topic")
self.state_response = config.gettemplate("state_response_template")
self.qos: Optional[int] = config.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
for name, value in measurements.items():
fdata_list = self.field_info.get(name)
if fdata_list is None:
continue
for fdata in fdata_list:
fdata.tracker.update(value)
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.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",
RequestType.GET,
self._handle_sensor_list_request,
)
self.server.register_endpoint(
"/server/sensors/info",
RequestType.GET,
self._handle_sensor_info_request,
)
self.server.register_endpoint(
"/server/sensors/measurements",
RequestType.GET,
self._handle_sensor_measurements_request,
)
# Register notifications
self.server.register_notification(SENSOR_EVENT_NAME)
prefix_sections = config.get_prefix_sections("sensor ")
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(cfg)
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}", exc_info=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]]:
extended = web_request.get_boolean("extended", False)
return {
"sensors": {
key: sensor.get_sensor_info(extended)
for key, sensor in self.sensors.items()
}
}
async def _handle_sensor_info_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
sensor_name: str = web_request.get_str("sensor")
extended = web_request.get_boolean("extended", False)
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(extended)
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:
sensor = self.sensors.get(sensor_name, None)
if sensor is None:
raise self.server.error(f"No valid sensor named {sensor_name}")
return {sensor_name: sensor.get_sensor_measurements()}
else:
return {
key: sensor.get_sensor_measurements()
for key, sensor in self.sensors.items()
}
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)
+440
View File
@@ -0,0 +1,440 @@
# 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,
cast
)
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,
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.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:
transport = cast(asyncio.SubprocessTransport, transport)
self._transport = transport
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(msg)
if cb is not None:
if isinstance(data, str):
data = data.encode()
lines = cast(bytes, 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.,
attempts: 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)
attempts = max(1, attempts)
stdin: Optional[bytes] = None
stdout = stderr = b""
if proc_input is not None:
stdin = proc_input.encode()
while attempts > 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
attempts -= 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, 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 asyncio.CancelledError:
raise
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.eventloop = config.get_server().get_event_loop()
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 run_cmd_async(
self,
cmd: str,
callback: OutputCallback = None,
std_err_callback: OutputCallback = None,
timeout: float = 2.,
attempts: int = 1,
verbose: bool = True,
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[None]:
"""
Runs a command and processes responses as they are received. Optional
callbacks may be provided to handle stdout and stderr.
"""
scmd = ShellCommand(
self, cmd, callback, std_err_callback, env, log_stderr, cwd
)
attempts = max(1, attempts)
async def _wrapper() -> None:
for _ in range(attempts):
if await scmd.run(
timeout, verbose, log_complete, sig_idx,
proc_input, success_codes
):
break
else:
ret_code = scmd.get_return_code()
raise ShellCommandError(f"Error running command {cmd}", ret_code)
return self.eventloop.create_task(_wrapper())
def exec_cmd(
self,
cmd: str,
timeout: float = 2.,
attempts: 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[str]:
"""
Executes a command and returns UTF-8 decoded stdout upon completion.
"""
scmd = ShellCommand(self, cmd, None, None, env,
log_stderr, cwd)
coro = scmd.run_with_response(
timeout, attempts, log_complete, sig_idx,
proc_input, success_codes
)
return self.eventloop.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
+427
View File
@@ -0,0 +1,427 @@
# Integration with Spoolman
#
# Copyright (C) 2023 Daniel Hultgren <daniel.cf.hultgren@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import logging
import re
import contextlib
import tornado.websocket as tornado_ws
from tornado import version_info as tornado_version
from ..common import RequestType, HistoryFieldData
from ..utils import json_wrapper as jsonw
from typing import (
TYPE_CHECKING,
List,
Dict,
Any,
Optional,
Union,
cast
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
from .http_client import HttpClient, HttpResponse
from .database import MoonrakerDatabase
from .announcements import Announcements
from .klippy_apis import KlippyAPI as APIComp
from .history import History
from tornado.websocket import WebSocketClientConnection
DB_NAMESPACE = "moonraker"
ACTIVE_SPOOL_KEY = "spoolman.spool_id"
class SpoolManager:
def __init__(self, config: ConfigHelper):
self.server = config.get_server()
self.eventloop = self.server.get_event_loop()
self._get_spoolman_urls(config)
self.sync_rate_seconds = config.getint("sync_rate", default=5, minval=1)
self.report_timer = self.eventloop.register_timer(self.report_extrusion)
self.pending_reports: Dict[int, float] = {}
self.spoolman_ws: Optional[WebSocketClientConnection] = None
self.connection_task: Optional[asyncio.Task] = None
self.spool_check_task: Optional[asyncio.Task] = None
self.ws_connected: bool = False
self.reconnect_delay: float = 2.
self.is_closing: bool = False
self.spool_id: Optional[int] = None
self._error_logged: bool = False
self._highest_epos: float = 0
self._last_epos: float = 0
self._current_extruder: str = "extruder"
self.spool_history = HistoryFieldData(
"spool_ids", "spoolman", "Spool IDs used", "collect",
reset_callback=self._on_history_reset
)
history: History = self.server.lookup_component("history")
history.register_auxiliary_field(self.spool_history)
self.klippy_apis: APIComp = self.server.lookup_component("klippy_apis")
self.http_client: HttpClient = self.server.lookup_component("http_client")
self.database: MoonrakerDatabase = self.server.lookup_component("database")
announcements: Announcements = self.server.lookup_component("announcements")
announcements.register_feed("spoolman")
self._register_notifications()
self._register_listeners()
self._register_endpoints()
self.server.register_remote_method(
"spoolman_set_active_spool", self.set_active_spool
)
def _get_spoolman_urls(self, config: ConfigHelper) -> None:
orig_url = config.get('server')
url_match = re.match(r"(?i:(?P<scheme>https?)://)?(?P<host>.+)", orig_url)
if url_match is None:
raise config.error(
f"Section [spoolman], Option server: {orig_url}: Invalid URL format"
)
scheme = url_match["scheme"] or "http"
host = url_match["host"].rstrip("/")
ws_scheme = "wss" if scheme == "https" else "ws"
self.spoolman_url = f"{scheme}://{host}/api"
self.ws_url = f"{ws_scheme}://{host}/api/v1/spool"
def _register_notifications(self):
self.server.register_notification("spoolman:active_spool_set")
self.server.register_notification("spoolman:spoolman_status_changed")
def _register_listeners(self):
self.server.register_event_handler(
"server:klippy_ready", self._handle_klippy_ready
)
def _register_endpoints(self):
self.server.register_endpoint(
"/server/spoolman/spool_id",
RequestType.GET | RequestType.POST,
self._handle_spool_id_request,
)
self.server.register_endpoint(
"/server/spoolman/proxy",
RequestType.POST,
self._proxy_spoolman_request,
)
self.server.register_endpoint(
"/server/spoolman/status",
RequestType.GET,
self._handle_status_request,
)
def _on_history_reset(self) -> List[int]:
if self.spool_id is None:
return []
return [self.spool_id]
async def component_init(self) -> None:
self.spool_id = await self.database.get_item(
DB_NAMESPACE, ACTIVE_SPOOL_KEY, None
)
self.connection_task = self.eventloop.create_task(self._connect_websocket())
async def _connect_websocket(self) -> None:
log_connect: bool = True
err_list: List[Exception] = []
while not self.is_closing:
if log_connect:
logging.info(f"Connecting To Spoolman: {self.ws_url}")
log_connect = False
try:
self.spoolman_ws = await tornado_ws.websocket_connect(
self.ws_url,
connect_timeout=5.,
ping_interval=None if tornado_version < (6, 5) else 20.
)
setattr(self.spoolman_ws, "on_ping", self._on_ws_ping)
cur_time = self.eventloop.get_loop_time()
self._last_ping_received = cur_time
except asyncio.CancelledError:
raise
except Exception as e:
if len(err_list) < 10:
# Allow up to 10 unique errors.
for err in err_list:
if type(err) is type(e) and err.args == e.args:
break
else:
err_list.append(e)
verbose = self.server.is_verbose_enabled()
if verbose:
logging.exception("Failed to connect to Spoolman")
self.server.add_log_rollover_item(
"spoolman_connect", f"Failed to Connect to spoolman: {e}",
not verbose
)
else:
err_list = []
self.ws_connected = True
self._error_logged = False
self.report_timer.start()
self.server.add_log_rollover_item(
"spoolman_connect", "Connected to Spoolman Spool Manager"
)
if self.spool_id is not None:
self._cancel_spool_check_task()
coro = self._check_spool_deleted()
self.spool_check_task = self.eventloop.create_task(coro)
self._send_status_notification()
await self._read_messages()
log_connect = True
if not self.is_closing:
await asyncio.sleep(self.reconnect_delay)
async def _read_messages(self) -> None:
message: Union[str, bytes, None]
while self.spoolman_ws is not None:
message = await self.spoolman_ws.read_message()
if isinstance(message, str):
self._decode_message(message)
elif message is None:
self.report_timer.stop()
self.ws_connected = False
cur_time = self.eventloop.get_loop_time()
ping_time: float = cur_time - self._last_ping_received
reason = code = None
if self.spoolman_ws is not None:
reason = self.spoolman_ws.close_reason
code = self.spoolman_ws.close_code
logging.info(
f"Spoolman Disconnected - Code: {code}, Reason: {reason}, "
f"Server Ping Time Elapsed: {ping_time}"
)
self.spoolman_ws = None
if not self.is_closing:
self._send_status_notification()
break
def _decode_message(self, message: str) -> None:
event: Dict[str, Any] = jsonw.loads(message)
if event.get("resource") != "spool":
return
if self.spool_id is not None and event.get("type") == "deleted":
payload: Dict[str, Any] = event.get("payload", {})
if payload.get("id") == self.spool_id:
self.pending_reports.pop(self.spool_id, None)
self.set_active_spool(None)
def _cancel_spool_check_task(self) -> None:
if self.spool_check_task is None or self.spool_check_task.done():
return
self.spool_check_task.cancel()
async def _check_spool_deleted(self) -> None:
if self.spool_id is not None:
response = await self.http_client.get(
f"{self.spoolman_url}/v1/spool/{self.spool_id}",
connect_timeout=1., request_timeout=2.
)
if response.status_code == 404:
logging.info(f"Spool ID {self.spool_id} not found, setting to None")
self.pending_reports.pop(self.spool_id, None)
self.set_active_spool(None)
elif response.has_error():
err_msg = self._get_response_error(response)
logging.info(f"Attempt to check spool status failed: {err_msg}")
else:
logging.info(f"Found Spool ID {self.spool_id} on spoolman instance")
self.spool_check_task = None
def connected(self) -> bool:
return self.ws_connected
def _on_ws_ping(self, data: bytes = b"") -> None:
self._last_ping_received = self.eventloop.get_loop_time()
async def _handle_klippy_ready(self) -> None:
result: Dict[str, Dict[str, Any]]
result = await self.klippy_apis.subscribe_objects(
{"toolhead": ["position", "extruder"]}, self._handle_status_update, {}
)
toolhead = result.get("toolhead", {})
self._current_extruder = toolhead.get("extruder", "extruder")
initial_e_pos = toolhead.get("position", [None]*4)[3]
logging.debug(f"Initial epos: {initial_e_pos}")
if initial_e_pos is not None:
self._highest_epos = initial_e_pos
else:
logging.error("Spoolman integration unable to subscribe to epos")
raise self.server.error("Unable to subscribe to e position")
def _get_response_error(self, response: HttpResponse) -> str:
err_msg = f"HTTP error: {response.status_code} {response.error}"
with contextlib.suppress(Exception):
msg: Optional[str] = cast(dict, response.json())["message"]
err_msg += f", Spoolman message: {msg}"
return err_msg
def _handle_status_update(self, status: Dict[str, Any], _: float) -> None:
toolhead: Optional[Dict[str, Any]] = status.get("toolhead")
if toolhead is None:
return
epos: float = toolhead.get("position", [0, 0, 0, self._highest_epos])[3]
self._last_epos = epos
extr = toolhead.get("extruder", self._current_extruder)
if extr != self._current_extruder:
self._highest_epos = epos
self._current_extruder = extr
elif epos > self._highest_epos:
if self.spool_id is not None:
self._add_extrusion(self.spool_id, epos - self._highest_epos)
self._highest_epos = epos
def _add_extrusion(self, spool_id: int, used_length: float) -> None:
if spool_id in self.pending_reports:
self.pending_reports[spool_id] += used_length
else:
self.pending_reports[spool_id] = used_length
def set_active_spool(self, spool_id: Union[int, None]) -> None:
assert spool_id is None or isinstance(spool_id, int)
if self.spool_id == spool_id:
logging.info(f"Spool ID already set to: {spool_id}")
return
self.spool_history.tracker.update(spool_id)
self.spool_id = spool_id
self.database.insert_item(DB_NAMESPACE, ACTIVE_SPOOL_KEY, spool_id)
self._highest_epos = self._last_epos
self.server.send_event(
"spoolman:active_spool_set", {"spool_id": spool_id}
)
logging.info(f"Setting active spool to: {spool_id}")
async def report_extrusion(self, eventtime: float) -> float:
if not self.ws_connected:
return eventtime + self.sync_rate_seconds
pending_reports = self.pending_reports
self.pending_reports = {}
for spool_id, used_length in pending_reports.items():
if not self.ws_connected:
self._add_extrusion(spool_id, used_length)
continue
logging.debug(
f"Sending spool usage: ID: {spool_id}, Length: {used_length:.3f}mm"
)
response = await self.http_client.request(
method="PUT",
url=f"{self.spoolman_url}/v1/spool/{spool_id}/use",
body={"use_length": used_length}
)
if response.has_error():
if response.status_code == 404:
# Since the spool is deleted we can remove any pending reports
# added while waiting for the request
self.pending_reports.pop(spool_id, None)
if spool_id == self.spool_id:
logging.info(f"Spool ID {spool_id} not found, setting to None")
self.set_active_spool(None)
else:
if not self._error_logged:
error_msg = self._get_response_error(response)
self._error_logged = True
logging.info(
f"Failed to update extrusion for spool id {spool_id}, "
f"received {error_msg}"
)
# Add missed reports back to pending reports for the next cycle
self._add_extrusion(spool_id, used_length)
continue
self._error_logged = False
return self.eventloop.get_loop_time() + self.sync_rate_seconds
async def _handle_spool_id_request(self, web_request: WebRequest):
if web_request.get_request_type() == RequestType.POST:
spool_id = web_request.get_int("spool_id", None)
self.set_active_spool(spool_id)
# For GET requests we will simply return the spool_id
return {"spool_id": self.spool_id}
async def _proxy_spoolman_request(self, web_request: WebRequest):
method = web_request.get_str("request_method")
path = web_request.get_str("path")
query = web_request.get_str("query", None)
body = web_request.get("body", None)
use_v2_response = web_request.get_boolean("use_v2_response", False)
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:
raise self.server.error(f"Invalid HTTP method: {method}")
if body is not None and method == "GET":
raise self.server.error("GET requests cannot have a body")
if len(path) < 4 or path[:4] != "/v1/":
raise self.server.error(
"Invalid path, must start with the API version, e.g. /v1"
)
query = f"?{query}" if query is not None else ""
full_url = f"{self.spoolman_url}{path}{query}"
if not self.ws_connected:
if not use_v2_response:
raise self.server.error("Spoolman server not available", 503)
return {
"response": None,
"error": {
"status_code": 503,
"message": "Spoolman server not available"
}
}
logging.debug(f"Proxying {method} request to {full_url}")
response = await self.http_client.request(
method=method,
url=full_url,
body=body,
)
if not use_v2_response:
response.raise_for_status()
return response.json()
if response.has_error():
msg: str = str(response.error or "")
with contextlib.suppress(Exception):
spoolman_msg = cast(dict, response.json()).get("message", msg)
msg = spoolman_msg
return {
"response": None,
"error": {
"status_code": response.status_code,
"message": msg
}
}
else:
return {
"response": response.json(),
"response_headers": dict(response.headers.items()),
"error": None
}
async def _handle_status_request(self, web_request: WebRequest) -> Dict[str, Any]:
pending: List[Dict[str, Any]] = [
{"spool_id": sid, "filament_used": used} for sid, used in
self.pending_reports.items()
]
return {
"spoolman_connected": self.ws_connected,
"pending_reports": pending,
"spool_id": self.spool_id
}
def _send_status_notification(self) -> None:
self.server.send_event(
"spoolman:spoolman_status_changed",
{"spoolman_connected": self.ws_connected}
)
async def close(self):
self.is_closing = True
self.report_timer.stop()
if self.spoolman_ws is not None:
self.spoolman_ws.close(1001, "Moonraker Shutdown")
self._cancel_spool_check_task()
if self.connection_task is None or self.connection_task.done():
return
try:
await asyncio.wait_for(self.connection_task, 2.)
except asyncio.TimeoutError:
pass
def load_component(config: ConfigHelper) -> SpoolManager:
return SpoolManager(config)
+309
View File
@@ -0,0 +1,309 @@
# Support for interfacing with TD-1 devices to assist in filament changers grabbing TD
# and color for all filament loaded.
#
# Copyright (C) 2025 AJAX3D and Jim Madill <jcmadill1@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import serial
import serial.tools.list_ports
import logging
import datetime
import contextlib
from ..utils import async_serial
from ..common import RequestType
from typing import Optional, Dict, List, Tuple, Any, TYPE_CHECKING
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..common import WebRequest
class TD1Connection:
def __init__(
self,
config: ConfigHelper,
serial_number: str,
port: str,
logger: logging.Logger
) -> None:
self.config = config
self.server = config.get_server()
self.port = port
self.serial_number = serial_number
self.baudrate = config.getint("baudrate", 115200)
self.name = f"{config.get_name()}-{self.serial_number}"
self.logger = logger
self.error_state: bool = False
self.enabled: bool = True
self.serial = async_serial.AsyncSerialConnection(
self.server, self.name, self.port, self.baudrate
)
self.serial_task: asyncio.Task
# Values to return back for td1_data endpoint
self._td: Optional[float] = None
self._color: Optional[str] = None
self._scan_time: str = datetime.datetime.now(
tz=datetime.timezone.utc
).isoformat() + "Z"
self._error: Optional[str] = None
self.done_initializing: bool = False
async def initialize(self) -> None:
self.serial_task = self.server.get_event_loop().create_task(self.run_serial())
for _ in range(5):
await asyncio.sleep(.01)
if self.serial.connected:
break
async def readline_with_timeout(self, timeout: float = 5.) -> Optional[bytes]:
with contextlib.suppress(asyncio.TimeoutError):
return await asyncio.wait_for(self.serial.reader.readline(), timeout)
return None
async def run_serial(self) -> None:
try:
self.serial.open()
except (self.serial.error, OSError):
self.error_state = True
self.logger.exception(
f"Error trying to open TD1 serial: {self.serial_number}"
)
return
await self.check_error_file()
self.done_initializing = True
async for read_line in self.serial.reader:
line = read_line.decode("utf-8").rstrip()
self._parse_line(line)
self.logger.debug(f"{self.serial_number}: {line}")
def _parse_line(self, line: str) -> None:
try:
parts = line.split(",")
if len(parts) >= 6:
self._td = float(parts[4])
self._color = parts[5].strip()
self._scan_time = datetime.datetime.now(
tz=datetime.timezone.utc
).isoformat() + "Z"
except Exception as e:
self.logger.error(f"Parse error from {self.serial_number}: {e}")
async def check_error_file(self) -> None:
"""
Requests error file from TD1
:return: Returns empty string if no error.txt file exists, returns error.txt
content if it exists so error can be displayed to user.
"""
file_name = "errors.txt"
# Wait for acknowledgment from the Raspberry Pi Pico
ack = None
while ack != 'ready' and ack != 'No file named errors.txt' and self.enabled:
# Send the file request command
if ack is None:
self.logger.debug(f"{self.serial_number}: Sending retrieve file")
await self.serial.send(b'retrieve file\n')
await self.serial.send(f"{file_name}\n".encode('utf-8'))
line = await self.readline_with_timeout()
if line is not None:
ack = line.decode('utf-8').strip()
self.logger.debug(f"{self.serial_number}: {ack}")
else:
self.logger.debug(f"{self.serial_number}: Timed out")
ack = None
self.logger.debug(f"{self.serial_number}: Done checking for error file")
if ack == 'No file named errors.txt':
return
# Receive file size and block count
data = await self.serial.reader.readline()
file_size = int(data.decode('utf-8').strip())
data = await self.serial.reader.readline()
blk_count = int(data.decode('utf-8').strip())
self.logger.debug(
f"Receiving file: {file_name}, Size: {file_size} bytes, Blocks: {blk_count}"
)
block_content = ''
for _ in range(blk_count):
# Receive a block size
data = await self.serial.reader.readuntil(b'\n')
# Receive the block content
data = await self.serial.reader.readuntil(b'\n')
block_content += data.decode()
# Send acknowledgment to the Raspberry Pi Pico
await self.serial.send(b'ready\n')
self.logger.info(
f"{self.serial_number}: Error file content: {block_content}"
)
self.logger.info(
f"{self.serial_number}: File '{file_name}' received successfully."
)
self._error = block_content
async def close(self) -> None:
self.enabled = False
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.serial.close(), 1)
if hasattr(self, "serial_task") and not self.serial_task.done():
with contextlib.suppress(asyncio.CancelledError, asyncio.TimeoutError):
await asyncio.wait_for(self.serial_task, 1)
async def reboot(self) -> None:
self.logger.info(f"Rebooting {self.serial_number}")
self.enabled = False
self.serial.set_read_callback(None, force=True)
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.serial_task, 1.)
await self.serial.send('change settings\n'.encode('utf-8'))
ack = await self.serial.reader.readuntil(b'\n')
ack_str = ack.decode('utf-8').strip()
if ack_str == 'ready':
await self.serial.send(b'RGB_Enabled = True\ndone\n')
ack = await self.serial.reader.readuntil(b'\n')
ack_str = ack.decode('utf-8').strip()
def get_data(self) -> Dict[str, Dict[str, Any]]:
if not self.done_initializing:
# Return empty dictionary until check_error_file has compeleted
return {}
return {
self.serial_number: {
"td": self._td,
"color": self._color,
"scan_time": self._scan_time,
"error": self._error
}
}
class TD1:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self._config = config
self._loop = self.server.get_event_loop()
self.logger = logging.getLogger("td1")
self._server = config.get_server()
self._vid: int = 0xE4B2
self._pid: int = 0x0045
self._enabled: bool = True
self._watch_task: Optional[asyncio.Task] = None
self._start_task: Optional[asyncio.Task] = None
self.td1_conns: Dict[str, TD1Connection] = {}
self._register_endpoints()
def _register_endpoints(self) -> None:
self._server.register_endpoint(
"/machine/td1/data", RequestType.GET, self._handle_get_data
)
self._server.register_endpoint(
"/machine/td1/reboot", RequestType.POST, self._handle_reboot
)
async def close(self) -> None:
# Stop watching for new devices
self._enabled = False
if self._start_task is not None:
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(self._start_task, 1.)
if self._watch_task is not None:
self._watch_task.cancel()
with contextlib.suppress(asyncio.TimeoutError, asyncio.CancelledError):
await asyncio.wait_for(self._watch_task, 1.)
for td1 in self.td1_conns.values():
await td1.close()
async def component_init(self) -> None:
self.logger.debug("Initializing TD1")
self._start_task = self._loop.create_task(self._start_all_serial_tasks())
self._watch_task = self._loop.create_task(self._watch_for_new_devices())
async def _start_all_serial_tasks(self) -> None:
devices = self._find_td1_devices()
if not devices:
self.logger.warning("No TD1 devices found.")
return
for port, serial_number in devices:
await self._start_serial_task(port, serial_number)
await asyncio.sleep(0.5)
async def _watch_for_new_devices(self) -> None:
while self._enabled:
await asyncio.sleep(5.) # Scan every 5 seconds
# Find currently connected devices
current_serials: set[str] = set()
for port, serial_number in self._find_td1_devices():
current_serials.add(serial_number)
if serial_number not in self.td1_conns:
self.logger.info(f"Hot-plugged TD1 detected: {serial_number}")
try:
await self._start_serial_task(port, serial_number)
except asyncio.CancelledError:
raise
except Exception:
continue
# Detect disconnected devices
known_serials = set(self.td1_conns.keys())
disconnected_serials = known_serials - current_serials
self.logger.debug(
f"Disconnected: {disconnected_serials}, All: {known_serials}"
)
for serial_number in disconnected_serials:
conn = self.td1_conns.pop(serial_number, None)
if conn is not None:
await conn.close()
def _find_td1_devices(self) -> List[Tuple[str, str]]:
found: List[Tuple[str, str]] = []
for port in serial.tools.list_ports.comports():
if port.vid == self._vid and port.pid == self._pid:
if port.serial_number:
found.append((port.device, port.serial_number))
return found
async def _start_serial_task(self, port: str, serial_number: str) -> None:
try:
conn = TD1Connection(self._config, serial_number, port, self.logger)
await conn.initialize()
if not conn.error_state:
self.td1_conns[serial_number] = conn
self.logger.info(f"TD1 listening on {port} (Serial: {serial_number})")
else:
self.logger.error(
f"Failed to open port:{port} for TD1 serial {serial_number}")
except serial.SerialException as e:
self.logger.error(f"Failed to open serial port {port}: {e}")
raise
except asyncio.CancelledError as e:
self.logger.error(f"Task canceled error {e}")
raise
async def _handle_get_data(self, web_request: WebRequest) -> Dict[str, Any]:
latest_data: Dict[str, Any] = {}
for task in self.td1_conns.values():
latest_data.update(task.get_data())
return {
"status": "ok",
"devices": latest_data
}
async def _handle_reboot(self, web_request: WebRequest) -> Dict[str, str]:
"""
Reboots TD1 device by serial when requested
"""
serial_number = web_request.get_str("serial")
req_conn = self.td1_conns.get(serial_number, None)
if req_conn is None:
return {
"status": "serial_error"
}
await req_conn.reboot()
await req_conn.close()
# Remove serial number from entries if they exist
self.td1_conns.pop(serial_number, None)
return {
"status": "ok"
}
def load_component(config: ConfigHelper) -> TD1:
return TD1(config)
+113
View File
@@ -0,0 +1,113 @@
# 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
from ..utils import json_wrapper as jsonw
from ..common import RenderableTemplate
# 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'] = jsonw.loads
self.async_env.add_extension("jinja2.ext.do")
self.async_env.filters['fromjson'] = jsonw.loads
self.ui_env.add_extension("jinja2.ext.do")
self.ui_env.filters['fromjson'] = jsonw.loads
self.add_environment_global("raise_error", self._raise_error)
self.add_environment_global("secrets", secrets)
self.add_environment_global("log_debug", logging.debug)
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(RenderableTemplate):
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,470 @@
# 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 hashlib
import logging
import re
import asyncio
import importlib
from datetime import datetime, timezone
from .common import AppType, Channel
from .base_deploy import BaseDeploy
from ...utils import pip_utils
from ...utils import json_wrapper as jsonw
from ...utils.sysdeps_parser import SysDepsParser
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
Dict,
List
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ..klippy_connection import KlippyConnection as Klippy
from ..machine import Machine
from ..file_manager.file_manager import FileManager
PIPVER_CHECK_DAYS = 30
class AppDeploy(BaseDeploy):
def __init__(self, config: ConfigHelper, prefix: str) -> None:
super().__init__(config, prefix=prefix)
self.config = config
type_choices = {str(t): t for t in AppType.valid_types()}
self.type = config.getchoice("type", type_choices)
channel_choices = {str(chnl): chnl for chnl in list(Channel)}
self.channel = config.getchoice(
"channel", channel_choices, str(self.type.default_channel)
)
self.channel_invalid: bool = False
if self.channel not in self.type.supported_channels:
str_channels = [str(c) for c in self.type.supported_channels]
self.channel_invalid = True
invalid_channel = self.channel
self.channel = self.type.default_channel
self.server.add_warning(
f"[{config.get_name()}]: Invalid value '{invalid_channel}' for "
f"option 'channel'. Type '{self.type}' supports the following "
f"channels: {str_channels}. Falling back to channel '{self.channel}'"
)
self.report_anomalies = config.getboolean("report_anomalies", True)
self._is_valid: bool = False
self.virtualenv: Optional[pathlib.Path] = None
self.py_exec: Optional[pathlib.Path] = None
self.pip_cmd: Optional[str] = None
self.pip_version_info: pip_utils.PipVersionInfo | None = None
self.pip_ver_date: datetime = datetime.fromtimestamp(0., timezone.utc)
self.venv_args: Optional[str] = None
self.npm_pkg_json: Optional[pathlib.Path] = None
self.python_reqs: Optional[pathlib.Path] = None
self.install_script: Optional[pathlib.Path] = None
self.system_deps_json: Optional[pathlib.Path] = None
self.info_tags: List[str] = config.getlist("info_tags", [])
self.managed_services: List[str] = []
def _configure_path(self, config: ConfigHelper, reserve: bool = True) -> None:
self.path = pathlib.Path(config.get('path')).expanduser().resolve()
self._verify_path(config, 'path', self.path, check_file=False)
if (
reserve and 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)
def _configure_virtualenv(self, config: ConfigHelper) -> None:
venv_path: Optional[pathlib.Path] = None
if config.has_option("virtualenv"):
venv_path = pathlib.Path(config.get("virtualenv")).expanduser()
if not venv_path.is_absolute():
venv_path = self.path.joinpath(venv_path)
self._verify_path(config, 'virtualenv', venv_path, check_file=False)
elif config.has_option("env"):
# Deprecated
if self.name != "klipper":
self.log_info("Option 'env' is deprecated, use 'virtualenv' instead.")
py_exec = pathlib.Path(config.get("env")).expanduser()
self._verify_path(config, 'env', py_exec, check_exe=True)
venv_path = py_exec.expanduser().parent.parent.resolve()
if venv_path is not None:
act_path = venv_path.joinpath("bin/activate")
if not act_path.is_file():
raise config.error(
f"[{config.get_name()}]: Invalid virtualenv at path {venv_path}. "
f"Verify that the 'virtualenv' option is set to a valid "
"virtualenv path."
)
self.py_exec = venv_path.joinpath("bin/python")
if not (self.py_exec.is_file() and os.access(self.py_exec, os.X_OK)):
raise config.error(
f"[{config.get_name()}]: Invalid python executable at "
f"{self.py_exec}. Verify that the 'virtualenv' option is set "
"to a valid virtualenv path."
)
self.log_info(f"Detected virtualenv: {venv_path}")
self.virtualenv = venv_path
pip_exe = self.virtualenv.joinpath("bin/pip")
if pip_exe.is_file():
self.pip_cmd = f"{self.py_exec} -m pip"
else:
self.log_info("Unable to locate pip executable")
self.venv_args = config.get('venv_args', None)
self.pip_env_vars = config.getdict("pip_environment_variables", None)
def _configure_dependencies(
self, config: ConfigHelper, node_only: bool = False
) -> 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)
if node_only:
return
if self.py_exec is not None:
self.python_reqs = self.path.joinpath(config.get("requirements"))
self._verify_path(config, 'requirements', self.python_reqs)
if not self._configure_sysdeps(config):
# Fall back on deprecated "install_script" option if dependencies file
# not present
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)
def _configure_sysdeps(self, config: ConfigHelper) -> bool:
deps = config.get("system_dependencies", None)
if deps is not None:
self.system_deps_json = self.path.joinpath(deps).resolve()
self._verify_path(config, 'system_dependencies', self.system_deps_json)
return True
return False
def _configure_managed_services(self, config: ConfigHelper) -> None:
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
)
if self.name in services:
machine: Machine = self.server.lookup_component("machine")
data_path: str = self.server.get_app_args()["data_path"]
asvc = pathlib.Path(data_path).joinpath("moonraker.asvc")
if not machine.is_service_allowed(self.name):
self.server.add_warning(
f"[{config.get_name()}]: Moonraker is not permitted to "
f"restart service '{self.name}'. To enable management "
f"of this service add {self.name} to the bottom of the "
f"file {asvc}. To disable management for this service "
"set 'is_system_service: False' in the configuration "
"for this section."
)
services.clear()
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)
self.log_debug(
f"Managed services: {self.managed_services}"
)
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")
async def initialize(self) -> Dict[str, Any]:
storage = await super().initialize()
pv_info: List[Any] | None = storage.get("pip_version_info", None)
if pv_info is not None:
self.pip_version_info = pip_utils.PipVersionInfo(*pv_info[:2])
self.pip_ver_date = datetime.fromtimestamp(pv_info[2], timezone.utc)
self.log_info(
f"Pip Version: {pv_info[0]}, Python Version: {pv_info[1]}\n"
f"Last checked on {self.pip_ver_date}"
)
return storage
def get_configured_type(self) -> AppType:
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.py_exec is None:
return False
try:
return (
self.path.samefile(app_path) and
self.py_exec.samefile(executable)
)
except Exception:
return False
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
raise NotImplementedError
async def restart_service(self) -> None:
if not self.managed_services:
return
machine: Machine = self.server.lookup_component("machine")
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
machine.restart_moonraker_service()
else:
if svc == "klipper":
kconn: Klippy = self.server.lookup_component("klippy_connection")
svc = kconn.unit_name
await machine.do_service_action("restart", svc)
async def _read_system_dependencies(self) -> List[str]:
eventloop = self.server.get_event_loop()
if self.system_deps_json is not None:
deps_json = self.system_deps_json
try:
ret = await eventloop.run_in_thread(deps_json.read_bytes)
dep_info: Dict[str, List[str]] = jsonw.loads(ret)
except asyncio.CancelledError:
raise
except Exception:
logging.exception(f"Error reading system deps: {deps_json}")
return []
parser = SysDepsParser()
return parser.parse_dependencies(dep_info)
# Fall back on install script if configured
if self.install_script is None:
return []
# Open install file file and read
inst_path: pathlib.Path = self.install_script
if not inst_path.is_file():
self.log_info(f"Failed to open install script: {inst_path}")
return []
try:
data = await eventloop.run_in_thread(inst_path.read_text)
except asyncio.CancelledError:
raise
except Exception:
logging.exception(f"Error reading install script: {inst_path}")
return []
plines: List[str] = re.findall(r'PKGLIST="(.*)"', data)
plines = [p.lstrip("${PKGLIST}").strip() for p in plines]
packages: List[str] = []
for line in plines:
packages.extend(line.split())
if not packages:
self.log_info(f"No packages found in script: {inst_path}")
return packages
async def _read_python_reqs(self) -> List[str]:
if self.python_reqs is None:
return []
pyreqs = self.python_reqs
if not pyreqs.is_file():
self.log_info(f"Failed to open python requirements file: {pyreqs}")
return []
eventloop = self.server.get_event_loop()
return await eventloop.run_in_thread(
pip_utils.read_requirements_file, self.python_reqs
)
def get_update_status(self) -> Dict[str, Any]:
return {
'channel': str(self.channel),
'debug_enabled': self.server.is_debug_enabled(),
'channel_invalid': self.channel_invalid,
'is_valid': self._is_valid,
'configured_type': str(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
pv_info = None
if self.pip_version_info is not None:
pv_info = [
self.pip_version_info.pip_version_string,
self.pip_version_info.python_version_string,
self.pip_ver_date.timestamp()
]
storage['pip_version_info'] = pv_info
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
if self.name == "moonraker":
importlib.reload(pip_utils)
pip_exec = pip_utils.AsyncPipExecutor(
self.pip_cmd, self.server, self.cmd_helper.notify_update_response
)
# Check and update the pip version
await self._update_pip(pip_exec)
self.notify_status("Updating python packages...")
try:
await pip_exec.install_packages(requirements, self.pip_env_vars)
except asyncio.CancelledError:
raise
except Exception:
self.log_exc("Error updating python requirements")
async def _update_pip(self, pip_exec: pip_utils.AsyncPipExecutor) -> None:
self.notify_status("Checking pip version...")
check_time = datetime.now(timezone.utc) - self.pip_ver_date
if self.pip_version_info is None or check_time.days > PIPVER_CHECK_DAYS:
self.pip_version_info = await pip_exec.get_pip_version()
self.pip_ver_date = datetime.now(timezone.utc)
try:
if self.pip_version_info.needs_pip_update:
cur_ver = self.pip_version_info.pip_version_string
update_ver = self.pip_version_info.max_pip_version_string
self.notify_status(
f"Updating pip from version {cur_ver} to {update_ver}..."
)
await pip_exec.update_pip()
self.pip_version_info = await pip_exec.get_pip_version()
self.pip_ver_date = datetime.now(timezone.utc)
else:
self.notify_status("Pip version up to date")
except asyncio.CancelledError:
raise
except Exception as e:
self.notify_status(f"Pip Version Check Error: {e}")
self.log_exc("Pip Version Check Error")
async def _collect_dependency_info(self) -> Dict[str, Any]:
pkg_deps = await self._read_system_dependencies()
pyreqs = await self._read_python_reqs()
npm_hash = await self._get_file_hash(self.npm_pkg_json)
logging.debug(
f"\nApplication {self.name}: Pre-update dependencies:\n"
f"Packages: {pkg_deps}\n"
f"Python Requirements: {pyreqs}"
)
return {
"system_packages": pkg_deps,
"python_modules": pyreqs,
"npm_hash": npm_hash
}
async def _update_dependencies(
self, dep_info: Dict[str, Any], force: bool = False
) -> None:
packages = await self._read_system_dependencies()
modules = await self._read_python_reqs()
logging.debug(
f"\nApplication {self.name}: Post-update dependencies:\n"
f"Packages: {packages}\n"
f"Python Requirements: {modules}"
)
if not force:
packages = list(set(packages) - set(dep_info["system_packages"]))
modules = list(set(modules) - set(dep_info["python_modules"]))
logging.debug(
f"\nApplication {self.name}: Dependencies to install:\n"
f"Packages: {packages}\n"
f"Python Requirements: {modules}\n"
f"Force All: {force}"
)
if packages:
await self._install_packages(packages)
if modules:
await self._update_python_requirements(self.python_reqs or modules)
npm_hash: Optional[str] = dep_info["npm_hash"]
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")
@@ -0,0 +1,119 @@
# 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 ...utils import pretty_print_time
from typing import TYPE_CHECKING, Dict, Any, Optional, Coroutine
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ...utils import ServerError
from .update_manager import CommandHelper
class BaseDeploy:
cmd_helper: CommandHelper
def __init__(
self,
config: ConfigHelper,
name: Optional[str] = None,
prefix: str = "",
cfg_hash: Optional[str] = None
) -> None:
if name is None:
name = self.parse_name(config)
self.name = name
if prefix:
prefix = f"{prefix} {self.name}: "
self.prefix = prefix
self.server = config.get_server()
self.refresh_interval = self.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
@staticmethod
def parse_name(config: ConfigHelper) -> str:
name = config.get_name().split(maxsplit=1)[-1]
if name.startswith("client "):
# allow deprecated [update_manager client app] style names
name = name[7:]
return name
@staticmethod
def set_command_helper(cmd_helper: CommandHelper) -> None:
BaseDeploy.cmd_helper = cmd_helper
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, log_remaining_time: bool = False) -> bool:
next_refresh_time = self.last_refresh_time + self.refresh_interval
remaining_time = int(next_refresh_time - time.time() + .5)
if self.cfg_hash != self.last_cfg_hash or remaining_time <= 0:
return True
if log_remaining_time:
self.log_info(f"Next refresh in: {pretty_print_time(remaining_time)}")
return False
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
async def rollback(self) -> bool:
raise self.server.error(f"Rollback not available for {self.name}")
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 log_debug(self, msg: str) -> None:
log_msg = f"{self.prefix}{msg}"
logging.debug(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)
def close(self) -> Optional[Coroutine]:
return None
@@ -0,0 +1,113 @@
# 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 sys
import copy
import pathlib
from ...common import ExtendedEnum
from ...utils import source_info
from typing import (
TYPE_CHECKING,
Dict,
Union,
List
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ..klippy_connection import KlippyConnection
BASE_CONFIG: Dict[str, Dict[str, str]] = {
"moonraker": {
"origin": "https://github.com/arksine/moonraker.git",
"requirements": "scripts/moonraker-requirements.txt",
"venv_args": "-p python3",
"system_dependencies": "scripts/system-dependencies.json",
"virtualenv": sys.exec_prefix,
"pip_environment_variables": "SKIP_CYTHON=Y",
"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 python3",
"install_script": "scripts/install-octopi.sh",
"managed_services": "klipper"
}
}
OPTION_OVERRIDES = ("channel", "pinned_commit", "refresh_interval", "report_anomalies")
class AppType(ExtendedEnum):
NONE = 1
WEB = 2
GIT_REPO = 3
ZIP = 4
PYTHON = 5
EXECUTABLE = 6
@classmethod
def detect(cls, app_path: Union[str, pathlib.Path, None] = None):
# If app path is None, detect Moonraker
if isinstance(app_path, str):
app_path = pathlib.Path(app_path).expanduser()
if source_info.is_git_repo(app_path):
return AppType.GIT_REPO
elif app_path is None and source_info.is_vitualenv_project():
return AppType.PYTHON
else:
return AppType.NONE
@classmethod
def valid_types(cls) -> List[AppType]:
all_types = list(cls)
all_types.remove(AppType.NONE)
return all_types
@property
def supported_channels(self) -> List[Channel]:
if self == AppType.NONE:
return []
elif self in [AppType.WEB, AppType.ZIP, AppType.EXECUTABLE]:
return [Channel.STABLE, Channel.BETA] # type: ignore
else:
return list(Channel)
@property
def default_channel(self) -> Channel:
if self == AppType.GIT_REPO:
return Channel.DEV # type: ignore
return Channel.STABLE # type: ignore
class Channel(ExtendedEnum):
STABLE = 1
BETA = 2
DEV = 3
def get_base_configuration(config: ConfigHelper) -> ConfigHelper:
server = config.get_server()
base_cfg = copy.deepcopy(BASE_CONFIG)
kconn: KlippyConnection = server.lookup_component("klippy_connection")
base_cfg["moonraker"]["type"] = str(AppType.detect())
base_cfg["klipper"]["path"] = str(kconn.path)
base_cfg["klipper"]["env"] = str(kconn.executable)
base_cfg["klipper"]["type"] = str(AppType.detect(kconn.path))
default_channel = config.get("channel", None)
# Check for configuration overrides
for app_name in base_cfg.keys():
if default_channel is not None:
base_cfg[app_name]["channel"] = default_channel
override_section = f"update_manager {app_name}"
if not config.has_section(override_section):
continue
app_cfg = config[override_section]
for opt in OPTION_OVERRIDES:
if app_cfg.has_option(opt):
base_cfg[app_name][opt] = app_cfg.get(opt)
return config.read_supplemental_dict(base_cfg)
File diff suppressed because it is too large. Load diff
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff. Show more