Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60ba8ff1d5 | ||
|
|
45557b8260 | ||
|
|
f229c3ec2c | ||
|
|
0e22a0cfe8 | ||
|
|
f2135d7483 | ||
|
|
baf97f8ea4 | ||
|
|
29b89fb87d | ||
|
|
ec7936ee97 | ||
|
|
ceaa4911bb | ||
|
|
f9dcda7ba9 | ||
|
|
0fcae5b6e4 | ||
|
|
dd81beab47 | ||
|
|
9648630392 | ||
|
|
fe2cec1087 | ||
|
|
81104a6618 | ||
|
|
980912270e | ||
|
|
39334d1098 | ||
|
|
943b78195b | ||
|
|
49c5583e95 | ||
|
|
e8776a5d85 | ||
|
|
9c385ce067 | ||
|
|
9e240c3b86 | ||
|
|
c365de32cf | ||
|
|
aa9bf0fb9c | ||
|
|
ddc7405249 | ||
|
|
25b3911d3d | ||
|
|
19bc2bfbb8 | ||
|
|
578ce740c5 | ||
|
|
6a88df095e | ||
|
|
c17d86aa09 | ||
|
|
0ad97fd9eb | ||
|
|
f3ae6da635 | ||
|
|
e9ab5fb480 | ||
|
|
21d1726bfd | ||
|
|
0b3b8cede8 | ||
|
|
00db209d5d | ||
|
|
b4602115d7 | ||
|
|
ff8e53b269 | ||
|
|
e2c325a724 | ||
|
|
a1f2228473 | ||
|
|
d70bd8d2e0 | ||
|
|
8c365c62cb | ||
|
|
6f4a72fe2e | ||
|
|
bdd270fa4a | ||
|
|
d194ce00ab | ||
|
|
5f986ab770 | ||
|
|
e0f4b46364 | ||
|
|
fb3706c54f | ||
|
|
d1388080c4 | ||
|
|
f1a75117db | ||
|
|
4ae63dbbf8 | ||
|
|
30637011e6 | ||
|
|
8a18fa6c2f | ||
|
|
4cd97d61f9 | ||
|
|
40f876192c | ||
|
|
fa53d889d0 | ||
|
|
6fcb26ddd7 | ||
|
|
67adcfc448 | ||
|
|
0c280122fb | ||
|
|
5b9f637c2d | ||
|
|
2bb9128b5b | ||
|
|
222f0c4695 | ||
|
|
ea1ad0277d | ||
|
|
1e81297624 | ||
|
|
ae3661b100 | ||
|
|
67f5b32d84 | ||
|
|
14b5384572 | ||
|
|
c261ee51f3 | ||
|
|
67f992dabd | ||
|
|
a535e6e94a | ||
|
|
4aa2a86e3b | ||
|
|
7d738c7a8b | ||
|
|
f753263c60 | ||
|
|
2f8a1567a8 | ||
|
|
933622adda | ||
|
|
1814a11a8d | ||
|
|
77c483ea0f | ||
|
|
96941922bc | ||
|
|
1f2c1b3fcd | ||
|
|
2953c3f16f | ||
|
|
8fc5aab2f0 | ||
|
|
1acb00e2f1 | ||
|
|
b0fda218f1 | ||
|
|
34af0b4bfb | ||
|
|
fad6bc4ad7 | ||
|
|
9501d72059 | ||
|
|
9993b1e656 | ||
|
|
b5394228ef | ||
|
|
6bf4ef8b00 | ||
|
|
0a7080741c | ||
|
|
223c125106 | ||
|
|
f9fc679831 | ||
|
|
586bb6a7ca | ||
|
|
76ccc8b3e1 | ||
|
|
f91e425463 | ||
|
|
46de7c48c8 | ||
|
|
063ef7194a | ||
|
|
313357061e | ||
|
|
0f62b283bd | ||
|
|
9f9a05cabb | ||
|
|
40fbe1abf1 | ||
|
|
9a309ffd59 | ||
|
|
684ff07ba2 | ||
|
|
0a7eed2767 | ||
|
|
6898ff8ab6 | ||
|
|
653c9190c4 | ||
|
|
cdbaaedc8a | ||
|
|
fa20d106cf | ||
|
|
40b74cefb5 | ||
|
|
20d27b0be6 | ||
|
|
44bdf708e6 | ||
|
|
2ddd1966fe | ||
|
|
8bb7139468 | ||
|
|
ba4d771d10 | ||
|
|
eea2abd60e | ||
|
|
70501772c1 | ||
|
|
119b0bf60c | ||
|
|
59e58226ff | ||
|
|
ec5be560d5 | ||
|
|
d19e9e2d28 | ||
|
|
abbd02aa73 | ||
|
|
1b997b7457 | ||
|
|
6dfd3ca915 | ||
|
|
aaa6ec8eb2 | ||
|
|
aba5bdf339 | ||
|
|
43e2893e01 | ||
|
|
e025a5ce01 | ||
|
|
2e44766e1e | ||
|
|
77f79fcc20 | ||
|
|
1d0a790ef5 | ||
|
|
e2a8a9b49f | ||
|
|
290be28dae | ||
|
|
f488e985ab | ||
|
|
8678e25427 | ||
|
|
d41c1c4c00 |
No files matched your search
@@ -1,14 +1,15 @@
|
||||
# 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.
|
||||
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following web clients are currently available:
|
||||
install one. The following clients are currently available:
|
||||
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -17,7 +18,7 @@ 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) - November 19th 2020
|
||||
[user_changes.md](/docs/user_changes.md) - December 31st 2020
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - November 28th 2020
|
||||
[api_changes.md](/docs/api_changes.md) - January 31st 2021
|
||||
@@ -1,5 +1,45 @@
|
||||
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
|
||||
|
||||
### December 30th 2020
|
||||
- Some additional fields are now reported in the response to
|
||||
`GET /machine/update/status`.
|
||||
|
||||
### November 28th 2020
|
||||
- The following new endpoints are available when the `[update_manager]`
|
||||
section has been configured:
|
||||
|
||||
+155
-16
@@ -1,9 +1,14 @@
|
||||
This document describes Moonraker's full configuration.
|
||||
This document describes Moonraker's full configuration. As this file
|
||||
references configuration for both Klipper (printer.cfg) and Moonraker
|
||||
(moonraker.conf), each example contains a commment indicating which
|
||||
configuration file is being refrenenced.
|
||||
|
||||
# Primary Configuration
|
||||
The sections outlined here are required for Moonraker to function. A
|
||||
minimal functional configuration might look like the following:
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
port: 7125
|
||||
@@ -19,6 +24,8 @@ trusted_clients:
|
||||
## server
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
# The host address in which to bind the HTTP server. Default is to bind
|
||||
@@ -34,15 +41,25 @@ enable_debug_logging: True
|
||||
# When set to True Moonraker will log in verbose mode. During this stage
|
||||
# of development the default is True. In the future this will change.
|
||||
config_path:
|
||||
# An optional path where configuration files are located. If specified,
|
||||
# Moonraker will serve this path allowing file and directory manipulation
|
||||
# within it. This path must be located within the user's HOME directory,
|
||||
# by may not be the home directory itself. The default is no path, which
|
||||
# results in no configuration files being served.
|
||||
# The path to a directory where configuration files are located. This
|
||||
# directory may contain Klipper config files (printer.cfg) or Moonraker
|
||||
# config files (moonraker.conf). Clients may also write their own config
|
||||
# files to this directory. Note that this may not be the system root
|
||||
# (ie: "/") and moonraker must have read and write access permissions
|
||||
# for this directory.
|
||||
temperature_store_size: 1200
|
||||
# The maximum number of temperature values to store for each sensor. Note
|
||||
# that this value also applies to the "target", "power", and "fan_speed"
|
||||
# if the sensor reports them. The default is 1200, which is enough to
|
||||
# store approximately 20 minutes of data at one value per second.
|
||||
gcode_store_size: 1000
|
||||
# The maximum number "gcode lines" to store. The default is 1000.
|
||||
```
|
||||
## authorization
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
# Enables authorization. When set to true, requests must either contain
|
||||
@@ -75,9 +92,12 @@ functionality in moonraker.
|
||||
## paneldue
|
||||
Enables PanelDue display support. The PanelDue should be connected to the
|
||||
host machine, either via the machine's UART GPIOs or through a USB-TTL
|
||||
converter.
|
||||
converter. Currently PanelDue Firmware Version 1.24 is supported. Other
|
||||
releases may not behave correctly.
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[paneldue]
|
||||
serial:
|
||||
# The serial port in which the PanelDue is connected. This parameter
|
||||
@@ -110,6 +130,8 @@ in the PanelDue's "macro" menu.
|
||||
|
||||
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
|
||||
```
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
@@ -126,10 +148,27 @@ Enables device power control. Currently GPIO (relays), TPLink Smartplug,
|
||||
and Tasmota (via http) devices are supported.
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[power device_name]
|
||||
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
|
||||
@@ -139,6 +178,10 @@ pin: gpiochip0/gpio26
|
||||
# !gpiochip0/gpio26
|
||||
# !gpio26
|
||||
# This parameter must be provided for "gpio" type devices
|
||||
initial_state: off
|
||||
# The initial state for GPIO type devices. May be on or
|
||||
# off. When moonraker starts the device will be set to this
|
||||
# state. Default is off.
|
||||
address:
|
||||
port:
|
||||
# The above options are used for "tplink_smartplug" devices. The
|
||||
@@ -156,17 +199,38 @@ output_id:
|
||||
# If your single-relay Tasmota device switches on/off successfully,
|
||||
# but fails to report its state, ensure that 'SetOption26' is set in
|
||||
# Tasmota.
|
||||
address:
|
||||
user:
|
||||
password:
|
||||
output_id:
|
||||
# The above options are used for "shelly" devices. The
|
||||
# address should be a valid ip or hostname for the Shelly device.
|
||||
# Provide a user and password if configured in Shelly (default is empty).
|
||||
# If password is set but user is empty the default user "admin" will be used
|
||||
# Provided an output_id (relay id) if the Shelly device supports
|
||||
# more than one (default is 0).
|
||||
|
||||
|
||||
```
|
||||
Below are some potential examples:
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[power printer]
|
||||
type: gpio
|
||||
pin: gpio26
|
||||
off_when_shutdown: True
|
||||
initial_state: off
|
||||
|
||||
[power printer_led]
|
||||
type: gpio
|
||||
pin: !gpiochip0/gpio16
|
||||
initial_state: off
|
||||
|
||||
[power light_strip]
|
||||
type: gpio
|
||||
pin: gpiochip0/gpio17
|
||||
initial_state: on
|
||||
|
||||
[power wifi_switch]
|
||||
type: tplink_smartplug
|
||||
@@ -176,11 +240,19 @@ address: 192.168.1.123
|
||||
type: tasmota
|
||||
address: 192.168.1.124
|
||||
password: password1
|
||||
|
||||
[power shelly_plug]
|
||||
type: shelly
|
||||
address: 192.168.1.125
|
||||
user: user2
|
||||
password: password2
|
||||
```
|
||||
|
||||
It is possible to toggle device power from the Klippy host, this can be done
|
||||
with a gcode_macro, such as:
|
||||
```
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro POWER_OFF_PRINTER]
|
||||
gcode:
|
||||
{action_call_remote_method("set_device_power",
|
||||
@@ -191,6 +263,8 @@ The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
|
||||
This could be used in conjunction with Klipper's idle timeout to turn the
|
||||
printer off when idle with a configuration similar to that of below:
|
||||
```
|
||||
# printer.cfg
|
||||
|
||||
[delayed_gcode delayed_printer_off]
|
||||
initial_duration: 0.
|
||||
gcode:
|
||||
@@ -211,15 +285,80 @@ performed on pristine git repos. Repos that have been modified on
|
||||
disk or cloned from unofficial sources are not supported.
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager]
|
||||
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
|
||||
enable_repo_debug: False
|
||||
# When set to True moonraker will bypass repo validation and allow
|
||||
# updates from unofficial remotes and/or branches. Updates on
|
||||
# detached repos are also allowed. This option is intended for
|
||||
# developers and should not be used on production machines. The
|
||||
# default is False.
|
||||
enable_auto_refresh: False
|
||||
# When set to True Moonraker will attempt to fetch status about
|
||||
# available updates roughly every 24 hours, between 12am-4am.
|
||||
# When set to False Moonraker will only fetch update state on startup
|
||||
# and clients will need to request that Moonraker updates state. The
|
||||
# default is False.
|
||||
distro: debian
|
||||
# The disto in which moonraker has been installed. Currently the
|
||||
# update manager only supports "debian", which encompasses all of
|
||||
# its derivatives. The default is debain.
|
||||
```
|
||||
|
||||
### Client Configuration
|
||||
This allows client programs such as Fluidd, KlipperScreen, and Mainsail to be
|
||||
updated in addition to klipper, moonraker, and the system os. Repos that have
|
||||
been modified or cloned from unofficial sources are not supported.
|
||||
|
||||
There are two types of update manager clients and each will be detailed
|
||||
separately. The first one is targeted towards releases that do not need a
|
||||
service restart such as Fluidd/Mainsail.
|
||||
|
||||
```
|
||||
# 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
|
||||
```
|
||||
+60
-21
@@ -8,7 +8,8 @@ Python 3 packages meet this requirement.
|
||||
|
||||
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.
|
||||
for instructions on how to do this. After installation you should make
|
||||
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
|
||||
|
||||
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
|
||||
@@ -38,8 +39,27 @@ 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"
|
||||
```
|
||||
You may also want to take this opportunity to change the location of
|
||||
printer.cfg if you enable Moonraker's "config_path" option (see the
|
||||
[configuration section](#moonraker-configuration-moonrakerconf) for more information).
|
||||
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:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
|
||||
```
|
||||
|
||||
If necessary, create the config directory and move printer.cfg to it:
|
||||
```
|
||||
cd ~
|
||||
mkdir printer_config
|
||||
mv printer.cfg printer_config
|
||||
```
|
||||
|
||||
You can now install the Moonraker application:
|
||||
```
|
||||
@@ -47,12 +67,24 @@ cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
Finally, run moonraker's install script:
|
||||
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
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
Or to install with `moonraker.conf` in the `config_path`:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
|
||||
```
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
- -r\
|
||||
@@ -64,24 +96,21 @@ particularly for those upgrading:
|
||||
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".
|
||||
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: New connection established`
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
|
||||
|
||||
Now you may install a client, such as [Mainsail](
|
||||
https://github.com/meteyou/mainsail).
|
||||
- Note that as of the time of this writing (August 11 2020) the current version
|
||||
of Mainsail (0.1.2) is not compatible with this repo. Please give the
|
||||
developer some time to bring up Mainsail in line with the latest release
|
||||
of Moonraker.
|
||||
Now you may install a client, such as
|
||||
[Mainsail](https://github.com/meteyou/mainsail) or
|
||||
[Fluidd](https://github.com/cadriel/fluidd)
|
||||
|
||||
## Command line Usage
|
||||
The configuration and log file paths may be specified via the command
|
||||
line.
|
||||
```
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>]
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
@@ -91,14 +120,26 @@ optional arguments:
|
||||
Location of moonraker configuration file
|
||||
-l <logfile>, --logfile <logfile>
|
||||
log file name and location
|
||||
-n, --nologfile disable logging to a file
|
||||
```
|
||||
|
||||
The default configuration is:
|
||||
- config file - `~/moonraker.conf`
|
||||
- log file - `/tmp/moonraker.log`
|
||||
- config file path- `~/moonraker.conf`
|
||||
- log file path - `/tmp/moonraker.log`
|
||||
- logging to a file is enabled
|
||||
|
||||
It is recommended to use the defaults, however one may change these
|
||||
arguments by editing `/etc/default/moonraker`.
|
||||
If one needs to start moonraker without generating a log file, the
|
||||
'-n' option may be used, for example:
|
||||
```
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
|
||||
```
|
||||
In general it is not recommended to install moonraker with this option.
|
||||
While moonraker will still log to stdout, all requests for support must
|
||||
be accompanied by moonraker.log.
|
||||
|
||||
These options may be changed by editing
|
||||
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
|
||||
may also be used to modify the config file location.
|
||||
|
||||
## Prerequisites (Klipper Configuration)
|
||||
|
||||
@@ -120,10 +161,8 @@ missing one or both, you can simply add the bare sections to printer.cfg:
|
||||
path: ~/gcode_files
|
||||
```
|
||||
NOTES:
|
||||
- While Klipper does not set any hard limits on the location of the
|
||||
`path` option for the `virtual_sdcard`, Moonraker requires that the path
|
||||
be located within the HOME directory, it cannot however be the HOME
|
||||
directory. If you wish to host your files elsewhere, use a symlink.
|
||||
- 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.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Sample Moonraker Configuration File
|
||||
|
||||
[server]
|
||||
# Bind server defaults of 0.0.0.0, port 7125
|
||||
enable_debug_logging: True
|
||||
config_path: ~/printer_config
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
# Enter your client IP here or range here
|
||||
192.168.1.0/24
|
||||
cors_domains:
|
||||
# Allow CORS requests for Fluidd
|
||||
http://app.fluidd.xyz
|
||||
@@ -1,6 +1,26 @@
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
|
||||
### December 31st 2020
|
||||
- The file manager no longer restricts the `config_path` to a folder
|
||||
within the HOME directory. The path may not be the system root,
|
||||
however it can reside anywhere else on the file system as long as
|
||||
Moonraker has read and write access to the directory. This applies
|
||||
to gcode path received from Klipper via the `virtual_sdcard` section
|
||||
as well.
|
||||
|
||||
### December 6th 2020
|
||||
- Moonraker is now installed as a systemd service. This allows logging
|
||||
to stdout which can be viewed with the `journalctl -u moonraker` command.
|
||||
This changes requires the user to rerun the install script. If
|
||||
`moonraker.conf` is not located in the home directory, the command
|
||||
will looks something like the following:
|
||||
```
|
||||
cd ~/moonraker
|
||||
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
|
||||
```
|
||||
Otherwise you can run the install script with no arguments.
|
||||
|
||||
### November 19th 2020
|
||||
- The install script (`install-moonraker.sh`) now has command-line
|
||||
options:\
|
||||
|
||||
+110
-24
@@ -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`
|
||||
@@ -844,41 +864,81 @@ information.
|
||||
{
|
||||
'version_info': {
|
||||
'moonraker': {
|
||||
branch: <string>,
|
||||
remote_alias: <string>,
|
||||
version: <string>,
|
||||
remote_version: <string>,
|
||||
current_hash: <string>,
|
||||
remote_hash: <string>,
|
||||
is_valid: <bool>,
|
||||
is_dirty: <bool>
|
||||
is_dirty: <bool>,
|
||||
detached: <bool>,
|
||||
debug_enabled: <bool>
|
||||
},
|
||||
'klipper': {
|
||||
branch: <string>,
|
||||
remote_alias: <string>,
|
||||
version: <string>,
|
||||
remote_version: <string>,
|
||||
current_hash: <string>,
|
||||
remote_hash: <string>,
|
||||
is_valid: <bool>,
|
||||
is_dirty: <bool>
|
||||
}
|
||||
'client': {
|
||||
is_dirty: <bool>,
|
||||
detached: <bool>,
|
||||
debug_enabled: <bool>
|
||||
},
|
||||
'client_name_1': {
|
||||
name: <string>,
|
||||
version: <string>,
|
||||
remote_version: <string>
|
||||
},
|
||||
'system': {
|
||||
package_count: <int>,
|
||||
package_list: <array>
|
||||
}
|
||||
},
|
||||
busy: false
|
||||
busy: false,
|
||||
github_rate_limit: <int>,
|
||||
github_requests_remaining: <int>
|
||||
github_limit_reset_time: <int>,
|
||||
}
|
||||
```
|
||||
- The `busy` field is set to true if an update is in progress. Moonraker
|
||||
will not allow concurrent updates.
|
||||
- The `github_rate_limit` is the maximum number of github API requests
|
||||
the user currently has. An unathenticated user typically has 60
|
||||
requests per hour.
|
||||
- The `github_requests_remaining` is the number of API request the user
|
||||
currently has remaining.
|
||||
- The `github_limit_reset_time` is reported as seconds since the epoch.
|
||||
When this time is reached the user's limit will be reset.
|
||||
- The `moonraker` and `klipper` objects have the following fields:
|
||||
- `branch`: the name of the current git branch. This should typically
|
||||
be "master".
|
||||
- `remote_alias`: the alias for the remote. This should typically be
|
||||
"origin".
|
||||
- `version`: version of the current repo on disk
|
||||
- `remote_version`: version of the latest available update
|
||||
- `current_hash`: hash of the most recent commit on disk
|
||||
- `remote_hash`: hash of the most recent commit pushed to the remote
|
||||
- `is_valid`: True if installation is a valid git repo on the master branch
|
||||
and an "origin" set to the official remote
|
||||
- `is_dirty`: True if the repo has been modified
|
||||
- The `client` object has 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
|
||||
- `detached`: True if the repo is currently in a detached state
|
||||
- `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".
|
||||
- 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
|
||||
for update
|
||||
|
||||
### Update Moonraker
|
||||
Pulls the most recent version of Moonraker from GitHub and restarts
|
||||
@@ -886,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`
|
||||
@@ -909,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`
|
||||
@@ -927,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`
|
||||
@@ -1067,6 +1134,11 @@ Notify clients when Klippy has reported a ready state
|
||||
|
||||
`{jsonrpc: "2.0", method: "notify_klippy_ready"}`
|
||||
|
||||
### Klippy Shutdown:
|
||||
Notify clients when Klippy has reported a shutdown state
|
||||
|
||||
`{jsonrpc: "2.0", method: "notify_klippy_shutdown"}`
|
||||
|
||||
### Klippy Disconnected:
|
||||
Notify clients when Moonraker's connection to Klippy has terminated
|
||||
|
||||
@@ -1159,7 +1231,8 @@ Where `response` is an object int he following format:
|
||||
{
|
||||
application: <string>,
|
||||
proc_id: <int>,
|
||||
message: <string>
|
||||
message: <string>,
|
||||
complete: <boolean>
|
||||
}
|
||||
```
|
||||
- The `application` field contains the name of application currently being
|
||||
@@ -1169,6 +1242,19 @@ Where `response` is an object int he following format:
|
||||
process. This id is generated for each update request.
|
||||
- The `message` field contains an asyncronous message sent during the update
|
||||
process.
|
||||
- The `complete` field is set to true on the final message sent during an
|
||||
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
|
||||
|
||||
|
||||
+9
-4
@@ -24,6 +24,7 @@ RESERVED_ENDPOINTS = [
|
||||
]
|
||||
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
|
||||
|
||||
# Status objects require special parsing
|
||||
def _status_parser(request_handler):
|
||||
@@ -130,7 +131,11 @@ class MoonrakerApp:
|
||||
|
||||
# Register handlers
|
||||
logfile = config['system_args'].get('logfile')
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
if logfile:
|
||||
self.register_static_file_handler(
|
||||
"moonraker.log", logfile, force=True)
|
||||
self.register_static_file_handler(
|
||||
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
|
||||
self.auth.register_handlers(self)
|
||||
|
||||
def listen(self, host, port):
|
||||
@@ -193,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] != "/":
|
||||
@@ -329,7 +334,7 @@ class FileRequestHandler(AuthorizedFileHandler):
|
||||
|
||||
async def delete(self, path):
|
||||
path = self.request.path.lstrip("/").split("/", 2)[-1]
|
||||
path = url_unescape(path)
|
||||
path = url_unescape(path, plus=False)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
try:
|
||||
filename = await file_manager.delete_file(path)
|
||||
|
||||
@@ -15,10 +15,12 @@ class Sentinel:
|
||||
|
||||
class ConfigHelper:
|
||||
error = ConfigError
|
||||
def __init__(self, server, config, section):
|
||||
def __init__(self, server, config, section, orig_sects, parsed={}):
|
||||
self.server = server
|
||||
self.config = config
|
||||
self.section = section
|
||||
self.orig_sections = orig_sects
|
||||
self.parsed = parsed
|
||||
self.sections = config.sections
|
||||
self.has_section = config.has_section
|
||||
|
||||
@@ -34,13 +36,17 @@ class ConfigHelper:
|
||||
def get_name(self):
|
||||
return self.section
|
||||
|
||||
def get_options(self):
|
||||
return dict(self.config[self.section])
|
||||
|
||||
def get_prefix_sections(self, prefix):
|
||||
return [s for s in self.sections() if s.startswith(prefix)]
|
||||
|
||||
def getsection(self, section):
|
||||
if section not in self.config:
|
||||
raise ConfigError(f"No section [{section}] in config")
|
||||
return ConfigHelper(self.server, self.config, section)
|
||||
return ConfigHelper(self.server, self.config, section,
|
||||
self.orig_sections, self.parsed)
|
||||
|
||||
def _get_option(self, func, option, default):
|
||||
try:
|
||||
@@ -52,6 +58,9 @@ class ConfigHelper:
|
||||
if val == Sentinel:
|
||||
raise ConfigError(
|
||||
f"No option found ({option}) in section [{self.section}]")
|
||||
if self.section in self.orig_sections:
|
||||
# Only track sections included in the original config
|
||||
self.parsed.setdefault(self.section, {})[option] = val
|
||||
return val
|
||||
|
||||
def get(self, option, default=Sentinel):
|
||||
@@ -67,9 +76,40 @@ 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):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
|
||||
if not os.path.isfile(cfg_file_path):
|
||||
raise ConfigError(
|
||||
f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
try:
|
||||
self.config.read(cfg_file_path)
|
||||
except Exception:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
|
||||
|
||||
def write_config(self, file_obj):
|
||||
self.config.write(file_obj)
|
||||
|
||||
def get_parsed_config(self):
|
||||
return dict(self.parsed)
|
||||
|
||||
def validate_config(self):
|
||||
for sect in self.orig_sections:
|
||||
if sect not in self.parsed:
|
||||
logging.warn(
|
||||
f"Invalid config section [{sect}] detected. In "
|
||||
"the future this will result in a startup error")
|
||||
continue
|
||||
parsed_opts = self.parsed[sect]
|
||||
for opt, val in self.config.items(sect):
|
||||
if opt not in parsed_opts:
|
||||
logging.warn(
|
||||
f"Invalid option '{opt}' detected in section "
|
||||
f"[{sect}]. In the future this will result in a "
|
||||
"startup error.")
|
||||
|
||||
def get_configuration(server, system_args):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(
|
||||
system_args.configfile))
|
||||
@@ -86,10 +126,17 @@ def get_configuration(server, system_args):
|
||||
except KeyError:
|
||||
raise ConfigError("No section [server] in config")
|
||||
|
||||
if server_cfg.get('enable_debug_logging', True):
|
||||
orig_sections = config.sections()
|
||||
try:
|
||||
orig_sections.remove("DEFAULT")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if server_cfg.getboolean('enable_debug_logging', True):
|
||||
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')
|
||||
return ConfigHelper(server, config, 'server', orig_sections)
|
||||
Regular → Executable
+55
-9
@@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
@@ -7,6 +8,7 @@ import argparse
|
||||
import sys
|
||||
import importlib
|
||||
import os
|
||||
import io
|
||||
import time
|
||||
import socket
|
||||
import logging
|
||||
@@ -34,8 +36,17 @@ class Sentinel:
|
||||
|
||||
class Server:
|
||||
error = ServerError
|
||||
def __init__(self, args):
|
||||
config = confighelper.get_configuration(self, args)
|
||||
def __init__(self, args, file_logger):
|
||||
self.file_logger = file_logger
|
||||
self.config = 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)
|
||||
|
||||
@@ -53,6 +64,7 @@ class Server:
|
||||
self.init_attempts = 0
|
||||
self.klippy_state = "disconnected"
|
||||
self.subscriptions = {}
|
||||
self.failed_plugins = []
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
@@ -64,6 +76,8 @@ class Server:
|
||||
|
||||
self.register_endpoint(
|
||||
"/server/info", ['GET'], self._handle_info_request)
|
||||
self.register_endpoint(
|
||||
"/server/config", ['GET'], self._handle_config_request)
|
||||
self.register_endpoint(
|
||||
"/server/restart", ['POST'], self._handle_server_restart)
|
||||
|
||||
@@ -84,6 +98,7 @@ class Server:
|
||||
self.plugins = {}
|
||||
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
|
||||
self._load_plugins(config)
|
||||
config.validate_config()
|
||||
|
||||
def start(self):
|
||||
hostname, hostport = self.get_host_info()
|
||||
@@ -94,6 +109,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
|
||||
@@ -115,11 +136,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"
|
||||
@@ -130,6 +152,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
|
||||
@@ -285,10 +308,11 @@ class Server:
|
||||
f"Klippy may have experienced an error during startup.\n"
|
||||
f"Please check klippy.log for more information")
|
||||
return
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
self.klippy_info = dict(result)
|
||||
self.klippy_state = result.get('state', "unknown")
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
self.send_event("server:klippy_identified")
|
||||
if self.klippy_state == "ready":
|
||||
await self._verify_klippy_requirements()
|
||||
logging.info("Klippy ready")
|
||||
@@ -366,6 +390,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):
|
||||
@@ -443,10 +471,21 @@ 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}
|
||||
|
||||
async def _handle_config_request(self, web_request):
|
||||
return {
|
||||
'config': self.config.get_parsed_config()
|
||||
}
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, on_recd, on_close):
|
||||
@@ -549,14 +588,21 @@ def main():
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
parser.add_argument(
|
||||
"-n", "--nologfile", action='store_true',
|
||||
help="disable logging to a file")
|
||||
system_args = parser.parse_args()
|
||||
|
||||
# Setup Logging
|
||||
version = utils.get_software_version()
|
||||
log_file = os.path.normpath(os.path.expanduser(system_args.logfile))
|
||||
if system_args.nologfile:
|
||||
log_file = ""
|
||||
else:
|
||||
log_file = os.path.normpath(os.path.expanduser(
|
||||
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. " \
|
||||
@@ -571,7 +617,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
|
||||
|
||||
@@ -9,17 +9,16 @@ from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
TEMPERATURE_UPDATE_MS = 1000
|
||||
TEMPERATURE_STORE_SIZE = 20 * 60
|
||||
|
||||
MAX_GCODE_LINES = 1000
|
||||
|
||||
class DataStore:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.temp_store_size = config.getint('temperature_store_size', 1200)
|
||||
self.gcode_store_size = config.getint('gcode_store_size', 1000)
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps = {}
|
||||
self.gcode_queue = deque(maxlen=MAX_GCODE_LINES)
|
||||
self.gcode_queue = deque(maxlen=self.gcode_store_size)
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
@@ -61,14 +60,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=self.temp_store_size)}
|
||||
for item in ["target", "power", "speed"]:
|
||||
if item in fields:
|
||||
new_store[sensor][f"{item}s"] = deque(
|
||||
maxlen=self.temp_store_size)
|
||||
if sensor not in self.last_temps:
|
||||
self.last_temps[sensor] = (0., 0.)
|
||||
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 +89,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 +116,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)
|
||||
@@ -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:
|
||||
@@ -45,7 +45,7 @@ class FileManager:
|
||||
self.server.register_upload_handler("/api/files/local")
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._update_fixed_paths)
|
||||
"server:klippy_identified", self._update_fixed_paths)
|
||||
|
||||
# Register Klippy Configuration Path
|
||||
config_path = config.get('config_path', None)
|
||||
@@ -77,20 +77,29 @@ 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
|
||||
home = os.path.expanduser('~')
|
||||
path = os.path.normpath(os.path.expanduser(path))
|
||||
if not os.path.isdir(path) or not path.startswith(home) or \
|
||||
path == home:
|
||||
path = os.path.abspath(os.path.expanduser(path))
|
||||
if os.path.islink(path):
|
||||
path = os.path.realpath(path)
|
||||
if not os.path.isdir(path) or path == "/":
|
||||
logging.info(
|
||||
f"\nSupplied path ({path}) for ({root}) not valid. Please\n"
|
||||
"check that the path exists and is a subfolder in the HOME\n"
|
||||
"directory. Note that the path may not BE the home directory.")
|
||||
f"\nSupplied path ({path}) for ({root}) a valid. Make sure\n"
|
||||
"that the path exists and is not the file system root.")
|
||||
return False
|
||||
permissions = os.R_OK
|
||||
if root in FULL_ACCESS_ROOTS:
|
||||
permissions |= os.W_OK
|
||||
if not os.access(path, permissions):
|
||||
logging.info(
|
||||
f"\nMoonraker does not have permission to access path "
|
||||
f"({path}) for ({root}).")
|
||||
return False
|
||||
if path != self.file_paths.get(root, ""):
|
||||
self.file_paths[root] = path
|
||||
@@ -108,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)
|
||||
|
||||
@@ -131,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
|
||||
@@ -264,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):
|
||||
@@ -373,11 +399,10 @@ class FileManager:
|
||||
full_path = root_path
|
||||
dir_path = ""
|
||||
else:
|
||||
parts = os.path.split(upload['filename'].strip().lstrip("/"))
|
||||
filename = os.path.join(parts[0], "_".join(parts[1].split()))
|
||||
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(
|
||||
@@ -439,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 = {}
|
||||
@@ -448,12 +486,30 @@ class FileManager:
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info(f"Updating File List <{root}>...")
|
||||
for root_path, dirs, files in os.walk(path, followlinks=True):
|
||||
st = os.stat(path)
|
||||
visited_dirs = {(st.st_dev, st.st_ino)}
|
||||
for dir_path, dir_names, files in os.walk(path, followlinks=True):
|
||||
scan_dirs = []
|
||||
# Filter out directories that have already been visted. This
|
||||
# prevents infinite recrusion "followlinks" is set to True
|
||||
for dname in dir_names:
|
||||
st = os.stat(os.path.join(dir_path, dname))
|
||||
key = (st.st_dev, st.st_ino)
|
||||
if key not in visited_dirs:
|
||||
visited_dirs.add(key)
|
||||
scan_dirs.append(dname)
|
||||
dir_names[:] = scan_dirs
|
||||
for name in files:
|
||||
ext = os.path.splitext(name)[-1].lower()
|
||||
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root_path, name)
|
||||
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
|
||||
@@ -478,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)
|
||||
@@ -653,13 +707,16 @@ class MetadataStorage:
|
||||
self.busy = False
|
||||
|
||||
async def _run_extract_metadata(self, filename, notify):
|
||||
# Escape single quotes in the file name so that it may be
|
||||
# properly loaded
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
self.gc_path, "-f", "'" + filename + "'"])
|
||||
self.gc_path, "-f", f"\"{filename}\""])
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
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']
|
||||
|
||||
@@ -80,6 +80,8 @@ class KlippyAPI:
|
||||
# XXX - validate that file is on disk
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
|
||||
return await self.run_gcode(script)
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
+150
-91
@@ -9,13 +9,14 @@ 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 tornado.locks import Lock
|
||||
|
||||
MIN_EST_TIME = 10.
|
||||
INITIALIZE_TIMEOUT = 10.
|
||||
|
||||
class PanelDueError(ServerError):
|
||||
pass
|
||||
@@ -29,13 +30,15 @@ class SerialConnection:
|
||||
self.paneldue = paneldue
|
||||
self.port = config.get('serial')
|
||||
self.baud = config.getint('baud', 57600)
|
||||
self.sendlock = Lock()
|
||||
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):
|
||||
def disconnect(self, reconnect=False):
|
||||
if self.connected:
|
||||
if self.fd is not None:
|
||||
self.ioloop.remove_handler(self.fd)
|
||||
@@ -43,7 +46,13 @@ class SerialConnection:
|
||||
self.connected = False
|
||||
self.ser.close()
|
||||
self.ser = None
|
||||
self.partial_input = b""
|
||||
self.send_buffer = b""
|
||||
self.paneldue.initialized = False
|
||||
logging.info("PanelDue Disconnected")
|
||||
if reconnect and not self.attempting_connect:
|
||||
self.attempting_connect = True
|
||||
self.ioloop.call_later(1., self._connect)
|
||||
|
||||
async def _connect(self):
|
||||
start_time = connect_time = time.time()
|
||||
@@ -69,11 +78,12 @@ class SerialConnection:
|
||||
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
|
||||
self.connected = True
|
||||
logging.info("PanelDue Connected")
|
||||
self.attempting_connect = False
|
||||
|
||||
def _handle_incoming(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
logging.info("PanelDue Connection Error")
|
||||
self.disconnect()
|
||||
self.disconnect(reconnect=True)
|
||||
return
|
||||
# Process incoming data using same method as gcode.py
|
||||
try:
|
||||
@@ -83,55 +93,56 @@ class SerialConnection:
|
||||
|
||||
if not data:
|
||||
# possibly an error, disconnect
|
||||
self.disconnect()
|
||||
self.disconnect(reconnect=True)
|
||||
logging.info("serial_display: No data received, disconnecting")
|
||||
return
|
||||
self.ioloop.spawn_callback(self._process_data, data)
|
||||
|
||||
async def _process_data(self, data):
|
||||
# Remove null bytes, separate into lines
|
||||
data = data.strip(b'\x00')
|
||||
lines = data.split(b'\n')
|
||||
lines[0] = self.partial_input + lines[0]
|
||||
self.partial_input = lines.pop()
|
||||
for line in lines:
|
||||
line = line.strip().decode()
|
||||
try:
|
||||
await self.paneldue.process_line(line)
|
||||
line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(line)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
"GCode Processing Error: " + line)
|
||||
f"GCode Processing Error: {line}")
|
||||
self.paneldue.handle_gcode_response(
|
||||
"!! GCode Processing Error: " + line)
|
||||
f"!! GCode Processing Error: {line}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
|
||||
async def send(self, data):
|
||||
if self.connected:
|
||||
async with self.sendlock:
|
||||
while data:
|
||||
try:
|
||||
sent = os.write(self.fd, data)
|
||||
except os.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
|
||||
sent = 0
|
||||
else:
|
||||
await gen.sleep(.001)
|
||||
continue
|
||||
if sent:
|
||||
data = data[sent:]
|
||||
else:
|
||||
logging.exception(
|
||||
"Error writing data, closing serial connection")
|
||||
self.disconnect()
|
||||
return
|
||||
def send(self, data):
|
||||
self.send_buffer += data
|
||||
if not self.send_busy:
|
||||
self.send_busy = True
|
||||
self.ioloop.spawn_callback(self._do_send)
|
||||
|
||||
async def _do_send(self):
|
||||
while self.send_buffer:
|
||||
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):
|
||||
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"
|
||||
@@ -153,7 +164,12 @@ class PanelDue:
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
self.last_printer_state = 'C'
|
||||
self.initialized = False
|
||||
self.cq_busy = self.gq_busy = False
|
||||
self.command_queue = []
|
||||
self.gc_queue = []
|
||||
self.last_printer_state = 'O'
|
||||
self.last_update_time = 0.
|
||||
|
||||
# Set up macros
|
||||
self.confirmed_gcode = ""
|
||||
@@ -178,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
|
||||
@@ -277,31 +294,32 @@ class PanelDue:
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
async def _process_klippy_shutdown(self):
|
||||
def _process_klippy_shutdown(self):
|
||||
self.is_shutdown = True
|
||||
|
||||
async def _process_klippy_disconnect(self):
|
||||
# Tell the PD that we are shutting down
|
||||
await self.write_response({'status': 'S'})
|
||||
self.is_ready = False
|
||||
def _process_klippy_disconnect(self):
|
||||
# Tell the PD that the printer is "off"
|
||||
self.write_response({'status': 'O'})
|
||||
self.last_printer_state = 'O'
|
||||
self.is_shutdown = self.is_shutdown = False
|
||||
|
||||
async def handle_status_update(self, status):
|
||||
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
|
||||
|
||||
async def paneldue_beep(self, frequency, duration):
|
||||
def paneldue_beep(self, frequency, duration):
|
||||
duration = int(duration * 1000.)
|
||||
await self.write_response(
|
||||
self.write_response(
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
async def process_line(self, line):
|
||||
def process_line(self, line):
|
||||
self.debug_queue.append(line)
|
||||
# If we find M112 in the line then skip verification
|
||||
if "M112" in line.upper():
|
||||
await self.klippy_apis.emergency_stop()
|
||||
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
|
||||
return
|
||||
|
||||
if self.enable_checksum:
|
||||
@@ -337,31 +355,36 @@ class PanelDue:
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
await self._run_gcode(line[line_index+1:cs_index])
|
||||
script = line[line_index+1:cs_index]
|
||||
else:
|
||||
await self._run_gcode(line)
|
||||
|
||||
async def _run_gcode(self, script):
|
||||
script = line
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
# require special handling
|
||||
parts = script.split()
|
||||
cmd = parts[0].strip()
|
||||
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
|
||||
arg = script[len(cmd):].strip()
|
||||
parts = [cmd, arg]
|
||||
|
||||
# Check for commands that query state and require immediate response
|
||||
if cmd in self.direct_gcodes:
|
||||
params = {}
|
||||
for p in parts[1:]:
|
||||
arg = p[0].lower() if p[0].lower() in "psr" else "p"
|
||||
if p[0] not in "PSR":
|
||||
params["arg_p"] = p.strip(" \"\t\n")
|
||||
continue
|
||||
arg = p[0].lower()
|
||||
try:
|
||||
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
|
||||
val = int(p[1:].strip()) if arg in "sr" \
|
||||
else p[1:].strip(" \"\t\n")
|
||||
except Exception:
|
||||
msg = f"paneldue: Error parsing direct gcode {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
return
|
||||
params["arg_" + arg] = val
|
||||
params[f"arg_{arg}"] = val
|
||||
func = self.direct_gcodes[cmd]
|
||||
await func(**params)
|
||||
self.queue_command(func, **params)
|
||||
return
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
@@ -371,18 +394,48 @@ class PanelDue:
|
||||
|
||||
if not script:
|
||||
return
|
||||
elif script in RESTART_GCODES:
|
||||
await self.klippy_apis.do_restart(script)
|
||||
return
|
||||
self.queue_gcode(script)
|
||||
|
||||
try:
|
||||
await self.klippy_apis.run_gcode(script)
|
||||
except self.server.error:
|
||||
msg = f"Error executing script {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
def queue_gcode(self, script):
|
||||
self.gc_queue.append(script)
|
||||
if not self.gq_busy:
|
||||
self.gq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_gcode_queue)
|
||||
|
||||
async def _process_gcode_queue(self):
|
||||
while self.gc_queue:
|
||||
script = self.gc_queue.pop(0)
|
||||
try:
|
||||
if script in RESTART_GCODES:
|
||||
await self.klippy_apis.do_restart(script)
|
||||
else:
|
||||
await self.klippy_apis.run_gcode(script)
|
||||
except self.server.error:
|
||||
msg = f"Error executing script {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
self.gq_busy = False
|
||||
|
||||
def queue_command(self, cmd, *args, **kwargs):
|
||||
self.command_queue.append((cmd, args, kwargs))
|
||||
if not self.cq_busy:
|
||||
self.cq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_command_queue)
|
||||
|
||||
async def _process_command_queue(self):
|
||||
while self.command_queue:
|
||||
cmd, args, kwargs = self.command_queue.pop(0)
|
||||
try:
|
||||
ret = cmd(*args, **kwargs)
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception("Error processing command")
|
||||
self.cq_busy = False
|
||||
|
||||
def _clean_filename(self, filename):
|
||||
# Remove quotes and whitespace
|
||||
filename.strip(" \"\t\n")
|
||||
# Remove drive number
|
||||
if filename.startswith("0:/"):
|
||||
filename = filename[3:]
|
||||
@@ -399,15 +452,17 @@ class PanelDue:
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "M23 " + filename
|
||||
filename = self._clean_filename(args[0])
|
||||
return f"M23 {filename}"
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "SDCARD_PRINT_FILE FILENAME=" + filename
|
||||
filename = self._clean_filename(args[0])
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
|
||||
|
||||
def _prepare_M98(self, args):
|
||||
macro = args[0][1:].strip()
|
||||
macro = args[0][1:].strip(" \"\t\n")
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
cmd = self.available_macros.get(macro)
|
||||
@@ -444,7 +499,8 @@ class PanelDue:
|
||||
mbox['msgBox.title'] = title
|
||||
mbox['msgBox.controls'] = 0
|
||||
mbox['msgBox.timeout'] = 0
|
||||
self.ioloop.spawn_callback(self.write_response, mbox)
|
||||
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
|
||||
self.write_response(mbox)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
@@ -458,9 +514,9 @@ class PanelDue:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
async def write_response(self, response):
|
||||
def write_response(self, response):
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
await self.ser_conn.send(byte_resp.encode())
|
||||
self.ser_conn.send(byte_resp.encode())
|
||||
|
||||
def _get_printer_status(self):
|
||||
# PanelDue States applicable to Klipper:
|
||||
@@ -471,8 +527,6 @@ class PanelDue:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
p_busy = printer_state['idle_timeout'].get(
|
||||
'state', 'Idle') == "Printing"
|
||||
sd_state = printer_state['print_stats'].get('state', "standby")
|
||||
if sd_state == "printing":
|
||||
if self.last_printer_state == 'A':
|
||||
@@ -481,37 +535,41 @@ class PanelDue:
|
||||
# Printing
|
||||
return 'P'
|
||||
elif sd_state == "paused":
|
||||
if p_busy and self.last_printer_state != 'A':
|
||||
p_active = printer_state['idle_timeout'].get(
|
||||
'state', 'Idle') == "Printing"
|
||||
if p_active and self.last_printer_state != 'A':
|
||||
# Pausing
|
||||
return 'D'
|
||||
else:
|
||||
# Paused
|
||||
return 'A'
|
||||
|
||||
if p_busy:
|
||||
# Printer is "busy"
|
||||
return 'B'
|
||||
|
||||
return 'I'
|
||||
|
||||
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
response = {}
|
||||
sequence = arg_r
|
||||
response_type = arg_s
|
||||
|
||||
if not self.is_ready:
|
||||
# Klipper is still starting up, do not query status
|
||||
self.last_printer_state = 'S' if self.is_shutdown else 'C'
|
||||
response['status'] = self.last_printer_state
|
||||
await self.write_response(response)
|
||||
return
|
||||
curtime = self.ioloop.time()
|
||||
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
|
||||
self.initialized = False
|
||||
self.last_update_time = curtime
|
||||
|
||||
# Send gcode responses
|
||||
if not self.initialized:
|
||||
response['dir'] = "/macros"
|
||||
response['files'] = list(self.available_macros.keys())
|
||||
self.initialized = True
|
||||
if not self.is_ready:
|
||||
self.last_printer_state = 'O'
|
||||
response['status'] = self.last_printer_state
|
||||
self.write_response(response)
|
||||
return
|
||||
if sequence is not None and self.last_gcode_response:
|
||||
# Send gcode responses
|
||||
response['seq'] = sequence + 1
|
||||
response['resp'] = self.last_gcode_response
|
||||
self.last_gcode_response = None
|
||||
|
||||
if response_type == 1:
|
||||
# Extended response Request
|
||||
response['myName'] = self.machine_name
|
||||
@@ -611,9 +669,9 @@ class PanelDue:
|
||||
# is strange about this, and displays it as a full screen
|
||||
# notification
|
||||
self.last_message = msg
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
@@ -651,7 +709,7 @@ class PanelDue:
|
||||
flist = self.file_manager.list_dir(path, simple_format=True)
|
||||
if flist:
|
||||
response['files'] = flist
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p=None):
|
||||
# Delete a file. Clean up the file name and make sure
|
||||
@@ -667,7 +725,7 @@ class PanelDue:
|
||||
path = "gcodes/" + path
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
async def _run_paneldue_M36(self, arg_p=None):
|
||||
def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
@@ -682,16 +740,17 @@ class PanelDue:
|
||||
if not filename or not active:
|
||||
# Either no file printing or no virtual_sdcard
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
return
|
||||
else:
|
||||
response['fileName'] = filename.split("/")[-1]
|
||||
|
||||
|
||||
# For consistency make sure that the filename begins with the
|
||||
# "gcodes/" root. The M20 HACK should add this in some cases.
|
||||
# Ideally we would add support to the PanelDue firmware that
|
||||
# indicates Moonraker supports a "gcodes" directory.
|
||||
if filename[0] == "/":
|
||||
filename = filename[1:]
|
||||
if not filename.startswith("gcodes/"):
|
||||
filename = "gcodes/" + filename
|
||||
|
||||
@@ -718,9 +777,9 @@ class PanelDue:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def close(self):
|
||||
def close(self):
|
||||
self.ser_conn.disconnect()
|
||||
msg = "\nPanelDue GCode Dump:"
|
||||
for i, gc in enumerate(self.debug_queue):
|
||||
|
||||
+176
-57
@@ -20,6 +20,29 @@ 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)
|
||||
elif dev_type == "shelly":
|
||||
dev = Shelly(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 +57,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 +106,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 +166,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 +220,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,7 +240,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")
|
||||
self.set_power("off")
|
||||
self.initial_state = config.getboolean('initial_state', False)
|
||||
|
||||
def _parse_pin(self, config):
|
||||
pin = cfg_pin = config.get("pin")
|
||||
@@ -189,15 +265,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"
|
||||
}
|
||||
|
||||
@@ -231,18 +303,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 = {}
|
||||
@@ -299,13 +366,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"
|
||||
}
|
||||
|
||||
@@ -334,28 +397,24 @@ 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"]:
|
||||
out_cmd = f"Power{self.output_id}%20{command}"
|
||||
elif command == "info":
|
||||
out_cmd = "Power{self.output_id}"
|
||||
out_cmd = f"Power{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid tasmota command: {command}")
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password=" \
|
||||
f"{self.password}&cmnd={out_cmd}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
@@ -370,13 +429,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"
|
||||
}
|
||||
|
||||
@@ -402,6 +457,70 @@ class Tasmota:
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
|
||||
class Shelly(PowerDevice):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.server = config.get_server()
|
||||
self.addr = config.get("address")
|
||||
self.output_id = config.getint("output_id", 0)
|
||||
self.user = config.get("user", "admin")
|
||||
self.password = config.get("password", "")
|
||||
|
||||
async def _send_shelly_command(self, command):
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = f"relay/{self.output_id}?turn={command}"
|
||||
elif command == "info":
|
||||
out_cmd = f"relay/{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid shelly command: {command}")
|
||||
if self.password != "":
|
||||
out_pwd = f"{self.user}:{self.password}@"
|
||||
else:
|
||||
out_pwd = f""
|
||||
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
response = await http_client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending shelly command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
**super().get_device_info(),
|
||||
'type': "shelly"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_shelly_command("info")
|
||||
state = res[f"ison"]
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_shelly_command(state)
|
||||
state = res[f"ison"]
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Setting Device Status: {self.name} to {state}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
# The power plugin has multiple configuration sections
|
||||
def load_plugin_multi(config):
|
||||
return PrinterPower(config)
|
||||
@@ -7,7 +7,6 @@ import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import logging
|
||||
import tornado
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
@@ -20,6 +19,7 @@ class ShellCommand:
|
||||
self.command = shlex.split(cmd)
|
||||
self.partial_output = b""
|
||||
self.cancelled = False
|
||||
self.return_code = None
|
||||
|
||||
def _process_output(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
@@ -40,8 +40,13 @@ class ShellCommand:
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
def get_return_code(self):
|
||||
return self.return_code
|
||||
|
||||
async def run(self, timeout=2., verbose=True):
|
||||
fd = None
|
||||
self.return_code = fd = None
|
||||
self.partial_output = b""
|
||||
self.cancelled = False
|
||||
if timeout is None:
|
||||
# Never timeout
|
||||
timeout = 9999999999999999.
|
||||
@@ -55,7 +60,7 @@ class ShellCommand:
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
return
|
||||
return False
|
||||
if verbose:
|
||||
fd = proc.stdout.fileno()
|
||||
self.io_loop.add_handler(
|
||||
@@ -79,17 +84,22 @@ class ShellCommand:
|
||||
if self.partial_output:
|
||||
self.output_cb(self.partial_output)
|
||||
self.partial_output = b""
|
||||
if complete:
|
||||
msg = f"Command ({self.name}) finished"
|
||||
elif self.cancelled:
|
||||
msg = f"Command ({self.name}) cancelled"
|
||||
else:
|
||||
msg = f"Command ({self.name}) timed out"
|
||||
logging.info(msg)
|
||||
self.io_loop.remove_handler(fd)
|
||||
return complete
|
||||
self.return_code = proc.returncode
|
||||
success = self.return_code == 0 and complete
|
||||
if success:
|
||||
msg = f"Command ({self.name}) successfully finished"
|
||||
elif self.cancelled:
|
||||
msg = f"Command ({self.name}) cancelled"
|
||||
elif not complete:
|
||||
msg = f"Command ({self.name}) timed out"
|
||||
else:
|
||||
msg = f"Command ({self.name}) exited with return code" \
|
||||
f" {self.return_code}"
|
||||
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):
|
||||
@@ -98,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)
|
||||
|
||||
|
||||
+662
-167
File diff suppressed because it is too large.
Load diff
+30
-12
@@ -6,6 +6,7 @@
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
from queue import SimpleQueue as Queue
|
||||
@@ -27,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.
|
||||
@@ -73,11 +81,21 @@ def setup_logging(log_file, software_version):
|
||||
queue_handler = LocalQueueHandler(queue)
|
||||
root_logger.addHandler(queue_handler)
|
||||
root_logger.setLevel(logging.INFO)
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
software_version, log_file, when='midnight', backupCount=2)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
listener = logging.handlers.QueueListener(queue, file_hdlr)
|
||||
stdout_hdlr = logging.StreamHandler(sys.stdout)
|
||||
stdout_fmt = logging.Formatter(
|
||||
'[%(filename)s:%(funcName)s()] - %(message)s')
|
||||
stdout_hdlr.setFormatter(stdout_fmt)
|
||||
file_hdlr = None
|
||||
if log_file:
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
software_version, log_file, when='midnight', backupCount=2)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
listener = logging.handlers.QueueListener(
|
||||
queue, file_hdlr, stdout_hdlr)
|
||||
else:
|
||||
listener = logging.handlers.QueueListener(
|
||||
queue, stdout_hdlr)
|
||||
listener.start()
|
||||
return listener
|
||||
return listener, file_hdlr
|
||||
+16
-3
@@ -172,6 +172,8 @@ class WebsocketManager:
|
||||
# Register events
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._handle_klippy_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_klippy_shutdown)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._handle_klippy_disconnect)
|
||||
self.server.register_event_handler(
|
||||
@@ -184,10 +186,15 @@ 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")
|
||||
|
||||
async def _handle_klippy_shutdown(self):
|
||||
await self.notify_websockets("klippy_shutdown")
|
||||
|
||||
async def _handle_klippy_disconnect(self):
|
||||
await self.notify_websockets("klippy_disconnected")
|
||||
|
||||
@@ -206,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):
|
||||
@@ -266,6 +276,7 @@ class WebsocketManager:
|
||||
ws.write_message(msg)
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(ws.uid, None)
|
||||
self.server.remove_subscription(ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
@@ -284,6 +295,7 @@ class WebSocket(WebSocketHandler):
|
||||
self.wsm = app.get_websocket_manager()
|
||||
self.rpc = self.wsm.rpc
|
||||
self.uid = id(self)
|
||||
self.is_closed = False
|
||||
|
||||
async def open(self):
|
||||
await self.wsm.add_websocket(self)
|
||||
@@ -301,7 +313,7 @@ class WebSocket(WebSocketHandler):
|
||||
logging.exception("Websocket Command Error")
|
||||
|
||||
def send_status(self, status):
|
||||
if not status:
|
||||
if not status or self.is_closed:
|
||||
return
|
||||
try:
|
||||
self.write_message({
|
||||
@@ -309,8 +321,9 @@ class WebSocket(WebSocketHandler):
|
||||
'method': "notify_status_update",
|
||||
'params': [status]})
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(self.uid, None)
|
||||
logging.info(f"Websocket Removed: {self.uid}")
|
||||
self.is_closed = True
|
||||
logging.info(
|
||||
f"Websocket Closed During Status Update: {self.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {self.uid}")
|
||||
|
||||
@@ -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(
|
||||
@@ -259,7 +271,7 @@ class SuperSlicer(PrusaSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
class Cura(BaseSlicer):
|
||||
class Cura(PrusaSlicer):
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Cura_SteamEngine\s(.*)", data)
|
||||
if match:
|
||||
@@ -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)
|
||||
@@ -298,6 +311,11 @@ class Cura(BaseSlicer):
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
# Attempt to parse thumbnails from file metadata
|
||||
thumbs = super().parse_thumbnails()
|
||||
if thumbs is not None:
|
||||
return thumbs
|
||||
# Check for thumbnails extracted from the ufp
|
||||
thumbName = os.path.splitext(
|
||||
os.path.basename(self.path))[0] + ".png"
|
||||
thumbPath = os.path.join(
|
||||
@@ -345,8 +363,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 +432,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 +486,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 +529,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 +552,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']
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# Raspbian/Raspberry Pi OS based distributions.
|
||||
|
||||
PYTHONDIR="${HOME}/moonraker-env"
|
||||
SYSTEMDDIR="/etc/systemd/system"
|
||||
REBUILD_ENV="n"
|
||||
FORCE_DEFAULTS="n"
|
||||
CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
@@ -19,7 +20,19 @@ check_klipper()
|
||||
|
||||
}
|
||||
|
||||
# Step 2: Install packages
|
||||
# Step 2: Clean up legacy installation
|
||||
cleanup_legacy() {
|
||||
if [ -f "/etc/init.d/moonraker" ]; then
|
||||
# Stop Moonraker Service
|
||||
echo "#### Cleanup legacy install script"
|
||||
sudo systemctl stop moonraker
|
||||
sudo update-rc.d -f moonraker remove
|
||||
sudo rm -f /etc/init.d/moonraker
|
||||
sudo rm -f /etc/default/moonraker
|
||||
fi
|
||||
}
|
||||
|
||||
# Step 3: Install packages
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
|
||||
@@ -33,7 +46,7 @@ install_packages()
|
||||
sudo apt-get install --yes ${PKGLIST}
|
||||
}
|
||||
|
||||
# Step 3: Create python virtual environment
|
||||
# Step 4: Create python virtual environment
|
||||
create_virtualenv()
|
||||
{
|
||||
report_status "Installing python virtual environment..."
|
||||
@@ -44,45 +57,50 @@ create_virtualenv()
|
||||
rm -rf ${PYTHONDIR}
|
||||
fi
|
||||
|
||||
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
|
||||
if [ ! -d ${PYTHONDIR} ]; then
|
||||
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
|
||||
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
|
||||
fi
|
||||
|
||||
# Install/update dependencies
|
||||
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
|
||||
}
|
||||
|
||||
# Step 4: Install startup script
|
||||
# Step 5: Install startup script
|
||||
install_script()
|
||||
{
|
||||
# Create systemd service file
|
||||
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
|
||||
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
report_status "Installing system start script..."
|
||||
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
|
||||
sudo update-rc.d moonraker defaults
|
||||
}
|
||||
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
|
||||
#Systemd service file for moonraker
|
||||
[Unit]
|
||||
Description=Starts Moonraker on startup
|
||||
After=network.target
|
||||
|
||||
# Step 5: Install startup script config
|
||||
install_config()
|
||||
{
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
|
||||
report_status "Installing system start configuration..."
|
||||
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
|
||||
# Configuration for /etc/init.d/moonraker
|
||||
|
||||
MOONRAKER_USER=$USER
|
||||
|
||||
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
|
||||
|
||||
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=$USER
|
||||
RemainAfterExit=yes
|
||||
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
EOF
|
||||
# Use systemctl to enable the klipper systemd service script
|
||||
sudo systemctl enable moonraker.service
|
||||
}
|
||||
|
||||
|
||||
# Step 6: Start server
|
||||
start_software()
|
||||
{
|
||||
report_status "Launching Moonraker API Server..."
|
||||
sudo systemctl stop klipper
|
||||
sudo /etc/init.d/moonraker restart
|
||||
sudo systemctl restart moonraker
|
||||
sudo systemctl start klipper
|
||||
}
|
||||
|
||||
@@ -118,8 +136,8 @@ done
|
||||
# Run installation steps defined above
|
||||
verify_ready
|
||||
check_klipper
|
||||
cleanup_legacy
|
||||
install_packages
|
||||
create_virtualenv
|
||||
install_script
|
||||
install_config
|
||||
start_software
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
#!/bin/bash
|
||||
|
||||
# moonraker-sudo (mnrkrsudo)
|
||||
# Provides a specified Group that is intended to elevate user privileges
|
||||
# to help moonraker with sudo actions, if in CustomPIOS Images with
|
||||
# Module "password-for-sudo".
|
||||
#
|
||||
# Partially used functions from Arcsine
|
||||
#
|
||||
# Copyright (C) 2020 Stephan Wendel <me@stephanwe.de>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
### Exit on Errors
|
||||
set -e
|
||||
|
||||
### Configuration
|
||||
|
||||
SUDOERS_DIR='/etc/sudoers.d'
|
||||
SUDOERS_FILE='020-sudo-for-moonraker'
|
||||
NEW_GROUP='mnrkrsudo'
|
||||
|
||||
|
||||
### Functions
|
||||
|
||||
verify_ready()
|
||||
{
|
||||
if [ "$EUID" -eq 0 ]; then
|
||||
echo "This script must not run as root"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
create_sudoers_file()
|
||||
{
|
||||
|
||||
SCRIPT_TEMP_PATH=/tmp
|
||||
|
||||
report_status "Creating ${SUDOERS_FILE} ..."
|
||||
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
sudo sed "s/GROUPNAME/$NEW_GROUP/g" > $SCRIPT_TEMP_PATH/$SUDOERS_FILE << '#EOF'
|
||||
|
||||
### Elevate moonraker API rights
|
||||
### Do NOT allow Command Parts only Full Commands
|
||||
### for example
|
||||
###
|
||||
### /sbin/systemctl "reboot", /sbin/apt "update", .....
|
||||
|
||||
Defaults!/usr/bin/apt-get env_keep +="DEBIAN_FRONTEND"
|
||||
|
||||
Cmnd_Alias REBOOT = /sbin/shutdown -r now, /bin/systemctl "reboot"
|
||||
Cmnd_Alias SHUTDOWN = /sbin/shutdown now, /sbin/shutdown -h now, /bin/systemctl "poweroff"
|
||||
Cmnd_Alias APT = /usr/bin/apt-get
|
||||
Cmnd_Alias SYSTEMCTL = /bin/systemctl
|
||||
|
||||
|
||||
|
||||
%GROUPNAME ALL=(ALL) NOPASSWD: REBOOT, SHUTDOWN, APT, SYSTEMCTL
|
||||
|
||||
#EOF
|
||||
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
update_env()
|
||||
{
|
||||
report_status "Export System Variable: DEBIAN_FRONTEND=noninteractive"
|
||||
sudo /bin/sh -c 'echo "DEBIAN_FRONTEND=noninteractive" >> /etc/environment'
|
||||
}
|
||||
|
||||
verify_syntax()
|
||||
{
|
||||
report_status "\e[1;33mVerifying Syntax of ${SUDOERS_FILE}\e[0m\n"
|
||||
|
||||
if [ $(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE | grep -c "OK" ) -eq 1 ];
|
||||
then
|
||||
VERIFY_STATUS=0
|
||||
report_status "\e[1;32m$(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE)\e[0m"
|
||||
else
|
||||
report_status "\e[1;31mSyntax Error:\e[0m Check File: $SCRIPT_TEMP_PATH/$SUDOERS_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
install_sudoers_file()
|
||||
{
|
||||
verify_syntax
|
||||
if [ $VERIFY_STATUS -eq 0 ];
|
||||
then
|
||||
report_status "Copying $SCRIPT_TEMP_PATH/$SUDOERS_FILE to $SUDOERS_DIR/$SUDOERS_FILE"
|
||||
sudo chmod 0440 $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
sudo cp --preserve=mode $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
check_update_sudoers_file()
|
||||
{
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
|
||||
then
|
||||
create_sudoers_file
|
||||
if [ -z $(sudo diff $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE) ]
|
||||
then
|
||||
report_status "No need to update $SUDOERS_DIR/$SUDOERS_FILE"
|
||||
else
|
||||
report_status "$SUDOERS_DIR/$SUDOERS_FILE needs to be updated."
|
||||
install_sudoers_file
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
add_new_group()
|
||||
{
|
||||
sudo addgroup --system $NEW_GROUP &> /dev/null
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
add_user_to_group()
|
||||
{
|
||||
sudo usermod -aG $NEW_GROUP $USER &> /dev/null
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
adduser_hint()
|
||||
{
|
||||
report_status "\e[1;31mYou have to REBOOT to take changes effect!\e[0m"
|
||||
}
|
||||
|
||||
# Helper functions
|
||||
report_status()
|
||||
{
|
||||
echo -e "\n\n###### $1"
|
||||
}
|
||||
|
||||
clean_temp()
|
||||
{
|
||||
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
}
|
||||
### Main
|
||||
|
||||
verify_ready
|
||||
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ] && [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ] && [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
|
||||
then
|
||||
check_update_sudoers_file
|
||||
report_status "\e[1;32mEverything is setup, nothing to do...\e[0m\n"
|
||||
exit 0
|
||||
|
||||
else
|
||||
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
|
||||
then
|
||||
report_status "\e[1;32mFile exists:\e[0m ${SUDOERS_FILE}"
|
||||
check_update_sudoers_file
|
||||
else
|
||||
report_status "\e[1;31mFile not found:\e[0m ${SUDOERS_FILE}\n"
|
||||
create_sudoers_file
|
||||
install_sudoers_file
|
||||
fi
|
||||
|
||||
if [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ];
|
||||
then
|
||||
report_status "Group ${NEW_GROUP} already exists..."
|
||||
else
|
||||
report_status "Group ${NEW_GROUP} will be added..."
|
||||
add_new_group
|
||||
fi
|
||||
|
||||
if [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
|
||||
then
|
||||
report_status "User ${USER} is already in $NEW_GROUP..."
|
||||
else
|
||||
report_status "Adding User ${USER} to Group $NEW_GROUP..."
|
||||
add_user_to_group
|
||||
adduser_hint
|
||||
fi
|
||||
fi
|
||||
|
||||
update_env
|
||||
clean_temp
|
||||
exit 0
|
||||
@@ -4,20 +4,25 @@
|
||||
stop_service() {
|
||||
# Stop Moonraker Service
|
||||
echo "#### Stopping Moonraker Service.."
|
||||
sudo service moonraker stop
|
||||
sudo systemctl stop moonraker
|
||||
}
|
||||
|
||||
remove_service() {
|
||||
# Remove Moonraker from Startup
|
||||
echo
|
||||
echo "#### Removing Moonraker from Startup.."
|
||||
sudo update-rc.d -f moonraker remove
|
||||
|
||||
# Remove Moonraker from Services
|
||||
# Remove Moonraker LSB/systemd service
|
||||
echo
|
||||
echo "#### Removing Moonraker Service.."
|
||||
sudo rm -f /etc/init.d/moonraker /etc/default/moonraker
|
||||
|
||||
if [ -f "/etc/init.d/moonraker" ]; then
|
||||
# legacy installation, remove the LSB service
|
||||
sudo update-rc.d -f moonraker remove
|
||||
sudo rm -f /etc/init.d/moonraker
|
||||
sudo rm -f /etc/default/moonraker
|
||||
else
|
||||
# Remove systemd installation
|
||||
sudo systemctl disable moonraker
|
||||
sudo rm -f /etc/systemd/system/moonraker.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl reset-failed
|
||||
fi
|
||||
}
|
||||
|
||||
remove_files() {
|
||||
@@ -47,6 +52,9 @@ remove_files() {
|
||||
echo
|
||||
echo "The following command is typically used to remove source files:"
|
||||
echo " rm -rf ~/moonraker"
|
||||
echo
|
||||
echo "You may also wish to uninstall nginx:"
|
||||
echo " sudo apt-get remove nginx"
|
||||
}
|
||||
|
||||
verify_ready()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Supplemental configuration for Moonraker's Update Manager
|
||||
# plugin. This file should not be modified.
|
||||
|
||||
[update_manager static debian moonraker]
|
||||
origin: https://github.com/arksine/moonraker.git
|
||||
requirements: scripts/moonraker-requirements.txt
|
||||
venv_args: -p python3
|
||||
install_script: scripts/install-moonraker.sh
|
||||
python_dist_path: /usr/lib/python3/dist-packages
|
||||
env_package_path: lib/python*/site-packages
|
||||
python_dist_packages:
|
||||
gpiod
|
||||
|
||||
[update_manager static debian klipper]
|
||||
origin: https://github.com/kevinoconnor/klipper.git
|
||||
requirements: scripts/klippy-requirements.txt
|
||||
venv_args: -p python2
|
||||
install_script: scripts/install-octopi.sh
|
||||
python_dist_path: /usr/lib/python2.7/dist-packages
|
||||
env_package_path: lib/python*/site-packages
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
env_version=0.2.0
|
||||
deps_version=0.2.0
|
||||
env_version=0.2.6
|
||||
deps_version=0.2.2
|
||||
@@ -738,6 +738,10 @@ function handle_power_changed(power_status) {
|
||||
json_rpc.register_method("notify_power_changed", handle_power_changed);
|
||||
|
||||
function handle_update_response(response) {
|
||||
if (response.complete === true) {
|
||||
console.log("Update complete");
|
||||
console.log(response);
|
||||
}
|
||||
update_term(response.message)
|
||||
}
|
||||
json_rpc.register_method("notify_update_response", handle_update_response);
|
||||
|
||||
Reference in new issue
Block a user