57 Commits
Author SHA1 Message Date
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
18 changed files with 801 additions and 244 deletions

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
# 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 [Klipper](https://github.com/KevinOConnor/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
@@ -21,4 +21,4 @@ Users:\
[user_changes.md](/docs/user_changes.md) - December 31st 2020
Developers:\
[api_changes.md](/docs/api_changes.md) - January 1st 2021
[api_changes.md](/docs/api_changes.md) - January 31st 2021
+34
View File
@@ -1,4 +1,38 @@
This document keeps a record of all changes to Moonraker's web APIs.
### January 31st 2021
- The `GET /server/temperature_store` endpoint now only returns fields
that each sensor reports. For example, if a particuarly temperature
sensor does not report "target" or "power", then the corresponding
fields will not be reported for that sensor in response to the
`temperature_store` request.
### January 22nd 2021
- The `POST /machine/update/client` endpoint now requires a `name`
argument. This change added multiple client support
- The response to `GET /machine/update/status` no longer returns a
`client` field. Instead it will add fields matching the `name` of
each configured client. Keep in mind that the client object could
have a different set of fields depending on the type of a client. The
easy way to check for this is to see if a `branch` field is present.
If so, this client is a `git repo`. Otherwise it is a `web` client.
### January 4th 2021
- A `notify_update_refreshed` notification has been added. Moonraker now
auto-refreshes the update status at roughly a 2 hour interval. When
an auto-refresh is complete this notification is broadcast. Included
is an object that matches the response from `/machine/update/status`.
- The behavior of some of the `update_manager` APIs has changed:
- The `refresh` argument for `/machine/update/status` is now more
of a suggestion than a rule. If an update or a print is in
progress then the request will ignore the refresh argument
and immediately return the current status. Generally speaking requesting
a refresh should not be necessary with addition of auto refresh.
- The update requests (ie `/machine/update/klipper`) will now return
an error if a print is in progress. If the requested update is in
progress then the request will return valid with a message stating
that the update is in progress. If another object is being updated
then the request will be queued and block until it its complete.
### January 1st 2021
- A `notify_klippy_shutdown` websocket notification has been added
+78 -9
View File
@@ -147,6 +147,21 @@ and Tasmota (via http) devices are supported.
type: gpio
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
# This parameter must be provided.
off_when_shutdown: False
# If set to True the device will be powered off when Klipper enters
# the "shutdown" state. This option applies to all device types.
# The default is False.
locked_while_printing: False
# If True, locks the device so that the power cannot be changed while the
# printer is printing. This is useful to avert an accidental shutdown to
# the printer's power. The default is False.
restart_klipper_when_powered: False
# If set to True, Moonraker will issue a "FIRMWARE_RESTART" to Klipper
# after the device has been powered on. The default is False, thus no
# attempt to made to restart Klipper after power on.
restart_delay: 1.
# If "restart_klipper_when_powered" is set, this option specifies the amount
# of time (in seconds) to delay the restart. Default is 1 second.
pin: gpiochip0/gpio26
# The pin to use for GPIO devices. The chip is optional, if left out
# then the module will default to gpiochip0. If one wishes to invert
@@ -186,6 +201,7 @@ Below are some potential examples:
[power printer]
type: gpio
pin: gpio26
off_when_shutdown: True
initial_state: off
[power printer_led]
@@ -254,18 +270,71 @@ enable_repo_debug: False
# detached repos are also allowed. This option is intended for
# developers and should not be used on production machines. The
# default is False.
enable_auto_refresh: False
# When set to True Moonraker will attempt to fetch status about
# available updates roughly every 24 hours, between 12am-4am.
# When set to False Moonraker will only fetch update state on startup
# and clients will need to request that Moonraker updates state. The
# default is False.
distro: debian
# The disto in which moonraker has been installed. Currently the
# update manager only supports "debian", which encompasses all of
# its derivatives. The default is debain.
client_repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
# meteyou/mainsail to update Mainsail. If this option is not set then
# the update manager will not attempt to update a client.
client_path:
# The path to the client's files on disk. This cannot be a symbolic link,
# it must be the real directory in which the client's files are located.
# If `client_repo` is set, this parameter must be provided
```
### Client Configuration
This allows client programs such as Fluidd, KlipperScreen, and Mainsail to be
updated in addition to klipper, moonraker, and the system os. Repos that have
been modified or cloned from unofficial sources are not supported.
There are two types of update manager clients and each will be detailed
separately. The first one is targeted towards releases that do not need a
service restart such as Fluidd/Mainsail.
```
# moonraker.conf
[update_manager client client_name]
type: web
repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
# meteyou/mainsail to update Mainsail. This parameter must be provided.
path:
# The path to the client's files on disk. This parameter must be provided.
persistent_files:
# A list of newline separated file names that should persist between
# updates. This is useful for static configuration files, or perhaps
# themes. The default is no persistent files.
```
This second example is for git repositories that have a service that need
updating.
```
# moonraker.conf
# service_name must be the name of the systemd service
[update_manager client service_name]
type: git_repo
path:
# The path to the client's files on disk. This parameter must be provided.
origin:
# The full GitHub URL of the "origin" remote for the repository. This can
# be be viewed by navigating to your repository and running:
# git remote -v
# This parameter must be provided.
env:
# The path to the client's virtual environment executable on disk. For
# example, Moonraker's venv is located at ~/moonraker-env/bin/python.
# The default is no env, which disables updating python packages.
requirements:
# This is the location in the repository to the client's virtual environment
# requirements file. This location is relative to the root of the repository.
# This parameter must be provided if the "env" option is set, otherwise it
# should be omitted.
install_script:
# The file location, relative to the repository, for the installation script.
# The update manager parses this file for "system" packages that need updating.
# The default is no install script, which disables system package updates
```
+56 -16
View File
@@ -240,6 +240,23 @@ websocket. See the `notify_status_update` notification for details.
1 second by default, containing a total of 1200 values (20 minutes). The
array is organized from oldest temperature to most recent (left to right).
Note that when the host starts each array is initialized to 0s.
```json
{
extruder: {
temperatures: [],
targets: [],
powers: []
},
temperature_fan my_fan: {
temperatures: [],
targets: [],
speeds: [],
},
temperature_sensor my_sensor: {
temperatures: []
}
}
```
### Fetch stored gcode info
- HTTP command:\
@@ -267,7 +284,8 @@ websocket. See the `notify_status_update` notification for details.
gcode_store: [
{
message: <string>,
time: unix_time_stamp
time: unix_time_stamp,
type: <string>
}, ...
]
}
@@ -282,6 +300,7 @@ for (let resp of result.gcode_store) {
// Do something with date and resp.message ...
}
```
The `type` field will either be "command" or "response".
### Restart Server
- HTTP command:\
@@ -819,12 +838,13 @@ been configured:
### Get update status
Retreives the current state of each "package" available for update. Typically
this will consist of information regarding `moonraker`, `klipper`, and
a `client`. If moonraker has not yet received information from Klipper then
its status will be omitted. If a client has not been configured then its
status will also be omitted. If the parameter "refresh" is passed and set
to true then Moonraker will query Github for the most recent release
information.
this will consist of information regarding `moonraker`, `klipper`, a `client`,
and `system` packages. If moonraker has not yet received information from
Klipper then its status will be omitted. If a client has not been configured
then its status will also be omitted. One may request that the update info
be refreshed by sending a `refresh=true` argument. Note that the refresh
parameter is ignored if an update is in progress or if a print is in progress.
In these cases the current status will be returned immediately.
- HTTP command:\
`GET /machine/update/status?refresh=false`
@@ -867,7 +887,7 @@ information.
detached: <bool>,
debug_enabled: <bool>
},
'client': {
'client_name_1': {
name: <string>,
version: <string>,
remote_version: <string>
@@ -908,10 +928,13 @@ information.
- `debug_enabled`: True when "enable_repo_debug" has been configured. This
will bypass repo validation, allowing detached updates, and updates from
a remote/origin other than "origin/master".
- The `client` object has the following fields:
- Multiple `client` fields may be present. Web clients have the following
fields:
- `name`: Name of the configured client
- `version`: version of the installed client.
- `remote_version`: version of the latest release published to GitHub
A `git_repo` client will have fields that match that of `klipper` and
`moonraker`
- The `system` object has the following fields:
- `package_count`: The number of system packages available for update
- `package_list`: An array containing the names of packages available
@@ -923,7 +946,8 @@ the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
Note that Moonraker uses semantic versioning to check for dependency changes
automatically, so it is generally not necessary to set `include_deps`
to `true`.
to `true`. If an update is requested while a print is in progress then
this request will return an error.
- HTTP command:\
`POST /machine/update/moonraker?include_deps=false`
@@ -946,7 +970,8 @@ the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
At the moment there is no method for automatically checking for updated
Klipper dependencies, so clients might wish to make this option available
to users via the UI.
to users via the UI. If an update is requested while a print is in progress
then this request will return an error.
- HTTP command:\
`POST /machine/update/klipper?include_deps=false`
@@ -964,22 +989,27 @@ to users via the UI.
`ok` when complete
### Update Client
If `client_repo` and `client_path` have been configured in `[update_manager]`
this endpoint can be used to install the most recently publish release
of the client.
If one more more `[update_manager client client_name]` sections have
been configured this endpoint can be used to install the most recently
published release of the client. If an update is requested while a
print is in progress then this request will return an error. The
`name` argument is requred, it's value should match the `client_name`
of the configured section.
- HTTP command:\
`POST /machine/update/client`
`POST /machine/update/client?name=client_name`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.client",
id: <request id>}`
params: {name: "client_name"}, id: <request id>}`
- Returns:\
`ok` when complete
### Update System Packages
Upgrades the system packages. Currently only `apt-get` is supported.
If an update is requested while a print is in progress then this request
will return an error.
- HTTP command:\
`POST /machine/update/system`
@@ -1216,6 +1246,16 @@ Where `response` is an object int he following format:
update, indicating that the update completed successfully. Otherwise it
will be false.
### Update Manager Refreshed
The update manager periodically auto refreshes the state of each application
it is tracking. After an auto refresh has completed the following
notification is broadcast:
`{jsonrpc: "2.0", method: "notify_update_refreshed", params: [update_info]}`
Where `update_info` is an object that matches the response from an
[update status](#get-update-status) request.
# Appendix
## Websocket setup
+5 -4
View File
@@ -132,9 +132,10 @@ class MoonrakerApp:
# Register handlers
logfile = config['system_args'].get('logfile')
if logfile:
self.register_static_file_handler("moonraker.log", logfile)
self.register_static_file_handler(
"moonraker.log", logfile, force=True)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
self.auth.register_handlers(self)
def listen(self, host, port):
@@ -197,10 +198,10 @@ class MoonrakerApp:
self.wsm.register_local_handler(api_def, callback)
logging.info(msg)
def register_static_file_handler(self, pattern, file_path):
def register_static_file_handler(self, pattern, file_path, force=False):
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path):
if os.path.isfile(file_path) or force:
pattern += '()'
elif os.path.isdir(file_path):
if pattern[-1] != "/":
+5 -1
View File
@@ -70,7 +70,7 @@ class ConfigHelper:
self.config[self.section].getboolean, option, default)
def getfloat(self, option, default=Sentinel):
return self._get_item(
return self._get_option(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
@@ -83,6 +83,9 @@ class ConfigHelper:
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
def write_config(self, file_obj):
self.config.write(file_obj)
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
@@ -103,6 +106,7 @@ def get_configuration(server, system_args):
logging.getLogger().setLevel(logging.DEBUG)
config['system_args'] = {
'configfile': system_args.configfile,
'logfile': system_args.logfile,
'software_version': system_args.software_version}
return ConfigHelper(server, config, 'server')
+34 -5
View File
@@ -8,6 +8,7 @@ import argparse
import sys
import importlib
import os
import io
import time
import socket
import logging
@@ -35,8 +36,17 @@ class Sentinel:
class Server:
error = ServerError
def __init__(self, args):
def __init__(self, args, file_logger):
self.file_logger = file_logger
config = confighelper.get_configuration(self, args)
# log config file
strio = io.StringIO()
config.write_config(strio)
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
cfg_item += strio.getvalue()
cfg_item += "#"*65
strio.close()
self.add_log_rollover_item('config', cfg_item)
self.host = config.get('host', "0.0.0.0")
self.port = config.getint('port', 7125)
@@ -54,6 +64,7 @@ class Server:
self.init_attempts = 0
self.klippy_state = "disconnected"
self.subscriptions = {}
self.failed_plugins = []
# Server/IOLoop
self.server_running = False
@@ -95,6 +106,12 @@ class Server:
self.server_running = True
self.ioloop.spawn_callback(self._connect_klippy)
def add_log_rollover_item(self, name, item, log=True):
if self.file_logger is not None:
self.file_logger.set_rollover_info(name, item)
if log and item is not None:
logging.info(item)
# ***** Plugin Management *****
def _load_plugins(self, config):
# load core plugins
@@ -116,11 +133,12 @@ class Server:
if not os.path.exists(mod_path):
msg = f"Plugin ({plugin_name}) does not exist"
logging.info(msg)
self.failed_plugins.append(plugin_name)
if default == Sentinel:
raise ServerError(msg)
return default
module = importlib.import_module("plugins." + plugin_name)
try:
module = importlib.import_module("plugins." + plugin_name)
func_name = "load_plugin"
if hasattr(module, "load_plugin_multi"):
func_name = "load_plugin_multi"
@@ -131,6 +149,7 @@ class Server:
except Exception:
msg = f"Unable to load plugin ({plugin_name})"
logging.exception(msg)
self.failed_plugins.append(plugin_name)
if default == Sentinel:
raise ServerError(msg)
return default
@@ -368,6 +387,10 @@ class Server:
if rpc_method == "objects/subscribe":
return await self._request_subscripton(web_request)
else:
if rpc_method == "gcode/script":
script = web_request.get_str('script', "")
data_store = self.lookup_plugin('data_store')
data_store.store_gcode_command(script)
return await self._request_standard(web_request)
async def _request_subscripton(self, web_request):
@@ -445,10 +468,16 @@ class Server:
return "ok"
async def _handle_info_request(self, web_request):
file_manager = self.lookup_plugin('file_manager', None)
reg_dirs = []
if file_manager is not None:
reg_dirs = file_manager.get_registered_dirs()
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_state,
'plugins': list(self.plugins.keys())}
'plugins': list(self.plugins.keys()),
'failed_plugins': self.failed_plugins,
'registered_directories': reg_dirs}
class KlippyConnection:
def __init__(self, on_recd, on_close):
@@ -565,7 +594,7 @@ def main():
system_args.logfile))
system_args.logfile = log_file
system_args.software_version = version
ql = utils.setup_logging(log_file, version)
ql, file_logger = utils.setup_logging(log_file, version)
if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \
@@ -580,7 +609,7 @@ def main():
estatus = 0
while True:
try:
server = Server(system_args)
server = Server(system_args, file_logger)
except Exception:
logging.exception("Moonraker Error")
estatus = 1
+31 -13
View File
@@ -61,14 +61,18 @@ class DataStore:
logging.info(f"Configuring available sensors: {sensors}")
new_store = {}
for sensor in sensors:
fields = list(status.get(sensor, {}).keys())
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE)}
for item in ["target", "power", "speed"]:
if item in fields:
new_store[sensor][f"{item}s"] = deque(
maxlen=TEMPERATURE_STORE_SIZE)
if sensor not in self.last_temps:
self.last_temps[sensor] = (0., 0.)
self.last_temps[sensor] = (0., 0., 0., 0.)
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
@@ -86,17 +90,21 @@ class DataStore:
def _set_current_temps(self, data):
for sensor in self.temperature_store:
if sensor in data:
last_temp, last_target = self.last_temps[sensor]
last_val = self.last_temps[sensor]
self.last_temps[sensor] = (
round(data[sensor].get('temperature', last_temp), 2),
data[sensor].get('target', last_target))
round(data[sensor].get('temperature', last_val[0]), 2),
data[sensor].get('target', last_val[1]),
data[sensor].get('power', last_val[2]),
data[sensor].get('speed', last_val[3]))
def _update_temperature_store(self):
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, (temp, target) in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(temp)
self.temperature_store[sensor]['targets'].append(target)
for sensor, vals in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(vals[0])
for val, item in zip(vals[1:], ["targets", "powers", "speeds"]):
if item in self.temperature_store[sensor]:
self.temperature_store[sensor][item].append(val)
async def _handle_temp_store_request(self, web_request):
store = {}
@@ -109,15 +117,25 @@ class DataStore:
def _update_gcode_store(self, response):
curtime = time.time()
self.gcode_queue.append({'message': response, 'time': curtime})
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def store_gcode_command(self, script):
curtime = time.time()
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
self.gcode_queue.append(
{'message': script, 'time': curtime, 'type': "command"})
async def _handle_gcode_store_request(self, web_request):
count = web_request.get_int("count", None)
if count is not None:
res = list(self.gcode_queue)[-count:]
gc_responses = list(self.gcode_queue)[-count:]
else:
res = list(self.gcode_queue)
return {'gcode_store': res}
gc_responses = list(self.gcode_queue)
return {'gcode_store': gc_responses}
def load_plugin(config):
return DataStore(config)
+60 -24
View File
@@ -13,9 +13,9 @@ import json
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Event
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco', '.ufp']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.normpath(os.path.join(
METADATA_SCRIPT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
class FileManager:
@@ -77,13 +77,15 @@ class FileManager:
# Register log path
log_file = paths.get('log_file')
log_path = os.path.normpath(os.path.expanduser(log_file))
self.server.register_static_file_handler("klippy.log", log_path)
if log_file is not None:
log_path = os.path.abspath(os.path.expanduser(log_file))
self.server.register_static_file_handler(
"klippy.log", log_path, force=True)
def register_directory(self, root, path):
if path is None:
return False
path = os.path.normpath(os.path.expanduser(path))
path = os.path.abspath(os.path.expanduser(path))
if os.path.islink(path):
path = os.path.realpath(path)
if not os.path.isdir(path) or path == "/":
@@ -115,6 +117,9 @@ class FileManager:
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
def get_registered_dirs(self):
return list(self.file_paths.keys())
def get_fixed_path_args(self):
return dict(self.fixed_path_args)
@@ -138,18 +143,7 @@ class FileManager:
if action == 'GET':
is_extended = web_request.get_boolean('extended', False)
# Get list of files and subdirectories for this target
dir_info = self._list_directory(dir_path)
# Check to see if a filelist update is necessary
for f in dir_info['files']:
fname = os.path.join(rel_path, f['filename'])
ext = os.path.splitext(f['filename'])[-1].lower()
if root != 'gcodes' or ext not in VALID_GCODE_EXTS:
continue
self.gcode_metadata.parse_metadata(
fname, f['size'], f['modified'], notify=True)
metadata = self.gcode_metadata.get(fname, None)
if metadata is not None and is_extended:
f.update(metadata)
dir_info = self._list_directory(dir_path, is_extended)
return dir_info
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
# Create a new directory
@@ -271,20 +265,45 @@ class FileManager:
{'path': src_rel_path, 'root': source_root})
return "ok"
def _list_directory(self, path):
def _list_directory(self, path, is_extended=False):
if not os.path.isdir(path):
raise self.server.error(
f"Directory does not exist ({path})")
flist = {'dirs': [], 'files': []}
for fname in os.listdir(path):
full_path = os.path.join(path, fname)
if not os.path.exists(full_path):
continue
path_info = self._get_path_info(full_path)
if os.path.isdir(full_path):
path_info['dirname'] = fname
flist['dirs'].append(path_info)
elif os.path.isfile(full_path):
path_info['filename'] = fname
# Check to see if a filelist update is necessary
ext = os.path.splitext(fname)[-1].lower()
gc_path = self.file_paths.get('gcodes', None)
if gc_path is not None and full_path.startswith(gc_path) and \
ext in VALID_GCODE_EXTS:
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(
full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
path_info = self._get_path_info(full_path)
path_info['filename'] = os.path.split(full_path)[-1]
rel_path = os.path.relpath(full_path, start=gc_path)
self.gcode_metadata.parse_metadata(
rel_path, path_info['size'], path_info['modified'],
notify=True)
metadata = self.gcode_metadata.get(rel_path, None)
if metadata is not None and is_extended:
path_info.update(metadata)
flist['files'].append(path_info)
usage = shutil.disk_usage(path)
flist['disk_usage'] = usage._asdict()
return flist
def _get_path_info(self, path):
@@ -383,7 +402,7 @@ class FileManager:
filename = upload['filename'].strip().lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(root_path, filename))
full_path = os.path.abspath(os.path.join(root_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(root_path):
raise self.server.error(
@@ -445,6 +464,19 @@ class FileManager:
except Exception:
logging.exception("Unable to write Image")
def _process_ufp_from_refresh(self, ufp_path):
filename = os.path.split(ufp_path)[-1]
ul = {
'filename': filename,
'full_path': ufp_path
}
with open(ufp_path, 'rb') as ufp:
body = ufp.read()
ul['body'] = body
self._unzip_ufp(ul)
os.remove(ufp_path)
return ul['full_path']
def get_file_list(self, root, list_format=False, notify=False):
# Use os.walk find files in sd path and subdirs
filelist = {}
@@ -472,6 +504,12 @@ class FileManager:
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(dir_path, name)
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
@@ -496,12 +534,10 @@ class FileManager:
if filename.startswith('gcodes/'):
filename = filename[7:]
flist = self.get_file_list("gcodes")
return self.gcode_metadata.get(filename, flist.get(filename, {}))
return self.gcode_metadata.get(filename, {})
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root. Currently the only
# Supported root is "gcodes"
# List a directory relative to its root.
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
@@ -680,7 +716,7 @@ class MetadataStorage:
scmd = shell_command.build_shell_command(
cmd, self._handle_script_response)
self.script_response = None
await scmd.run(timeout=4.)
await scmd.run(timeout=10.)
if self.script_response is None:
raise self.server.error("Unable to extract metadata")
path = self.script_response['file']
+6 -4
View File
@@ -39,15 +39,17 @@ class Machine:
async def reboot_machine(self):
await self._execute_cmd("sudo shutdown -r now")
async def restart_service(self, service_name):
await self._execute_cmd(f'sudo systemctl restart {service_name}')
async def _handle_service_restart(self, web_request):
name = web_request.get('service')
if name == "klipper":
await self._execute_cmd(f'sudo systemctl restart {name}')
await self.restart_service(name)
elif name == "moonraker":
IOLoop.current().spawn_callback(
self._execute_cmd, f'sudo systemctl restart {name}')
IOLoop.current().spawn_callback(self.restart_service, name)
else:
raise self.sever.error(
raise self.server.error(
f"Invalid argument recevied for 'name': {name}")
return "ok"
+1 -1
View File
@@ -143,7 +143,6 @@ class PanelDue:
def __init__(self, config):
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"
@@ -195,6 +194,7 @@ class PanelDue:
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.ser_conn = SerialConnection(config, self)
logging.info("PanelDue Configured")
# Register server events
+106 -55
View File
@@ -20,6 +20,27 @@ from tornado.escape import json_decode
class PrinterPower:
def __init__(self, config):
self.server = config.get_server()
self.chip_factory = GpioChipFactory()
self.devices = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power plugin loading devices: {prefix_sections}")
try:
for section in prefix_sections:
cfg = config[section]
dev_type = cfg.get("type")
if dev_type == "gpio":
dev = GpioDevice(cfg, self.chip_factory)
elif dev_type == "tplink_smartplug":
dev = TPLinkSmartPlug(cfg)
elif dev_type == "tasmota":
dev = Tasmota(cfg)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
self.devices[dev.get_name()] = dev
except Exception:
self.chip_factory.close()
raise
self.server.register_endpoint(
"/machine/device_power/devices", ['GET'],
self._handle_list_devices)
@@ -34,24 +55,32 @@ class PrinterPower:
self._handle_power_request)
self.server.register_remote_method(
"set_device_power", self.set_device_power)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_klippy_shutdown)
IOLoop.current().spawn_callback(
self._initalize_devices, list(self.devices.values()))
self.chip_factory = GpioChipFactory()
self.current_dev = None
self.devices = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power plugin loading devices: {prefix_sections}")
for section in prefix_sections:
cfg = config[section]
dev_type = cfg.get("type")
if dev_type == "gpio":
dev = GpioDevice(cfg, self.chip_factory)
elif dev_type == "tplink_smartplug":
dev = TPLinkSmartPlug(cfg)
elif dev_type == "tasmota":
dev = Tasmota(cfg)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
self.devices[dev.get_name()] = dev
async def _check_klippy_printing(self):
klippy_apis = self.server.lookup_plugin('klippy_apis')
result = await klippy_apis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "").lower()
return pstate == "printing"
async def _initalize_devices(self, inital_devs):
for dev in inital_devs:
ret = dev.initialize()
if asyncio.iscoroutine(ret):
await ret
async def _handle_klippy_shutdown(self):
for name, dev in self.devices.items():
if hasattr(dev, "off_when_shutdown"):
if dev.off_when_shutdown:
logging.info(
f"Powering off device [{name}] due to"
" klippy shutdown")
await self._process_request(dev, "off")
async def _handle_list_devices(self, web_request):
dev_list = [d.get_device_info() for d in self.devices.values()]
@@ -75,11 +104,21 @@ class PrinterPower:
async def _process_request(self, device, req):
if req in ["on", "off"]:
cur_state = device.get_device_info()['status']
if req == cur_state:
# device is already in requested state, do nothing
return cur_state
printing = await self._check_klippy_printing()
if device.get_locked_while_printing() and printing:
raise self.server.error(
f"Unable to change power for {device.get_name()} "
"while printing")
ret = device.set_power(req)
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
self.server.send_event("gpio_power:power_changed", dev_info)
device.run_power_changed_action()
elif req == "status":
ret = device.refresh_status()
if asyncio.iscoroutine(ret):
@@ -125,6 +164,45 @@ class PrinterPower:
self.chip_factory.close()
class PowerDevice:
def __init__(self, config):
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.server = config.get_server()
self.name = name_parts[1]
self.state = "init"
self.locked_while_printing = config.getboolean(
'locked_while_printing', False)
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
self.restart_delay = 1.
self.klipper_restart = config.getboolean(
'restart_klipper_when_powered', False)
if self.klipper_restart:
self.restart_delay = config.getfloat('restart_delay', 1.)
if self.restart_delay < .000001:
raise config.error("Option 'restart_delay' must be above 0.0")
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'locked_while_printing': self.locked_while_printing
}
def get_locked_while_printing(self):
return self.locked_while_printing
def run_power_changed_action(self):
if self.state == "on" and self.klipper_restart:
ioloop = IOLoop.current()
klippy_apis = self.server.lookup_plugin("klippy_apis")
ioloop.call_later(self.restart_delay, klippy_apis.do_restart,
"FIRMWARE_RESTART")
class GpioChipFactory:
def __init__(self):
self.chips = {}
@@ -140,13 +218,9 @@ class GpioChipFactory:
for chip in self.chips.values():
chip.close()
class GpioDevice:
class GpioDevice(PowerDevice):
def __init__(self, config, chip_factory):
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
super().__init__(config)
pin, chip_id, invert = self._parse_pin(config)
try:
chip = chip_factory.get_gpio_chip(chip_id)
@@ -164,8 +238,7 @@ class GpioDevice:
f"Unable to init {pin}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise config.error("Power GPIO Config Error")
initial_state = config.getboolean('initial_state', False)
self.set_power("on" if initial_state else "off")
self.initial_state = config.getboolean('initial_state', False)
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
@@ -190,15 +263,11 @@ class GpioDevice:
return pin, chip_id, invert
def initialize(self):
pass
def get_name(self):
return self.name
self.set_power("on" if self.initial_state else "off")
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "gpio"
}
@@ -232,18 +301,13 @@ class GpioDevice:
# https://github.com/softScheck/tplink-smartplug
#
# Copyright 2016 softScheck GmbH
class TPLinkSmartPlug:
class TPLinkSmartPlug(PowerDevice):
START_KEY = 0xAB
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.port = config.getint("port", 9999)
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tplink_command(self, command):
out_cmd = {}
@@ -300,13 +364,9 @@ class TPLinkSmartPlug:
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "tplink_smartplug"
}
@@ -335,18 +395,13 @@ class TPLinkSmartPlug:
self.state = state
class Tasmota:
class Tasmota(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tasmota_command(self, command, password=None):
if command in ["on", "off"]:
@@ -372,13 +427,9 @@ class Tasmota:
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "tasmota"
}
+11 -3
View File
@@ -7,7 +7,6 @@ import os
import shlex
import subprocess
import logging
import tornado
from tornado import gen
from tornado.ioloop import IOLoop
@@ -100,7 +99,7 @@ class ShellCommand:
logging.info(msg)
return success
async def run_with_response(self, timeout=2.):
async def run_with_response(self, timeout=2., retries=1):
result = []
def cb(data):
@@ -109,7 +108,16 @@ class ShellCommand:
result.append(data.decode())
prev_cb = self.output_cb
self.output_cb = cb
await self.run(timeout)
while 1:
ret = await self.run(timeout)
if not ret or not result:
retries -= 1
if not retries:
return None
await gen.sleep(.5)
result.clear()
continue
break
self.output_cb = prev_cb
return "\n".join(result)
+322 -83
View File
@@ -4,6 +4,7 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import glob
import re
import logging
import json
@@ -13,10 +14,11 @@ import zipfile
import io
import asyncio
import time
import tempfile
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.httpclient import AsyncHTTPClient
from tornado.locks import Event
from tornado.locks import Event, Condition, Lock
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
@@ -25,39 +27,75 @@ SUPPLEMENTAL_CFG_PATH = os.path.join(
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
SUPPORTED_DISTROS = ["debian"]
# Check To see if Updates are necessary each hour
UPDATE_REFRESH_INTERVAL_MS = 3600000
# Perform auto refresh no sooner than 12 hours apart
MIN_REFRESH_TIME = 43200
# Perform auto refresh no later than 4am
MAX_PKG_UPDATE_HOUR = 4
class UpdateManager:
def __init__(self, config):
self.server = config.get_server()
self.config = config
self.config.read_supplemental_config(SUPPLEMENTAL_CFG_PATH)
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
self.repo_debug = config.getboolean('enable_repo_debug', False)
auto_refresh_enabled = config.getboolean('enable_auto_refresh', False)
self.distro = config.get('distro', "debian").lower()
if self.distro not in SUPPORTED_DISTROS:
raise config.error(f"Unsupported distro: {self.distro}")
if self.repo_debug:
logging.warn("UPDATE MANAGER: REPO DEBUG ENABLED")
env = sys.executable
mooncfg = self.config[f"update_manager static {self.distro} moonraker"]
self.updaters = {
"system": PackageUpdater(self),
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
"moonraker": GitUpdater(self, mooncfg, MOONRAKER_PATH, env)
}
self.current_update = None
# TODO: Check for client config in [update_manager]. This is
# deprecated and will be removed.
client_repo = config.get("client_repo", None)
if client_repo is not None:
client_path = os.path.expanduser(config.get("client_path"))
if os.path.islink(client_path):
raise config.error(
"Option 'client_path' cannot be set to a symbolic link")
self.updaters['client'] = ClientUpdater(
self, client_repo, client_path)
client_path = config.get("client_path")
name = client_repo.split("/")[-1]
self.updaters[name] = WebUpdater(
self, {'repo': client_repo, 'path': client_path})
client_sections = self.config.get_prefix_sections(
"update_manager client")
for section in client_sections:
cfg = self.config[section]
name = section.split()[-1]
if name in self.updaters:
raise config.error("Client repo named %s already added"
% (name,))
client_type = cfg.get("type")
if client_type == "git_repo":
self.updaters[name] = GitUpdater(self, cfg)
elif client_type == "web":
self.updaters[name] = WebUpdater(self, cfg)
else:
raise config.error("Invalid type '%s' for section [%s]"
% (client_type, section))
# GitHub API Rate Limit Tracking
self.gh_rate_limit = None
self.gh_limit_remaining = None
self.gh_limit_reset_time = None
self.gh_init_evt = Event()
self.cmd_request_lock = Lock()
self.is_refreshing = False
# Auto Status Refresh
self.last_auto_update_time = 0
self.refresh_cb = None
if auto_refresh_enabled:
self.refresh_cb = PeriodicCallback(
self._handle_auto_refresh, UPDATE_REFRESH_INTERVAL_MS)
self.refresh_cb.start()
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
self.server.register_endpoint(
"/machine/update/moonraker", ["POST"],
@@ -78,8 +116,21 @@ class UpdateManager:
# Register Ready Event
self.server.register_event_handler(
"server:klippy_identified", self._set_klipper_repo)
# Initialize GitHub API Rate Limits
IOLoop.current().spawn_callback(self._init_api_rate_limit)
# Initialize GitHub API Rate Limits and configured updaters
IOLoop.current().spawn_callback(
self._initalize_updaters, list(self.updaters.values()))
async def _initalize_updaters(self, initial_updaters):
self.is_refreshing = True
await self._init_api_rate_limit()
for updater in initial_updaters:
if isinstance(updater, PackageUpdater):
ret = updater.refresh(False)
else:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
self.is_refreshing = False
async def _set_klipper_repo(self):
kinfo = self.server.get_klippy_info()
@@ -93,36 +144,112 @@ class UpdateManager:
kupdater.env == env:
# Current Klipper Updater is valid
return
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
kcfg = self.config[f"update_manager static {self.distro} klipper"]
self.updaters['klipper'] = GitUpdater(self, kcfg, kpath, env)
await self.updaters['klipper'].refresh()
async def _check_klippy_printing(self):
klippy_apis = self.server.lookup_plugin('klippy_apis')
result = await klippy_apis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "")
return pstate.lower() == "printing"
async def _handle_auto_refresh(self):
if await self._check_klippy_printing():
# Don't Refresh during a print
logging.info("Klippy is printing, auto refresh aborted")
return
cur_time = time.time()
cur_hour = time.localtime(cur_time).tm_hour
time_diff = cur_time - self.last_auto_update_time
# Update packages if it has been more than 12 hours
# and the local time is between 12AM and 5AM
if time_diff < MIN_REFRESH_TIME or cur_hour >= MAX_PKG_UPDATE_HOUR:
# Not within the update time window
return
self.last_auto_update_time = cur_time
vinfo = {}
need_refresh_all = not self.is_refreshing
async with self.cmd_request_lock:
self.is_refreshing = True
try:
for name, updater in list(self.updaters.items()):
if need_refresh_all:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
except Exception:
logging.exception("Unable to Refresh Status")
return
finally:
self.is_refreshing = False
uinfo = {
'version_info': vinfo,
'github_rate_limit': self.gh_rate_limit,
'github_requests_remaining': self.gh_limit_remaining,
'github_limit_reset_time': self.gh_limit_reset_time,
'busy': self.current_update is not None}
self.server.send_event("update_manager:update_refreshed", uinfo)
async def _handle_update_request(self, web_request):
if await self._check_klippy_printing():
raise self.server.error("Update Refused: Klippy is printing")
app = web_request.get_endpoint().split("/")[-1]
if app == "client":
app = web_request.get('name')
inc_deps = web_request.get_boolean('include_deps', False)
if self.current_update:
raise self.server.error("A current update is in progress")
if self.current_update is not None and \
self.current_update[0] == app:
return f"Object {app} is currently being updated"
updater = self.updaters.get(app, None)
if updater is None:
raise self.server.error(f"Updater {app} not available")
self.current_update = (app, id(web_request))
try:
await updater.update(inc_deps)
except Exception:
self.current_update = None
raise
self.current_update = None
async with self.cmd_request_lock:
self.current_update = (app, id(web_request))
try:
await updater.update(inc_deps)
except Exception as e:
self.notify_update_response(f"Error updating {app}")
self.notify_update_response(str(e), is_complete=True)
raise
finally:
self.current_update = None
return "ok"
async def _handle_status_request(self, web_request):
refresh = web_request.get_boolean('refresh', False)
check_refresh = web_request.get_boolean('refresh', False)
# Don't refresh if a print is currently in progress or
# if an update is in progress. Just return the current
# state
if self.current_update is not None or \
await self._check_klippy_printing():
check_refresh = False
need_refresh = False
if check_refresh:
# If there is an outstanding request processing a
# refresh, we don't need to do it again.
need_refresh = not self.is_refreshing
await self.cmd_request_lock.acquire()
self.is_refreshing = True
vinfo = {}
for name, updater in self.updaters.items():
await updater.check_initialized(120.)
if refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
try:
for name, updater in list(self.updaters.items()):
await updater.check_initialized(120.)
if need_refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
except Exception:
raise
finally:
if check_refresh:
self.is_refreshing = False
self.cmd_request_lock.release()
return {
'version_info': vinfo,
'github_rate_limit': self.gh_rate_limit,
@@ -144,7 +271,10 @@ class UpdateManager:
async def execute_cmd_with_response(self, cmd, timeout=10.):
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
return await scmd.run_with_response(timeout)
result = await scmd.run_with_response(timeout, retries=5)
if result is None:
raise self.server.error(f"Error Running Command: {cmd}")
return result
async def _init_api_rate_limit(self):
url = "https://api.github.com/rate_limit"
@@ -190,9 +320,11 @@ class UpdateManager:
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
timeout = time.time() + 10.
fut = self.http_client.fetch(
url, headers=headers, connect_timeout=5.,
request_timeout=5., raise_error=False)
resp = await tornado.gen.with_timeout(timeout, fut)
except Exception:
retries -= 1
msg = f"Error Processing GitHub API request: {url}"
@@ -241,9 +373,11 @@ class UpdateManager:
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
timeout = time.time() + 130.
fut = self.http_client.fetch(
url, headers={"Accept": "application/zip"},
connect_timeout=5., request_timeout=120.)
resp = await tornado.gen.with_timeout(timeout, fut)
except Exception:
retries -= 1
logging.exception("Error Processing Download")
@@ -270,29 +404,68 @@ class UpdateManager:
def close(self):
self.http_client.close()
if self.refresh_cb is not None:
self.refresh_cb.stop()
class GitUpdater:
def __init__(self, umgr, name, path, env):
def __init__(self, umgr, config, path=None, env=None):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
self.notify_update_response = umgr.notify_update_response
distro = umgr.distro
config = umgr.config
self.repo_info = config[f"repo_info {name}"].get_options()
self.dist_info = config[f"dist_info {distro} {name}"].get_options()
self.name = name
self.name = config.get_name().split()[-1]
self.repo_path = path
self.env = env
if path is None:
self.repo_path = config.get('path')
self.env = config.get("env", env)
dist_packages = None
if self.env is not None:
self.env = os.path.expanduser(self.env)
dist_packages = config.get('python_dist_packages', None)
self.python_reqs = os.path.join(
self.repo_path, config.get("requirements"))
self.origin = config.get("origin").lower()
self.install_script = config.get('install_script', None)
if self.install_script is not None:
self.install_script = os.path.abspath(os.path.join(
self.repo_path, self.install_script))
self.venv_args = config.get('venv_args', None)
self.python_dist_packages = None
self.python_dist_path = None
self.env_package_path = None
if dist_packages is not None:
self.python_dist_packages = [
p.strip() for p in dist_packages.split('\n')
if p.strip()]
self.python_dist_path = os.path.abspath(
config.get('python_dist_path'))
env_package_path = os.path.abspath(os.path.join(
os.path.dirname(self.env), "..",
config.get('env_package_path')))
matches = glob.glob(env_package_path)
if len(matches) == 1:
self.env_package_path = matches[0]
else:
raise config.error("No match for 'env_package_path': %s"
% (env_package_path,))
for opt in ["repo_path", "env", "python_reqs", "install_script",
"python_dist_path", "env_package_path"]:
val = getattr(self, opt)
if val is None:
continue
if not os.path.exists(val):
raise config.error("Invalid path for option '%s': %s"
% (val, opt))
self.version = self.cur_hash = "?"
self.remote_version = self.remote_hash = "?"
self.init_evt = Event()
self.refresh_condition = None
self.debug = umgr.repo_debug
self.remote = "origin"
self.branch = "master"
self.is_valid = self.is_dirty = self.detached = False
IOLoop.current().spawn_callback(self.refresh)
def _get_version_info(self):
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
@@ -338,8 +511,18 @@ class GitUpdater:
await self.init_evt.wait(timeout)
async def refresh(self):
await self._check_version()
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
await self._check_version()
except Exception:
logging.exception("Error Refreshing git state")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def _check_version(self, need_fetch=True):
self.is_valid = self.detached = False
@@ -420,7 +603,7 @@ class GitUpdater:
remote_url = remote_url.lower()
if remote_url[-4:] != ".git":
remote_url += ".git"
if remote_url == self.repo_info['origin']:
if remote_url == self.origin:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
@@ -431,6 +614,9 @@ class GitUpdater:
f"{self.remote}/{self.branch}")
async def update(self, update_deps=False):
await self.check_initialized(20.)
if self.refresh_condition is not None:
self.refresh_condition.wait()
if not self.is_valid:
raise self._log_exc("Update aborted, repo is not valid", False)
if self.is_dirty:
@@ -476,9 +662,10 @@ class GitUpdater:
self._notify_status("Update Finished...", is_complete=True)
async def _install_packages(self):
if self.install_script is None:
return
# Open install file file and read
inst_script = self.dist_info['install_script']
inst_path = os.path.join(self.repo_path, inst_script)
inst_path = self.install_script
if not os.path.isfile(inst_path):
self._log_info(f"Unable to open install script: {inst_path}")
return
@@ -505,24 +692,24 @@ class GitUpdater:
return
async def _update_virtualenv(self, rebuild_env=False):
if self.env is None:
return
# Update python dependencies
bin_dir = os.path.dirname(self.env)
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
if rebuild_env:
env_args = self.repo_info['venv_args']
self._notify_status(f"Creating virtualenv at: {env_path}...")
if os.path.exists(env_path):
shutil.rmtree(env_path)
try:
await self.execute_cmd(
f"virtualenv {env_args} {env_path}", timeout=300.)
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
except Exception:
self._log_exc(f"Error creating virtualenv")
return
if not os.path.expanduser(self.env):
if not os.path.exists(self.env):
raise self._log_exc("Failed to create new virtualenv", False)
reqs = os.path.join(
self.repo_path, self.repo_info['requirements'])
reqs = self.python_reqs
if not os.path.isfile(reqs):
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
return
@@ -534,16 +721,14 @@ class GitUpdater:
retries=3)
except Exception:
self._log_exc("Error updating python requirements")
self._install_python_dist_requirements(env_path)
self._install_python_dist_requirements()
def _install_python_dist_requirements(self, env_path):
dist_reqs = self.dist_info.get('python_dist_packages', None)
def _install_python_dist_requirements(self):
dist_reqs = self.python_dist_packages
if dist_reqs is None:
return
dist_reqs = [r.strip() for r in dist_reqs.split("\n")
if r.strip()]
dist_path = self.dist_info['python_dist_path']
site_path = os.path.join(env_path, self.dist_info['env_package_path'])
dist_path = self.python_dist_path
site_path = self.env_package_path
for pkg in dist_reqs:
for f in os.listdir(dist_path):
if f.startswith(pkg):
@@ -589,17 +774,21 @@ class PackageUpdater:
self.notify_update_response = umgr.notify_update_response
self.available_packages = []
self.init_evt = Event()
IOLoop.current().spawn_callback(self.refresh)
self.refresh_condition = None
async def refresh(self):
async def refresh(self, fetch_packages=True):
# TODO: Use python-apt python lib rather than command line for updates
try:
await self.execute_cmd(f"{APT_CMD} update", timeout=300.)
res = await self.execute_cmd_with_response(
"apt list --upgradable")
except Exception:
logging.exception("Error Refreshing System Packages")
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
if fetch_packages:
await self.execute_cmd(
f"{APT_CMD} update", timeout=300., retries=3)
res = await self.execute_cmd_with_response(
"apt list --upgradable", timeout=60.)
pkg_list = [p.strip() for p in res.split("\n") if p.strip()]
if pkg_list:
pkg_list = pkg_list[2:]
@@ -609,7 +798,11 @@ class PackageUpdater:
logging.info(
f"Detected {len(self.available_packages)} package updates:"
f"\n{pkg_list}")
except Exception:
logging.exception("Error Refreshing System Packages")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
@@ -619,6 +812,9 @@ class PackageUpdater:
await self.init_evt.wait(timeout)
async def update(self, *args):
await self.check_initialized(20.)
if self.refresh_condition is not None:
self.refresh_condition.wait()
self.notify_update_response("Updating packages...")
try:
await self.execute_cmd(
@@ -637,22 +833,35 @@ class PackageUpdater:
'package_list': self.available_packages
}
class ClientUpdater:
def __init__(self, umgr, repo, path):
class WebUpdater:
def __init__(self, umgr, config):
self.umgr = umgr
self.server = umgr.server
self.notify_update_response = umgr.notify_update_response
self.repo = repo.strip().strip("/")
self.repo = config.get('repo').strip().strip("/")
self.name = self.repo.split("/")[-1]
self.path = path
if hasattr(config, "get_name"):
self.name = config.get_name().split()[-1]
self.path = os.path.realpath(os.path.expanduser(
config.get("path")))
self.persistent_files = []
pfiles = config.get('persistent_files', None)
if pfiles is not None:
self.persistent_files = [pf.strip().strip("/") for pf in
pfiles.split("\n") if pf.strip()]
if ".version" in self.persistent_files:
raise config.error(
"Invalid value for option 'persistent_files': "
"'.version' can not be persistent")
self.version = self.remote_version = self.dl_url = "?"
self.etag = None
self.init_evt = Event()
self.refresh_condition = None
self._get_local_version()
logging.info(f"\nInitializing Client Updater: '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.refresh)
def _get_local_version(self):
version_path = os.path.join(self.path, ".version")
@@ -669,9 +878,21 @@ class ClientUpdater:
await self.init_evt.wait(timeout)
async def refresh(self):
# Local state
self._get_local_version()
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
self._get_local_version()
await self._get_remote_version()
except Exception:
logging.exception("Error Refreshing Client")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def _get_remote_version(self):
# Remote state
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
@@ -681,7 +902,7 @@ class ClientUpdater:
result = {}
if result is None:
# No change, update not necessary
return None
return
self.etag = result.get('etag', None)
self.remote_version = result.get('name', "?")
release_assets = result.get('assets', [{}])[0]
@@ -691,9 +912,12 @@ class ClientUpdater:
f"Local Version: {self.version}\n"
f"Remote Version: {self.remote_version}\n"
f"url: {self.dl_url}")
self.init_evt.set()
async def update(self, *args):
await self.check_initialized(20.)
if self.refresh_condition is not None:
# wait for refresh if in progess
self.refresh_condition.wait()
if self.remote_version == "?":
await self.refresh()
if self.remote_version == "?":
@@ -705,13 +929,28 @@ class ClientUpdater:
if self.version == self.remote_version:
# Already up to date
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.umgr.http_download_request(self.dl_url)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
with tempfile.TemporaryDirectory(
suffix=self.name, prefix="client") as tempdir:
if os.path.isdir(self.path):
# find and move persistent files
for fname in os.listdir(self.path):
src_path = os.path.join(self.path, fname)
if fname in self.persistent_files:
dest_dir = os.path.dirname(os.path.join(tempdir, fname))
os.makedirs(dest_dir, exist_ok=True)
shutil.move(src_path, dest_dir)
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.umgr.http_download_request(self.dl_url)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
# Move temporary files back into
for fname in os.listdir(tempdir):
src_path = os.path.join(tempdir, fname)
dest_dir = os.path.dirname(os.path.join(self.path, fname))
os.makedirs(dest_dir, exist_ok=True)
shutil.move(src_path, dest_dir)
self.version = self.remote_version
version_path = os.path.join(self.path, ".version")
if not os.path.exists(version_path):
+14 -6
View File
@@ -28,19 +28,26 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
except Exception:
self.handleError(record)
# Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, software_version, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.header = "Moonraker Log Start...\n"
self.header += f"Git Version: {software_version}\n"
self.header += "="*80 + "\n"
self.rollover_info = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}",
'version': f"Git Version: {software_version}",
}
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
def set_rollover_info(self, name, item):
self.rollover_info[name] = item
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
# Parse the git version from the command line. This code
# is borrowed from Klipper.
@@ -78,6 +85,7 @@ def setup_logging(log_file, software_version):
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
file_hdlr = None
if log_file:
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
@@ -90,4 +98,4 @@ def setup_logging(log_file, software_version):
listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
listener.start()
return listener
return listener, file_hdlr
+5
View File
@@ -186,6 +186,8 @@ class WebsocketManager:
"gpio_power:power_changed", self._handle_power_changed)
self.server.register_event_handler(
"update_manager:update_response", self._handle_update_response)
self.server.register_event_handler(
"update_manager:update_refreshed", self._handle_update_refreshed)
async def _handle_klippy_ready(self):
await self.notify_websockets("klippy_ready")
@@ -211,6 +213,9 @@ class WebsocketManager:
async def _handle_update_response(self, response):
await self.notify_websockets("update_response", response)
async def _handle_update_refreshed(self, refresh_info):
await self.notify_websockets("update_refreshed", refresh_info)
def register_local_handler(self, api_def, callback):
for ws_method, req_method in \
zip(api_def.ws_methods, api_def.request_methods):
+24 -7
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
@@ -55,6 +56,7 @@ class BaseSlicer(object):
def __init__(self, file_path):
self.path = file_path
self.header_data = self.footer_data = self.log = None
self.layer_height = None
def set_data(self, header_data, footer_data, fsize, log):
self.header_data = header_data
@@ -145,12 +147,22 @@ class PrusaSlicer(BaseSlicer):
return None
def parse_first_layer_height(self):
# Check percentage
pct = _regex_find_first(
r"; first_layer_height = (\d+)%", self.footer_data)
if pct is not None:
if self.layer_height is None:
# Failed to parse the original layer height, so it is not
# possible to calculate a percentage
return None
return round(pct / 100. * self.layer_height, 6)
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self):
matches = re.findall(
@@ -273,8 +285,9 @@ class Cura(BaseSlicer):
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
@@ -345,8 +358,9 @@ class Simplify3D(BaseSlicer):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
@@ -413,8 +427,9 @@ class KISSlicer(BaseSlicer):
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
@@ -466,7 +481,8 @@ class IdeaMaker(BaseSlicer):
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
self.layer_height = layer_info[2]
return self.layer_height
return None
def parse_object_height(self):
@@ -508,9 +524,10 @@ class IceSL(BaseSlicer):
self.header_data, float)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
@@ -530,7 +547,7 @@ SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
+7 -11
View File
@@ -1,24 +1,20 @@
# Supplemental configuration for Moonraker's Update Manager
# plugin. This file should not be modified.
[repo_info moonraker]
[update_manager static debian moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
[repo_info klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
[dist_info debian moonraker]
install_script: scripts/install-moonraker.sh
python_dist_path: /usr/lib/python3/dist-packages
env_package_path: lib/python3.7/site-packages
env_package_path: lib/python*/site-packages
python_dist_packages:
gpiod
[dist_info debian klipper]
[update_manager static debian klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
install_script: scripts/install-octopi.sh
python_dist_path: /usr/lib/python2.7/dist-packages
env_package_path: lib/python2.7/site-packages
env_package_path: lib/python*/site-packages