Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
6a13260e67 | ||
|
|
6403eaa0db | ||
|
|
4edad1b7a4 | ||
|
|
21a7a4e530 | ||
|
|
d9af161a18 | ||
|
|
83381446a0 | ||
|
|
093b8c14d6 | ||
|
|
116c1e9f29 | ||
|
|
706d86dd21 | ||
|
|
df81854f89 | ||
|
|
b0469da462 | ||
|
|
2e9c6de5d0 | ||
|
|
f96fb997da | ||
|
|
b0f781ec16 | ||
|
|
93fd850b63 | ||
|
|
a2327a093b | ||
|
|
4415a3c858 | ||
|
|
6ba54d9cb1 | ||
|
|
8d3e185894 | ||
|
|
01a48e530f | ||
|
|
675fe750f6 | ||
|
|
8ead49504b | ||
|
|
47c7cea5a5 | ||
|
|
f6fa093369 | ||
|
|
6738aa8c68 | ||
|
|
48266e0bd6 | ||
|
|
1975b875a5 | ||
|
|
0a7b580799 | ||
|
|
d18fc889d5 | ||
|
|
a5e8c290ef | ||
|
|
8b5ed3c9da | ||
|
|
de34fee72a | ||
|
|
346fce177f | ||
|
|
7ca910ec46 | ||
|
|
5081810a96 | ||
|
|
ac1d798a36 | ||
|
|
2d2f8bfbcd | ||
|
|
7414781b3a | ||
|
|
ea62bc9ed1 | ||
|
|
2cfc5b9501 | ||
|
|
222dda50bc | ||
|
|
b021d10de5 | ||
|
|
6763ea6197 | ||
|
|
697be6a822 | ||
|
|
a1de70ff89 | ||
|
|
6254586a65 | ||
|
|
3d827d7513 | ||
|
|
4b2f3a6f5f | ||
|
|
2ba41701e1 | ||
|
|
07c307f4ea | ||
|
|
daa93b0a2f | ||
|
|
5836d60d88 | ||
|
|
92d1715d88 | ||
|
|
7abc86847e | ||
|
|
a6913a982a | ||
|
|
8d1239c316 | ||
|
|
de1575f757 | ||
|
|
6c8ef93f9f | ||
|
|
a260356d78 | ||
|
|
27a17ed5a6 | ||
|
|
870cabfa05 | ||
|
|
7cd51fe1eb | ||
|
|
ac38899d1f | ||
|
|
faa415a823 | ||
|
|
30c236f1a9 | ||
|
|
b83211e98d | ||
|
|
6dfab37ef8 | ||
|
|
a0e23eb22a | ||
|
|
0fada7ffc2 | ||
|
|
453745c1b6 | ||
|
|
3b63205e70 | ||
|
|
ffdcfd527a | ||
|
|
472c7c4b23 | ||
|
|
c415f9ee15 | ||
|
|
e51dbb45c1 | ||
|
|
e5f3aeca78 | ||
|
|
59d27e6829 | ||
|
|
6464bbfc3c | ||
|
|
ba78a82a26 | ||
|
|
c6d629659b | ||
|
|
5ff87aa24e | ||
|
|
8bd6e45303 | ||
|
|
73cbcb7b7e | ||
|
|
624be50026 | ||
|
|
f14b1f3ff0 | ||
|
|
0c7fa454e9 | ||
|
|
aac11a9fb8 | ||
|
|
0d515e4938 | ||
|
|
b63d192df7 | ||
|
|
d582d76346 | ||
|
|
9394bf592c | ||
|
|
4919548ef5 | ||
|
|
374d984ced | ||
|
|
413062f8e8 | ||
|
|
7554a599b4 | ||
|
|
dfb1e19948 | ||
|
|
f2fb8d33d4 | ||
|
|
2d77400a65 | ||
|
|
8a6503da8a | ||
|
|
ab35346f24 | ||
|
|
28844cb41d | ||
|
|
8fcccfd46e | ||
|
|
f220e1b2ee | ||
|
|
346c3ad2a0 | ||
|
|
7a013a42f7 | ||
|
|
264e708c1d | ||
|
|
620fb356cc | ||
|
|
43d8e181be | ||
|
|
ac648cefcf | ||
|
|
7e3f236393 | ||
|
|
b8fc6f5130 | ||
|
|
a578199dab | ||
|
|
8440a10b9e | ||
|
|
756492f349 | ||
|
|
6905515f3d | ||
|
|
3d1faebf15 | ||
|
|
d1c0cdf65b | ||
|
|
36fb1da46d | ||
|
|
8b08b03fbf | ||
|
|
733cf0afac | ||
|
|
57fe71c800 | ||
|
|
ec86c7bfda | ||
|
|
ad8680be38 | ||
|
|
805821c928 | ||
|
|
e38f63254f | ||
|
|
97cb072981 | ||
|
|
4285ea7348 | ||
|
|
36c82d0c7f | ||
|
|
2a967303cb | ||
|
|
ae49dfe8f2 | ||
|
|
7078d5c980 | ||
|
|
059f5d6a73 | ||
|
|
c523f35c5e | ||
|
|
c122bd68e0 | ||
|
|
59277f8b7a | ||
|
|
8eaef1e559 | ||
|
|
5904c2daf5 | ||
|
|
33b965644b | ||
|
|
34008569dd | ||
|
|
371c15aa33 | ||
|
|
b034485ce8 | ||
|
|
76ea4d25a4 | ||
|
|
fdec6277eb | ||
|
|
2a34986acb |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# Editorconfig file for moonraker repo, courtesy of @trevjonez
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
charset = utf-8
|
||||
|
||||
[*.py]
|
||||
max_line_length = 80
|
||||
@@ -2,8 +2,23 @@
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use to interact with Klipper. Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket.
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
|
||||
is used to provide Moonraker's server functionality.
|
||||
|
||||
Moonraker depends on Tornado for its server functionality. Moonraker
|
||||
does not come bundled with a client, you will need to install one,
|
||||
such as [Mainsail](https://github.com/meteyou/mainsail).
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following clients are currently available:
|
||||
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
|
||||
|
||||
### Changes
|
||||
|
||||
This section contains changelogs that users and developers may reference
|
||||
to see if any action is necessary on their part. The date of the most
|
||||
recent change is included.
|
||||
|
||||
Users:\
|
||||
[user_changes.md](/docs/user_changes.md) - December 31st 2020
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - January 1st 2021
|
||||
+163
-2
@@ -1,5 +1,166 @@
|
||||
This document keeps a record of all changes to Moonraker's remote
|
||||
facing APIs.
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
### January 1st 2021
|
||||
- A `notify_klippy_shutdown` websocket notification has been added
|
||||
|
||||
### December 30th 2020
|
||||
- Some additional fields are now reported in the response to
|
||||
`GET /machine/update/status`.
|
||||
|
||||
### November 28th 2020
|
||||
- The following new endpoints are available when the `[update_manager]`
|
||||
section has been configured:
|
||||
- `GET /machine/update/status`
|
||||
- `POST /machine/update/moonraker`
|
||||
- `POST /machine/update/klipper`
|
||||
- `POST /machine/update/client`
|
||||
- `POST /machine/update/system`
|
||||
- The following endpoint has been added and is available as part of the
|
||||
core API:
|
||||
- `POST /machine/services/restart`
|
||||
|
||||
See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
|
||||
### November 23rd 2020
|
||||
- Moonraker now serves Klipper's "docs" directory. This can be access
|
||||
at `GET /server/files/docs/<filename>`.
|
||||
|
||||
### November 19th 2020
|
||||
- The path for the power APIs has changed from `gpio_power` to `device_power`:
|
||||
- `GET /machine/device_power/devices`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
|
||||
Returns an array of objects listing all detected devices.
|
||||
Each object in the array is guaranteed to have the following
|
||||
fields:
|
||||
- `device`: The device name
|
||||
- `status`: May be "init", "on", "off", or "error"
|
||||
- `type`: May be "gpio" or "tplink_smartplug"
|
||||
- `GET /machine/device_power/status?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
It is no longer possible to call this method with no arguments.
|
||||
Status will only be returned for the requested device, to get
|
||||
status of all devices use `/machine/device_power/devices`. As
|
||||
before, this returns an object in the format of
|
||||
`{device_name: status}`, where device_name is the name of the device
|
||||
and `status` is the devices current status.
|
||||
- `POST /machine/device_power/on?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device on. Returns the current status of the device.
|
||||
- `POST /machine/device_power/off?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device off. Returns the current status of the device.
|
||||
- The `notify_power_changed` notification now includes an object
|
||||
containing device info, matching that which would be recieved
|
||||
from a single item in `/machine/power/devices`.
|
||||
|
||||
### November 12th 2020
|
||||
- Two new fields have been added to the gcode metadata:
|
||||
- `gcode_start_byte`: Indicates the byte position in the
|
||||
file where the first "Gxx" or "Mxx" command is detected.
|
||||
- `gcode_end_byte`: Indicates the byte position in the
|
||||
file where the last "Gxx" or "Mxx" command is detected.
|
||||
These fields may be used to more accurately predict print
|
||||
progress based on the file size.
|
||||
|
||||
### November 11th 2020
|
||||
- The `server.websocket.id` API has been added. This returns a
|
||||
unique ID that Moonraker uses to track each client connection.
|
||||
As such, this API is only available over the websocket, there
|
||||
is no complementary HTTP request.
|
||||
- All HTTP API request may now include arguments in either the
|
||||
query string or in the request's body.
|
||||
- Subscriptions are now managed on a per connection basis. Each
|
||||
connection will only recieve updates for objects in which they
|
||||
are currently subscribed. If an "empty" request is sent, the
|
||||
subscription will be cancelled.
|
||||
- The `POST /printer/object/subscribe` now requires a
|
||||
`connection_id` argument. This is used to identify which
|
||||
connection's associated subscription should be updated.
|
||||
Currenlty subscriptions are only supported over the a
|
||||
websocket connection, one may use the id received from
|
||||
`server.websocket.id`.
|
||||
- The `notify_klippy_ready` websocket notification has been
|
||||
added.
|
||||
|
||||
### November 2nd 2020
|
||||
- The `GET /server/files/directory` endpoint now accepts a new
|
||||
optional argument, `extended`. If `extended=true`, then
|
||||
the data returned for gcode files will also include extracted
|
||||
metadata if it exists.
|
||||
|
||||
### October 25th 2020
|
||||
- The `modified` field reported for files and directories is no
|
||||
longer represented as a string. It is now a floating point
|
||||
value representing unix time (in seconds). This can be used
|
||||
to display the "last modified date" based on the client's
|
||||
timezone.
|
||||
|
||||
### October 21st 2020
|
||||
- The `/server/gcode_store` endpoint no longer returns a string
|
||||
in the result's `gcode_store` field. It now returns an
|
||||
Array of objects, each object containing `message` and `time`
|
||||
fields. The time refers to a timestamp in unix time (seconds),
|
||||
and may be used to determine when the gcode store received the
|
||||
accompanying `message`.
|
||||
|
||||
### September 30th 2020
|
||||
- Two new endpoints have been added:
|
||||
- `GET /server/info` (`server.info`)
|
||||
- `GET /server/gcode_store` (`server.gcode_store`)
|
||||
See web_api.md for details on their usage.
|
||||
|
||||
### September 7th 2020
|
||||
- A new websocket API has been added, `server.files.delete_file`:
|
||||
```
|
||||
{jsonrpc: "2.0", method: "server.files.delete_file", params:
|
||||
{path: "<root>/<file_name>"}, id: <request id>}
|
||||
```
|
||||
Where <root> is either "gcodes" or "config", and <file_name> is
|
||||
the relative path to the file for deletion. For example:
|
||||
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
|
||||
|
||||
|
||||
### September 3rd 2020
|
||||
- The Websocket APIs have changed for clarity. The APIs methods now
|
||||
use namespaces similar to those found in common programming languages.
|
||||
This change affects all websocket APIs, however websocket events have
|
||||
not changed. Below is a chart mapping the Previous API to the New API:
|
||||
| Previous Websocket Method | New Websocket Method |
|
||||
|---------------------------|----------------------|
|
||||
| get_printer_info | printer.info |
|
||||
| post_printer_emergency_stop | printer.emergency_stop |
|
||||
| post_printer_restart | printer.restart |
|
||||
| post_printer_firmware_restart | printer.firmware_restart |
|
||||
| get_printer_objects_list | printer.objects.list |
|
||||
| get_printer_objects_query | printer.objects.query |
|
||||
| post_printer_objects_subscribe | printer.objects.subscribe |
|
||||
| get_printer_query_endstops_status | printer.query_endstops.status |
|
||||
| post_printer_gcode_script | printer.gcode.script |
|
||||
| get_printer_gcode_help | printer.gcode.help |
|
||||
| post_printer_print_start | printer.print.start |
|
||||
| post_printer_print_pause | printer.print.pause |
|
||||
| post_printer_print_resume | printer.print.resume |
|
||||
| post_printer_print_cancel | printer.print.cancel |
|
||||
| post_machine_reboot | machine.reboot |
|
||||
| post_machine_shutdown | machine.shutdown |
|
||||
| get_server_temperature_store | server.temperature_store |
|
||||
| get_file_list | server.files.list |
|
||||
| get_file_metadata | server.files.metadata |
|
||||
| get_directory | server.files.get_directory |
|
||||
| post_directory | server.files.post_directory |
|
||||
| delete_directory | server.files.delete_directory |
|
||||
| post_file_move | server.files.move |
|
||||
| post_file_copy | server.files.copy |
|
||||
- The "power" plugin APIs have changed. This affects both HTTP and
|
||||
Websocket APIs. They were originally added to the "/printer" path,
|
||||
however this adds the possibility of a naming conflict. The new
|
||||
APIs are as follows:
|
||||
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
|
||||
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
|
||||
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
|
||||
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
|
||||
|
||||
### September 1st 2020
|
||||
- A new notification has been added: `notify_metdata_update`. This
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
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
|
||||
enable_debug_logging: True
|
||||
config_path: ~/.klippy_config
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
```
|
||||
|
||||
## server
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
# The host address in which to bind the HTTP server. Default is to bind
|
||||
# to all interfaces
|
||||
port: 7125
|
||||
# The port the HTTP server will listen on. Default is 7125
|
||||
klippy_uds_address: /tmp/klippy_uds
|
||||
# The address of Unix Domain Socket used to communicate with Klippy. Default
|
||||
# is /tmp/klippy_uds
|
||||
max_upload_size: 200
|
||||
# The maximum size allowed for a file upload. Default is 200 MiB.
|
||||
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:
|
||||
# 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.
|
||||
```
|
||||
## authorization
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
# Enables authorization. When set to true, requests must either contain
|
||||
# a valid API key or originate from a trusted client. Default is True.
|
||||
api_key_file: ~/.moonraker_api_key
|
||||
# Path of the file that stores Moonraker's API key. The default is
|
||||
# ~/.moonraker_api_key
|
||||
trusted_clients:
|
||||
192.168.1.30
|
||||
192.168.1.0/24
|
||||
# A list of newline separated ip addresses and/or ip ranges that are
|
||||
# trusted. Trusted clients are given full access to the API. Both IPv4
|
||||
# and IPv6 addresses and ranges are supported. Ranges must be expressed
|
||||
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
|
||||
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
|
||||
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
|
||||
# of the ip address must be 0. The default is no clients or ranges are
|
||||
# trusted.
|
||||
cors_domains:
|
||||
http://klipper-printer.local
|
||||
http://second-printer.local:7125
|
||||
# Enables CORS for the specified domains. One may specify * if they wish
|
||||
# to allow all domains.
|
||||
```
|
||||
|
||||
# Plugin Configuration
|
||||
The sections outlined here are optional and enable additional
|
||||
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. 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
|
||||
# must be provided.
|
||||
baud: 57600
|
||||
# The baud rate to connect at. The default is 57600 baud.
|
||||
machine_name: Klipper
|
||||
# An optional unique machine name which displays on the PanelDue's
|
||||
# Header. The default is "Klipper".
|
||||
macros:
|
||||
LOAD_FILAMENT
|
||||
UNLOAD_FILAMENT
|
||||
PANELDUE_BEEP FREQUENCY=500 DURATION=1
|
||||
# A list of newline separated "macros" that are displayed in the
|
||||
# PanelDue's "macros" tab. These can be gcode macros or simple
|
||||
# gcodes. A macro may contain parameters. The default is no
|
||||
# macros will be displayed by the PanelDue.
|
||||
confirmed_macros:
|
||||
RESTART
|
||||
FIRMWARE_RESTART
|
||||
# Like the "macros" option, this list is added to the macros tab.
|
||||
# When one of these macros is excuted the PanelDue will prompt
|
||||
# the user with a confirmation dialog. The default is to include
|
||||
# RESTART and FIRMWARE_RESTART.
|
||||
```
|
||||
|
||||
Most options above are self explanatory. The "macros" option can be used
|
||||
to specify commands (either built in or gcode_macros) that will show up
|
||||
in the PanelDue's "macro" menu.
|
||||
|
||||
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
|
||||
```
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
# Beep duration in seconds
|
||||
default_parameter_DURATION: 1.
|
||||
gcode:
|
||||
{action_call_remote_method("paneldue_beep",
|
||||
frequency=FREQUENCY|int,
|
||||
duration=DURATION|float)}
|
||||
```
|
||||
|
||||
## power
|
||||
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
|
||||
and Tasmota (via http) devices are supported.
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[power device_name]
|
||||
type: gpio
|
||||
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
|
||||
# This parameter must be provided.
|
||||
pin: gpiochip0/gpio26
|
||||
# The pin to use for GPIO devices. The chip is optional, if left out
|
||||
# then the module will default to gpiochip0. If one wishes to invert
|
||||
# the signal, a "!" may be prefixed to the pin. Valid examples:
|
||||
# gpiochip0/gpio26
|
||||
# gpio26
|
||||
# !gpiochip0/gpio26
|
||||
# !gpio26
|
||||
# This parameter must be provided for "gpio" type devices
|
||||
initial_state: off
|
||||
# The initial state for GPIO type devices. May be on or
|
||||
# off. When moonraker starts the device will be set to this
|
||||
# state. Default is off.
|
||||
address:
|
||||
port:
|
||||
# The above options are used for "tplink_smartplug" devices. The
|
||||
# address should be a valid ip or hostname for the tplink device.
|
||||
# The port should be the port the device is configured to use. The
|
||||
# address must be provided. The port defaults to 9999.
|
||||
address:
|
||||
password:
|
||||
output_id:
|
||||
# The above options are used for "tasmota" devices. The
|
||||
# address should be a valid ip or hostname for the tasmota device.
|
||||
# Provide a password if configured in Tasmota (default is empty).
|
||||
# Provided an output_id (relay id) if the Tasmota device supports
|
||||
# more than one (default is 1).
|
||||
# If your single-relay Tasmota device switches on/off successfully,
|
||||
# but fails to report its state, ensure that 'SetOption26' is set in
|
||||
# Tasmota.
|
||||
|
||||
```
|
||||
Below are some potential examples:
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[power printer]
|
||||
type: gpio
|
||||
pin: gpio26
|
||||
initial_state: off
|
||||
|
||||
[power printer_led]
|
||||
type: gpio
|
||||
pin: !gpiochip0/gpio16
|
||||
initial_state: off
|
||||
|
||||
[power light_strip]
|
||||
type: gpio
|
||||
pin: gpiochip0/gpio17
|
||||
initial_state: on
|
||||
|
||||
[power wifi_switch]
|
||||
type: tplink_smartplug
|
||||
address: 192.168.1.123
|
||||
|
||||
[power tasmota_plug]
|
||||
type: tasmota
|
||||
address: 192.168.1.124
|
||||
password: password1
|
||||
```
|
||||
|
||||
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",
|
||||
device="printer",
|
||||
state="off")}
|
||||
```
|
||||
The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
|
||||
This could be used in conjunction with Klipper's idle timeout to turn the
|
||||
printer off when idle with a configuration similar to that of below:
|
||||
```
|
||||
# printer.cfg
|
||||
|
||||
[delayed_gcode delayed_printer_off]
|
||||
initial_duration: 0.
|
||||
gcode:
|
||||
{% if printer.idle_timeout.state == "Idle" %}
|
||||
POWER_OFF_PRINTER
|
||||
{% endif %}
|
||||
|
||||
[idle_timeout]
|
||||
gcode:
|
||||
TURN_OFF_MOTORS
|
||||
TURN_OFF_HEATERS
|
||||
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
|
||||
```
|
||||
|
||||
## update_manager
|
||||
This enables moonraker's update manager. Note that updates can only be
|
||||
performed on pristine git repos. Repos that have been modified on
|
||||
disk or cloned from unofficial sources are not supported.
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager]
|
||||
enable_repo_debug: False
|
||||
# When set to True moonraker will bypass repo validation and allow
|
||||
# updates from unofficial remotes and/or branches. Updates on
|
||||
# detached repos are also allowed. This option is intended for
|
||||
# developers and should not be used on production machines. The
|
||||
# default is False.
|
||||
distro: debian
|
||||
# The disto in which moonraker has been installed. Currently the
|
||||
# update manager only supports "debian", which encompasses all of
|
||||
# its derivatives. The default is debain.
|
||||
client_repo:
|
||||
# This is the GitHub repo of the client, in the format of user/client.
|
||||
# For example, this could be set to cadriel/fluidd to update Fluidd or
|
||||
# meteyou/mainsail to update Mainsail. If this option is not set then
|
||||
# the update manager will not attempt to update a client.
|
||||
client_path:
|
||||
# The path to the client's files on disk. This cannot be a symbolic link,
|
||||
# it must be the real directory in which the client's files are located.
|
||||
# If `client_repo` is set, this parameter must be provided
|
||||
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
# Example Home Assistant configuration file for a Voron V0.
|
||||
# Credit to GitHub user @Kruppes
|
||||
#
|
||||
sensor:
|
||||
- platform: rest
|
||||
name: Voron_V0_sensor
|
||||
resource: "http://192.168.178.56:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
|
||||
json_attributes_path: "$.result.status"
|
||||
json_attributes:
|
||||
- heater_bed
|
||||
- extruder
|
||||
- print_stats
|
||||
- toolhead
|
||||
- display_status
|
||||
- virtual_sdcard
|
||||
value_template: 'OK'
|
||||
- platform: template
|
||||
sensors:
|
||||
vzero_hotend_target:
|
||||
friendly_name: 'V0.126 Hotend Target'
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
vzero_hotend_actual:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
vzero_bed_target:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
vzero_bed_actual:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
vzero_state:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["state"]}}'
|
||||
vzero_current_print:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["filename"]}}'
|
||||
vzero_current_progress:
|
||||
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
|
||||
unit_of_measurement: '%'
|
||||
vzero_print_time:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
|
||||
vzero_time_remaining:
|
||||
value_template: '{{ (((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
|
||||
vzero_eta:
|
||||
value_template: '{{ (as_timestamp(now())+2*60*60+((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
|
||||
vzero_nozzletemp:
|
||||
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1)| string)]|join}}'
|
||||
vzero_bedtemp:
|
||||
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1)| string)]|join}}'
|
||||
+81
-183
@@ -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,37 +67,50 @@ cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
If you have an experimental verison of moonraker that pre-dates this repo,
|
||||
it must be uninstalled:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./uninstall-moonraker.sh
|
||||
```
|
||||
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.
|
||||
|
||||
Finally, run moonraker's install script:
|
||||
For a default installation run the following commands:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
Or to install with `moonraker.conf` in the `config_path`:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
|
||||
```
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
- -r\
|
||||
This will rebuild the virtual environment for existing installations.
|
||||
Sometimes this is necessary when a dependency has been added.
|
||||
- -f\
|
||||
This will tell the script to overwrite Moonraker's "defaults" file.
|
||||
By default the script will not modify the "defaults" file if it is
|
||||
detected as present.
|
||||
- -c /path/to/moonraker.conf\
|
||||
This allows the user to specify the path to Moonraker's config file.
|
||||
The default location is `/home/<user>/moonraker.conf`.
|
||||
|
||||
When the script completes it should start both Moonraker and Klipper. In
|
||||
`klippy.log` you should find the following entry:\
|
||||
`webhooks: 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)
|
||||
|
||||
# Configuration
|
||||
|
||||
## Command line
|
||||
## 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
|
||||
|
||||
@@ -87,16 +120,28 @@ 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.
|
||||
|
||||
## Klipper configuration (printer.cfg)
|
||||
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)
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
- [virtual_sdcard]
|
||||
@@ -115,161 +160,14 @@ missing one or both, you can simply add the bare sections to printer.cfg:
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
```
|
||||
NOTE: 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.
|
||||
NOTES:
|
||||
- Make sure that Moonraker (and Klipper) has read and write access to the
|
||||
directory set in the `path` option for the `virtual_sdcard`.
|
||||
- Upon first starting Moonraker is not aware of the gcode file path, thus
|
||||
it cannot serve gcode files, add directories, etc. After Klippy enters
|
||||
the "ready" state it sends Moonraker the gcode file path.
|
||||
Once Moonraker receives the path it will retain it regardless of Klippy's
|
||||
state, and update it if the path is changed in printer.cfg.
|
||||
|
||||
## Moonraker configuration (moonraker.conf)
|
||||
|
||||
All other configuration is done via `moonraker.conf`. If you are
|
||||
familiar with Klipper, the configuration is similar. A basic
|
||||
configuration might look like the following:
|
||||
```
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
port: 7125
|
||||
enable_debug_logging: True
|
||||
config_path: ~/.klippy_config
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
```
|
||||
|
||||
Note that while all items in the `[server]` and `[authorization]`
|
||||
sections have default values, the sections must be present for
|
||||
moonraker to start. Aside from the `config_path` and `trusted_clients`
|
||||
options it is recommended to use default values.
|
||||
|
||||
Below is a detailed explanation of all options currently available:
|
||||
```
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
# The host address in which to bind the HTTP server. Default is to bind
|
||||
# to all interfaces
|
||||
port: 7125
|
||||
# The port the HTTP server will listen on. Default is 7125
|
||||
klippy_address: /tmp/klippy_uds
|
||||
# The address of Unix Domain Socket used to communicate with Klippy. Default
|
||||
# is /tmp/klippy_uds
|
||||
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.
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
# Enables authorization. When set to true, requests must either contain
|
||||
# a valid API key or originate from a trusted client. Default is True.
|
||||
api_key_path: ~/.moonraker_api_key
|
||||
# Path of the file that stores Moonraker's API key. The default is
|
||||
# ~/.moonraker_api_key
|
||||
trusted_clients:
|
||||
192.168.1.30
|
||||
192.168.1.0/24
|
||||
# A list of newline separated ip addresses and/or ip ranges that are
|
||||
# trusted. Trusted clients are given full access to the API. Both IPv4
|
||||
# and IPv6 addresses and ranges are supported. Ranges must be expressed
|
||||
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
|
||||
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
|
||||
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
|
||||
# of the ip address must be 0. The default is no clients or ranges are
|
||||
# trusted.
|
||||
```
|
||||
|
||||
For the moment, you need to restart the moonraker service to load a new
|
||||
configuration:
|
||||
```
|
||||
sudo service moonraker restart
|
||||
```
|
||||
|
||||
### Plugin Configuration
|
||||
The core plugins are configured via the primary configuration above. Optional
|
||||
plugins each need their own configuration as outlined below.
|
||||
|
||||
#### PanelDue Plugin
|
||||
```
|
||||
[paneldue]
|
||||
serial:
|
||||
# The serial port in which the PanelDue is connected. This parameter
|
||||
# must be provided.
|
||||
baud: 57600
|
||||
# The baud rate to connect at. The default is 57600 baud.
|
||||
machine_name: Klipper
|
||||
# An optional unique machine name which displays on the PanelDue's
|
||||
# Header. The default is "Klipper".
|
||||
macros:
|
||||
LOAD_FILAMENT
|
||||
UNLOAD_FILAMENT
|
||||
PANELDUE_BEEP FREQUENCY=500 DURATION=1
|
||||
# A list of newline separated "macros" that are displayed in the
|
||||
# PanelDue's "macros" tab. These can be gcode macros or simple
|
||||
# gcodes. A macro may contain parameters. The default is no
|
||||
# macros will be displayed by the PanelDue.
|
||||
confirmed_macros:
|
||||
RESTART
|
||||
FIRMWARE_RESTART
|
||||
# Like the "macros" option, this list is added to the macros tab.
|
||||
# When one of these macros is excuted the PanelDue will prompt
|
||||
# the user with a confirmation dialog. The default is to include
|
||||
# RESTART and FIRMWARE_RESTART.
|
||||
```
|
||||
|
||||
Most options above are self explanatory. The "macros" option can be used
|
||||
to specify commands (either built in or gcode_macros) that will show up
|
||||
in the PanelDue's "macro" menu.
|
||||
|
||||
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
|
||||
```
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
variable_sequence: 0
|
||||
variable_frequency: 0
|
||||
variable_duration: 0
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
# Beep duration in seconds
|
||||
default_parameter_DURATION: 1.
|
||||
gcode:
|
||||
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=frequency VALUE={FREQUENCY|int}
|
||||
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=duration VALUE={DURATION|float}
|
||||
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=sequence VALUE={printer["gcode_macro PANELDUE_BEEP"].sequence|int + 1}
|
||||
```
|
||||
|
||||
#### Power Control Plugin
|
||||
Power Plugin Configuration. One may use this module to toggle the
|
||||
state of a relay using a linux GPIO, enabling the ability to power
|
||||
a printer on/off regardless of Klippy's state. GPIOs are toggled
|
||||
using linux sysfs.
|
||||
```
|
||||
[power]
|
||||
devices: printer, led
|
||||
# A comma separated list of devices you wish to control. Device names may not
|
||||
# contain whitespace. This parameter must be provided.
|
||||
#
|
||||
# Each device specified in "devices" should define its own set of the below
|
||||
# options:
|
||||
{dev}_name: Friendly Name
|
||||
# An optional alias for the device. The default is the name specifed in
|
||||
# "devices".
|
||||
{dev}_pin: 23
|
||||
# The sysfs GPIO pin number you wish to control. This parameter must be
|
||||
# provided.
|
||||
{dev}_active_low: False
|
||||
# When set to true the pin signal is inverted. Default is False.
|
||||
```
|
||||
|
||||
Define the devices you wish to control under _devices_ with a comma separated
|
||||
list. For device specific configrations, swap {dev} for the name of the device
|
||||
that you listed under devices.
|
||||
|
||||
Each device can have a Friendly Name, pin, and activehigh set. Pin is the only
|
||||
required option. For devices that should be active when the signal is 0 or low,
|
||||
set {dev}_activehigh to False, otherwise don't put the option in the
|
||||
configuration.
|
||||
Please see [configuration.md](configuration.md) for details on how to
|
||||
configure moonraker.conf.
|
||||
@@ -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
|
||||
@@ -0,0 +1,344 @@
|
||||
As mentioned in the API documentation, it is possible to
|
||||
[query](web_api.md#query-printer-object-status) or
|
||||
[subscribe](web_api.md#subscribe-to-printer-object-status)
|
||||
to "Klipper Printer Objects." There are numerous printer objects in
|
||||
Klipper, many of which are optional and only report status if they are
|
||||
enabled by Klipper's configuration. Client's may retreive a list of
|
||||
available printer objects via the
|
||||
[list objects endpoint](web_api.md#list-available-printer-objects). This
|
||||
should be done after Klipper reports its state as "ready".
|
||||
|
||||
This section will provide an overview of the most useful printer objects.
|
||||
If a developer is interested in retreiving state for an object not listed here,
|
||||
look in Klipper's source code for module you wish to query. If the module
|
||||
contains a "get_status()" method, its return value will contain a dictionary
|
||||
that reports state which can be queried.
|
||||
|
||||
## webhooks
|
||||
```json
|
||||
{
|
||||
state: "startup",
|
||||
state_message: "message"
|
||||
}
|
||||
```
|
||||
The `webhooks` object contains the current printer state and the current
|
||||
state message. These fields match those returned via the `/printer/info`
|
||||
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
|
||||
so they are asynchonously notified of a change to printer state. The `state`
|
||||
may be "startup", "ready", "shutdown", or "error". The `state_message`
|
||||
contains a message specific to the current printers state.
|
||||
|
||||
## gcode_move
|
||||
```json
|
||||
{
|
||||
speed_factor: 1.0,
|
||||
speed: 100.0,
|
||||
extrude_factor: 1.0,
|
||||
absolute_coordinates: true,
|
||||
absolute_extrude: false,
|
||||
homing_origin: [0.0, 0.0, 0.0, 0.0],
|
||||
position: [0.0, 0.0, 0.0, 0.0],
|
||||
gcode_position: [0.0, 0.0, 0.0, 0.0]
|
||||
}
|
||||
```
|
||||
The `gcode_move` object reports the current gcode state:
|
||||
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
|
||||
- `speed`: The current gcode speed in mm/s.
|
||||
- `extrude_factor`: AKA "extrusion multiplier".
|
||||
- `absolute_coorinates`: true if the machine axes are moved using
|
||||
absolute coordinates, false if using relative coordinates.
|
||||
- `absolute_extrude`: true if the extruder is moved using absolute
|
||||
coordinates, false if using relative coordinates.
|
||||
- `homing_origin`: [X, Y, Z, E] - returns the "gcode offset" applied to
|
||||
each axis. For example, the "Z" axis can be checked to determine how
|
||||
much offset has been applied via "babystepping".
|
||||
- `position`: [X, Y, Z, E] - The internal gcode position, including
|
||||
any offsets (gcode_offset, G92, etc) added to an axis.
|
||||
- `gcode_position`: [X, Y, Z, E] - The current gcode position
|
||||
sans any offsets applied. For X, Y, and Z, this should match
|
||||
the most recent "G1" or "G0" processed assuming the machine is
|
||||
using absolute coordinates.
|
||||
|
||||
Note: The printer's actual movement may lag behind the reported positional
|
||||
coordinates due to lookahead.
|
||||
|
||||
## toolhead
|
||||
```json
|
||||
{
|
||||
homed_axes: "xyz",
|
||||
print_time: 0.0,
|
||||
estimated_print_time: 0.0,
|
||||
extruder: "extruder",
|
||||
position: [0.0, 0.0, 0.0, 0.0],
|
||||
max_velocity: 500.0,
|
||||
max_accel: 3000.0,
|
||||
max_accel_to_decel: 1500.0,
|
||||
square_corner_velocity: 5.0
|
||||
}
|
||||
```
|
||||
The `toolhead` object reports state of the current tool:
|
||||
- `homed_axes`: a string containing the axes that are homed. If no axes
|
||||
are homed, returns a null string.
|
||||
- `print_time`: internal value, not generally useful for clients
|
||||
- `estimated_print_time`: internal value, not generally useful for clients.
|
||||
- `extruder`: the name of the currently selected extruder, ie "extruder"
|
||||
or "extruder1".
|
||||
- `position`: [X, Y, Z, E] - This the the last position toward which the tool
|
||||
was commanded to move. It includes any offsets applied via gcode as well
|
||||
as any transforms made by modules such as "bed_mesh", "bed_tilt", or
|
||||
"skew_correction".
|
||||
- `max_velocity`: The currently set maximum velocity of the tool (mm/s^2).
|
||||
- `max_accel`: The currently set maximum acceleration of the tool (mm/s^2).
|
||||
- `max_accel_to_decel`: The currently set maximum accel to decel of the tool.
|
||||
This value is the maximum rate at which the tool can transition from
|
||||
acceleration to deceleration (mm/s^2).
|
||||
- `square_corner_velocity`: The currently set square corner velocity. This
|
||||
is the maximum velocity at which the tool may travel a 90 degree corner.
|
||||
|
||||
Note: `max_velocity`, `max_accel`, `max_accel_to_decel`, and
|
||||
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
|
||||
`M204` can also change `max_accel`.
|
||||
|
||||
## configfile
|
||||
```json
|
||||
{
|
||||
config: {},
|
||||
save_config_pending: false
|
||||
}
|
||||
```
|
||||
The `configfile` object reports printer configuration state:
|
||||
- `config`: This is an object containing the configuration as read from
|
||||
printer.cfg. Each config section will be an object containing the
|
||||
configured options. Option values will ALWAYS be reported as
|
||||
strings. Note that default values are not reported, only options
|
||||
configured in printer.cfg are present.
|
||||
- `save_config_pending`: True if the printer has taken an action which
|
||||
has updated the internal configuration (ie: PID calibration, probe
|
||||
calibration, bed mesh calibration). This allows clients to present
|
||||
the user with the option to execute a SAVE_CONFIG gcode which will
|
||||
save the configuration to printer.cfg and restart the Klippy Host.
|
||||
|
||||
## extruder
|
||||
*Enabled when [extruder] is included in printer.cfg*
|
||||
Note: If multiple extruders are configured, extruder 0 is available as
|
||||
`extruder`, extruder 1 as `extruder1` and so on.
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
pressure_advance: 0.0,
|
||||
smooth_time: 0.0
|
||||
}
|
||||
```
|
||||
The `extruder` object reports state of an extruder:
|
||||
- `temperature`: The extruder's current temperature (in C).
|
||||
- `target`: The extruder's target temperature (in C).
|
||||
- `pressure_advance`: The extruder's current pressure advance value.
|
||||
- `smooth_time`: The currently set time range to use when calculating the
|
||||
average extruder velocity for pressure advance.
|
||||
|
||||
## heater_bed
|
||||
*Enabled when [heater_bed] is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
}
|
||||
```
|
||||
The `heater_bed` object reports state of the heated bed:
|
||||
- `temperature`: The bed's current temperature
|
||||
- `target`: The bed's target temperature
|
||||
|
||||
## fan
|
||||
*Enabled when [fan] is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
speed: 0.0
|
||||
}
|
||||
```
|
||||
The `fan` object returns state of the part cooling fan:
|
||||
- `speed`: The current fan speed. This is reported as a
|
||||
percentage of maximum speed in the range of 0.0 - 1.0.
|
||||
|
||||
## idle_timeout
|
||||
```json
|
||||
{
|
||||
state: "Idle",
|
||||
printing_time: 0.0
|
||||
}
|
||||
```
|
||||
|
||||
The `idle_timeout` object reports the idle state of the printer:
|
||||
- `state`: Can be "Idle", "Ready", or "Printing". The printer will
|
||||
transition to the "Printing" state whenever a gcode is issued that
|
||||
commands the tool, this includes manual commands. Thus this should
|
||||
not be used to determine if a gcode file print is in progress. It can
|
||||
however be used to determine if the printer is busy.
|
||||
- `printing_time`: The amount of time the printer has been in the
|
||||
"Printing" state. This is reset to 0 whenever the printer transitions
|
||||
from "Printing" to "Ready".
|
||||
|
||||
## virtual_sdcard
|
||||
*Enabled when [virtual_sdcard] is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
progress: 0.0,
|
||||
is_active: false,
|
||||
file_position: 0
|
||||
}
|
||||
```
|
||||
The `virtual_sdcard` object reports the state of the virtual sdcard:
|
||||
- `progress`: The print progress reported as a percentage of the file
|
||||
read, in the range of 0.0 - 1.0.
|
||||
- `is_active`: Returns true if the virtual sdcard is currently processing
|
||||
a file. Note that this will return false if a virtual sdcard print is
|
||||
paused.
|
||||
- `file_position`: The current file position in bytes. This will always
|
||||
be an integer value
|
||||
|
||||
Note: `progress` and `file_position` will persist after a print has
|
||||
paused, completed, or errored. They are cleared when the user issues
|
||||
a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## print_stats
|
||||
*Enabled when [virtual_sdcard] is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
filename: "",
|
||||
total_duration: 0.0,
|
||||
print_duration: 0.0,
|
||||
filament_used: 0.0,
|
||||
state: "standby",
|
||||
message: ""
|
||||
}
|
||||
```
|
||||
The `print_stats` object reports "virtual_sdcard" print state:
|
||||
- `filename`: The name of the current file loaded. This will be a null
|
||||
string if no file is loaded. Note that name is a path relative to the
|
||||
gcode folder, thus if the file is located in a subdirectory it would
|
||||
be reported as "my_sub_dir/myprint.gcode".
|
||||
- `total_duration`: The total time (in seconds) elapsed since a print
|
||||
has started. This includes time spent paused.
|
||||
- `print_duration`: The total time spent printing (in seconds). This is
|
||||
equivalent to `total_duration` - time paused.
|
||||
- `filament_used`: The amount of filament used during the current print
|
||||
(in mm). Any extrusion during a pause is excluded.
|
||||
- `state`: Current print state. Can be "standby", "printing", "paused",
|
||||
"complete", or "error". If an error is detected the print will abort.
|
||||
- `message`: If an error is detected, this field contains the error
|
||||
message generated. Otherwise it will be a null string.
|
||||
|
||||
Note: After a print has started all of the values above will persist until
|
||||
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## display_status
|
||||
*Enabled when [display] or [display_status] is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
message: "",
|
||||
progress: 0.0
|
||||
}
|
||||
```
|
||||
The `display_status` object contains state typically used to update displays:
|
||||
- `message`: The message set by a M117 gcode. If no message is set this will
|
||||
be a null string.
|
||||
- `progress`: The percentage of print progress, as reported by M73. This
|
||||
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
|
||||
will fallback to the eqivalent of `virtual_sdcard.progess`. Note that
|
||||
progress updated via M73 has a timeout. If no M73 is received after 5
|
||||
seconds, `progress` will be set to the fallback value.
|
||||
|
||||
## temperature_sensor sensor_name
|
||||
*Enabled when [temperature_sensor sensor_name] is included in printer.cfg. It is*
|
||||
*possible for multiple temperature sensors to be configured.*
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
measured_min_temp: 0.0,
|
||||
measured_max_temp: 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_sensor` reports the following state:
|
||||
- `temperature`: Sensor's current reported temperature
|
||||
- `measured_min_temp`: The mimimum temperature read from the sensor
|
||||
- `measured_max_temp`: The maximum temperature read from the sensor
|
||||
|
||||
## temperature_fan fan_name
|
||||
*Enabled when [temperature_fan fan_name] is included in printer.cfg. It is*
|
||||
*possible for multiple temperature fans to be configured.*
|
||||
```json
|
||||
{
|
||||
speed: 0.0,
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_fan` reports the following state:
|
||||
- `speed`: Current fan speed as a percentage of maximum speed, reported
|
||||
in the range of 0.0 - 1.0
|
||||
- `temperature`: Currently reported temperature of the sensor associated
|
||||
with the fan
|
||||
- `target`: The current target temperature for the `temperature_fan`.
|
||||
|
||||
## filament_switch_sensor sensor_name
|
||||
*Enabled when [filament_switch_sensor sensor_name] is included in printer.cfg.*
|
||||
*It is possible for multiple filament sensors to be configured.*
|
||||
```json
|
||||
{
|
||||
filament_detected: false,
|
||||
enabled: true
|
||||
}
|
||||
```
|
||||
A `filament_switch_sensor` reports the following state:
|
||||
- `filament_detected`: Set to true if the switch detects filament, otherwise
|
||||
false
|
||||
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
|
||||
|
||||
## output_pin pin_name
|
||||
*Enabled when [output_pin pin_name] is included in printer.cfg.*
|
||||
*It is possible for multiple output pins to be configured.*
|
||||
```json
|
||||
{
|
||||
value: 0.0
|
||||
}
|
||||
```
|
||||
An `output_pin` reports the following state:
|
||||
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
|
||||
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
|
||||
across the entire range.
|
||||
|
||||
## bed_mesh
|
||||
*Enabled when [bed_mesh] is included in printer.cfg.*
|
||||
```json
|
||||
{
|
||||
profile_name: "",
|
||||
mesh_min: [0.0, 0.0],
|
||||
mesh_max: [0.0, 0.0],
|
||||
probed_matrix: [[]],
|
||||
mesh_matrix: [[]]
|
||||
}
|
||||
```
|
||||
The `bed_mesh` printer object reports the following state:
|
||||
- `profile_name`: The name of the currently loaded profile. If no profile is
|
||||
loaded then this will report a null string. If the user is not using bed_mesh
|
||||
profile management then this will report "default" after mesh calibration
|
||||
completes.
|
||||
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
|
||||
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
|
||||
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
|
||||
values. If the matrix has not been probed the the result is `[[]]`.
|
||||
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
|
||||
no matrix has been generated the result is `[[]]`.
|
||||
|
||||
Note: See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
|
||||
of how to use this information to generate (X,Y,Z) coordinates.
|
||||
|
||||
## gcode_macro macro_name
|
||||
*Enabled when [gcode_macro macro_name] is included in printer.cfg.*
|
||||
*It is possible for multiple gcode macros to be configured.*
|
||||
|
||||
Gcode macros will report the state of configured "variables".
|
||||
While user defined macros likely won't report state that is useful
|
||||
for a client, it is possible for client developers to recommend or
|
||||
request a specific gcode_macro configuration, then have the client
|
||||
take action based on the variables reported by the macro.
|
||||
@@ -0,0 +1,54 @@
|
||||
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:\
|
||||
`-r` Rebuild the python virtual env\
|
||||
`-f` Force an overwrite of `/etc/default/moonraker` during installation\
|
||||
`-c /path/to/moonraker.conf` Allows user to specify the path to
|
||||
moonraker.conf during configuration. Using this in conjunction with `-f`
|
||||
will update the defaults file wih the new path.
|
||||
- New dependencies have been added to Moonraker which require reinstallation.
|
||||
Run the following command to reinstall and rebuild the virtualenv:
|
||||
```
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
```
|
||||
- The power plugin configuration has changed. See the
|
||||
[install guide](installation.md#power-control-plugin) for
|
||||
details on the new configuration.
|
||||
- Users transitioning from the previous version of the power plugin will need
|
||||
to unexport any curently used pins. For example, the following command
|
||||
may be used to unexport pin 19:
|
||||
```
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
```
|
||||
Alternatively one may reboot the machine after upgrading:
|
||||
```
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
```
|
||||
Make sure that the power plugin configuration has been updated prior
|
||||
to rebooting the machine.
|
||||
+617
-65
@@ -11,8 +11,9 @@ of:
|
||||
|
||||
`{result: <response data>}`
|
||||
|
||||
The command matches the original command request, the result is the return
|
||||
value generated from the request.
|
||||
Arguments sent via the HTTP APIs may either be included in the query string
|
||||
or as part of the request's body. All of the examples in this document
|
||||
use the query string for arguments.
|
||||
|
||||
Websocket requests are returned in JSON-RPC format:
|
||||
`{jsonrpc: "2.0", "result": <response data>, id: <request id>}`
|
||||
@@ -37,7 +38,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`GET /printer/info`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_printer_info", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.info", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An object containing the build version, cpu info, Klippy's current state.
|
||||
@@ -61,7 +62,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/emergency_stop`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_emergency_stop", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.emergency_stop", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
@@ -71,7 +72,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/restart`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_restart", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.restart", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
@@ -81,19 +82,19 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/firmware_restart`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_firmware_restart", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.firmware_restart", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
|
||||
## Printer Status
|
||||
|
||||
### Request available printer objects and their attributes:
|
||||
### List available printer objects:
|
||||
- HTTP command:\
|
||||
`GET /printer/objects/list`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_printer_objects_list", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.objects.list", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An a list of "printer objects" that are currently available for query
|
||||
@@ -103,7 +104,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
|
||||
```
|
||||
|
||||
### Query the a status for an object, or group of objects:
|
||||
### Query printer object status:
|
||||
- HTTP command:\
|
||||
`GET /printer/objects/query?gcode`
|
||||
|
||||
@@ -113,8 +114,8 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`?gcode=gcode_position,busy&toolhead&extruder=target`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_printer_objects_query", params:
|
||||
{objects: {gcode: [], toolhead: ["position", "status"]}},
|
||||
`{jsonrpc: "2.0", method: "printer.objects.query", params:
|
||||
{objects: {gcode: null, toolhead: ["position", "status"]}},
|
||||
id: <request id>}`
|
||||
|
||||
Note that an empty array will fetch all available attributes for its key.
|
||||
@@ -138,17 +139,30 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
...}
|
||||
}
|
||||
```
|
||||
### Subscribe to a status request or a batch of status requests:
|
||||
See [printer_objects.md](printer_objects.md) for details on the printer objects
|
||||
available for query.
|
||||
|
||||
### Subscribe to printer object status:
|
||||
- HTTP command:\
|
||||
`POST /printer/objects/subscribe?gcode=gcode_position,bus&extruder=target`
|
||||
`POST /printer/objects/subscribe?connection_id=123456789&
|
||||
gcode=gcode_position,bus&extruder=target`
|
||||
|
||||
Note: The HTTP API requires that a `connection_id` is passed via the query
|
||||
string or as part of the form. This should be the
|
||||
[ID reported](#get-websocket-id) from a currently connected websocket. A
|
||||
request that includes only the `connection_id` argument will cancel the
|
||||
subscription on the specified websocket.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_objects_subscribe", params:
|
||||
{objects: {gcode: [], toolhead: ["position", "status"]}},
|
||||
`{jsonrpc: "2.0", method: "printer.objects.subscribe", params:
|
||||
{objects: {gcode: null, toolhead: ["position", "status"]}},
|
||||
id: <request id>}`
|
||||
|
||||
Note that if `objects` is an empty object then the subscription will
|
||||
be cancelled.
|
||||
|
||||
- Returns:\
|
||||
Status data for all currently subscribed objects, with the format matching that of
|
||||
Status data for objects in the request, with the format matching that of
|
||||
the `/printer/objects/query`:
|
||||
|
||||
```json
|
||||
@@ -166,20 +180,18 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
...}
|
||||
}
|
||||
```
|
||||
Note that Moonraker's current behavior is maintain a superset of all client
|
||||
subscriptions, thus you may received data for objects that you did not
|
||||
request. This behavior is subject to change in the future (where each
|
||||
client receives only the subscriptions it requested).
|
||||
See [printer_objects.md](printer_objects.md) for details on the printer objects
|
||||
available for subscription.
|
||||
|
||||
Future updates for subscribed objects are sent asynchronously over the
|
||||
websocket. See the `notify_status_update` notification for details.
|
||||
Status updates for subscribed objects are sent asynchronously over the
|
||||
websocket. See the `notify_status_update` notification for details.
|
||||
|
||||
### Query Endstops
|
||||
- HTTP command:\
|
||||
`GET /printer/query_endstops/status`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_printer_query_endstops_status", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.query_endstops.status", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An object containing the current endstop state, with each attribute in the
|
||||
@@ -192,12 +204,35 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
z: "open"}
|
||||
```
|
||||
|
||||
### Query Server Info
|
||||
- HTTP command:\
|
||||
`GET /server/info`
|
||||
|
||||
- Websocket command:
|
||||
`{jsonrpc: "2.0", method: "server.info", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An object containing the server's state, structured as follows:
|
||||
|
||||
```json
|
||||
{
|
||||
klippy_connected: <bool>,
|
||||
klippy_state: <string>,
|
||||
plugins: [<strings>]
|
||||
}
|
||||
```
|
||||
Note that `klippy_state` will match the `state` value received from
|
||||
`/printer/info`. The `klippy_connected` item tracks the state of the
|
||||
connection to Klippy. The `plugins` key will return a list of all
|
||||
enabled plugins. This can be used by clients to check if an optional
|
||||
plugin is available.
|
||||
|
||||
### Fetch stored temperature data
|
||||
- HTTP command:\
|
||||
`GET /server/temperature_store`
|
||||
|
||||
- Websocket command:
|
||||
`{jsonrpc: "2.0", method: "get_temperature_store", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "server.temperature_store", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An object where the keys are the available temperature sensor names, and with
|
||||
@@ -206,6 +241,78 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
array is organized from oldest temperature to most recent (left to right).
|
||||
Note that when the host starts each array is initialized to 0s.
|
||||
|
||||
### Fetch stored gcode info
|
||||
- HTTP command:\
|
||||
`GET /server/gcode_store`
|
||||
|
||||
Optionally, a `count` argument may be added to specify the number of
|
||||
responses to fetch. If omitted, the entire gcode store will be sent
|
||||
(up to 1000 responses).
|
||||
|
||||
`GET /server/gcode_store?count=100`
|
||||
|
||||
- Websocket command:
|
||||
`{jsonrpc: "2.0", method: "server.gcode_store", id: <request id>}`
|
||||
|
||||
OR
|
||||
`{jsonrpc: "2.0", method: "server.gcode_store",
|
||||
params: {count: <integer>} id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
An object with the field `gcode_store` that contains an array
|
||||
of objects. Each object will contain a `message` field and a
|
||||
`time` field:
|
||||
```json
|
||||
{
|
||||
gcode_store: [
|
||||
{
|
||||
message: <string>,
|
||||
time: unix_time_stamp
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
```
|
||||
Each `message` field contains a gcode response received at the time
|
||||
indicated in the `time` field. Note that the time stamp refers to
|
||||
unix time (in seconds). This can be used to create a JavaScript
|
||||
`Date` object:
|
||||
```javascript
|
||||
for (let resp of result.gcode_store) {
|
||||
let date = new Date(resp.time * 1000);
|
||||
// Do something with date and resp.message ...
|
||||
}
|
||||
```
|
||||
|
||||
### Restart Server
|
||||
- HTTP command:\
|
||||
`POST /server/restart`
|
||||
|
||||
- Websocket command:
|
||||
`{jsonrpc: "2.0", method: "server.restart", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`"ok"` upon receipt of the restart request. After the request
|
||||
is returns, the server will restart. Any existing connection
|
||||
will be disconnected. A restart will result in the creation
|
||||
of a new server instance where the configuration is reloaded.
|
||||
|
||||
## Get Websocket ID
|
||||
- HTTP command:\
|
||||
Not Available
|
||||
|
||||
- Websocket command:
|
||||
`{jsonrpc: "2.0", method: "server.websocket.id", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
This connected websocket's unique identifer in the format shown below.
|
||||
Note that this API call is only available over the websocket.
|
||||
|
||||
```json
|
||||
{
|
||||
websocket_id: <int>
|
||||
}
|
||||
```
|
||||
|
||||
## Gcode Controls
|
||||
|
||||
### Run a gcode:
|
||||
@@ -217,7 +324,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
Will echo "Hello" to the terminal.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_gcode_script",
|
||||
`{jsonrpc: "2.0", method: "printer.gcode.script",
|
||||
params: {script: <gc>}, id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
@@ -230,7 +337,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`GET /printer/gcode/help`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_printer_gcode_help",
|
||||
`{jsonrpc: "2.0", method: "printer.gcode.help",
|
||||
params: {script: <gc>}, id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
@@ -245,7 +352,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/print/start?filename=<file name>`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_print_start",
|
||||
`{jsonrpc: "2.0", method: "printer.print.start",
|
||||
params: {filename: <file name>, id:<request id>}`
|
||||
|
||||
- Returns:\
|
||||
@@ -256,7 +363,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/print/pause`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_print_pause", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.print.pause", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
@@ -266,7 +373,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/print/resume`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_print_resume", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.print.resume", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
@@ -276,7 +383,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /printer/print/cancel`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_printer_print_cancel", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "printer.print.cancel", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok`
|
||||
@@ -288,7 +395,7 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /machine/shutdown`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_machine_shutdown", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "machine.shutdown", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
No return value as the server will shut down upon execution
|
||||
@@ -298,11 +405,25 @@ that uses promises to return responses and errors (see json-rcp.js).
|
||||
`POST /machine/reboot`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_machine_reboot", id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "machine.reboot", id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
No return value as the server will shut down upon execution
|
||||
|
||||
### Restart a system service
|
||||
Restarts a system service via `sudo systemctl restart <name>`. Currently
|
||||
only `moonraker` and `klipper` are allowed.
|
||||
|
||||
- HTTP command:\
|
||||
`POST /machine/services/restart?service=<service_name>`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.services.restart",
|
||||
params: {service: "service name"}, id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok` when complete. Note that if `moonraker` is chosen, the return
|
||||
value will be sent prior to the restart.
|
||||
|
||||
## File Operations
|
||||
|
||||
@@ -315,6 +436,7 @@ as the "gcodes" root. The following roots are available:
|
||||
- gcodes
|
||||
- config
|
||||
- config_examples (read-only)
|
||||
- docs (read-only)
|
||||
|
||||
Write operations (upload, delete, make directory, remove directory) are
|
||||
only available on the `gcodes` and config roots. Note that the `config` root
|
||||
@@ -332,7 +454,7 @@ path relative to the specified "root". Note that if the query st
|
||||
the "gcodes" file list by default.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_file_list", params: {root: "gcodes"}
|
||||
`{jsonrpc: "2.0", method: "server.files.list", params: {root: "gcodes"}
|
||||
, id: <request id>}`
|
||||
|
||||
If `params` are are omitted then the command will return the "gcodes"
|
||||
@@ -344,8 +466,8 @@ path relative to the specified "root". Note that if the query st
|
||||
```json
|
||||
[
|
||||
{filename: "file name",
|
||||
size: <file size>,
|
||||
modified: "last modified date",
|
||||
size: <file_size>,
|
||||
modified: <unix_time>,
|
||||
...]
|
||||
```
|
||||
|
||||
@@ -360,7 +482,7 @@ path relative to the specified "root". Note that if the query st
|
||||
`GET /server/files/metadata?filename=<filename>`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_file_metadata", params: {filename: "filename"}
|
||||
`{jsonrpc: "2.0", method: "server.files.metadata", params: {filename: "filename"}
|
||||
, id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
@@ -371,20 +493,25 @@ path relative to the specified "root". Note that if the query st
|
||||
```json
|
||||
{
|
||||
filename: "file name",
|
||||
size: <file size>,
|
||||
modified: "last modified date",
|
||||
size: <file_size>,
|
||||
modified: <unix_time>,
|
||||
slicer: "Slicer Name",
|
||||
first_layer_height: <in mm>,
|
||||
layer_height: <in mm>,
|
||||
object_height: <in mm>,
|
||||
estimated_time: <time in seconds>,
|
||||
filament_total: <in mm>,
|
||||
slicer_version: "<version>",
|
||||
first_layer_height: <mm>,
|
||||
first_layer_bed_temp: <C>,
|
||||
first_layer_extr_temp: <C>,
|
||||
layer_height: <mm>,
|
||||
object_height: <mm>,
|
||||
estimated_time: <time_in_seconds>,
|
||||
filament_total: <mm>,
|
||||
gcode_start_byte: <byte_location_of_first_gcode_command>,
|
||||
gcode_end_byte: <byte_location_of_last_gcode_command>,
|
||||
thumbnails: [
|
||||
{
|
||||
width: <in pixels>,
|
||||
height: <in pixels>,
|
||||
size: <length of string>,
|
||||
data: <base64 string>
|
||||
width: <in_pixels>,
|
||||
height: <in_pixels>,
|
||||
size: <length_of_string>,
|
||||
data: <base64_string>
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
@@ -396,18 +523,23 @@ Unlike `/server/files/list`, this command does not walk through
|
||||
subdirectories.
|
||||
|
||||
- HTTP command:\
|
||||
`GET /server/files/directory?path=gcodes/my_subdir`
|
||||
`GET /server/files/directory?path=gcodes/my_subdir&extended=true`
|
||||
|
||||
If the query string is omitted then the command will return
|
||||
the "gcodes" file list by default.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "get_directory", params: {path: "gcodes/my_subdir"}
|
||||
, id: <request id>}`
|
||||
`{jsonrpc: "2.0", method: "server.files.get_directory",
|
||||
params: {path: "gcodes/my_subdir", extended: true} ,
|
||||
id: <request id>}`
|
||||
|
||||
If the "params" are omitted then the command will return
|
||||
the "gcodes" file list by default.
|
||||
|
||||
The `extended` argument is optional, and defaults to false. If
|
||||
specified and set to true, then data returned for gcode files
|
||||
will also include metadata if it is available.
|
||||
|
||||
- Returns:\
|
||||
An object containing file and subdirectory information in the
|
||||
following format:
|
||||
@@ -417,14 +549,14 @@ subdirectories.
|
||||
files: [
|
||||
{
|
||||
filename: "file name",
|
||||
size: <file size>,
|
||||
modified: "last modified date"
|
||||
size: <file_size>,
|
||||
modified: <unix_time>
|
||||
}, ...
|
||||
],
|
||||
dirs: [
|
||||
{
|
||||
dirname: "directory name",
|
||||
modified: "last modified date"
|
||||
modified: <unix_time>
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -437,7 +569,7 @@ Creates a new directory at the specified path.
|
||||
`POST /server/files/directory?path=gcodes/my_new_dir`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_directory", params:
|
||||
`{jsonrpc: "2.0", method: "server.files.post_directory", params:
|
||||
{path: "gcodes/my_new_dir"}, id: <request id>}`
|
||||
|
||||
Returns:\
|
||||
@@ -450,7 +582,7 @@ Deletes a directory at the specified path.
|
||||
`DELETE /server/files/directory?path=gcodes/my_subdir`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "delete_directory", params:
|
||||
`{jsonrpc: "2.0", method: "server.files.delete_directory", params:
|
||||
{path: "gcodes/my_subdir"} , id: <request id>}`
|
||||
|
||||
If the specified directory contains files then the delete request
|
||||
@@ -490,7 +622,7 @@ in *moving* the source directory to the destination directory.
|
||||
&dest=gcodes/subdir/my_file.gcode`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_file_move", params:
|
||||
`{jsonrpc: "2.0", method: "server.files.move", params:
|
||||
{source: "gcodes/my_file.gcode",
|
||||
dest: "gcodes/subdir/my_file.gcode"}, id: <request id>}`
|
||||
|
||||
@@ -505,7 +637,7 @@ the source and destination should have the root prefixed.
|
||||
&dest=gcodes/subdir/my_file.gcode`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "post_file_copy", params:
|
||||
`{jsonrpc: "2.0", method: "server.files.copy", params:
|
||||
{source: "gcodes/my_file.gcode", dest: "gcodes/subdir/my_file.gcode"},
|
||||
id: <request id>}`
|
||||
|
||||
@@ -563,7 +695,11 @@ to delete a file in a subdirectory.
|
||||
`DELETE /server/files/gcodes/<file_name>`
|
||||
|
||||
- Websocket command:\
|
||||
Not Available
|
||||
`{jsonrpc: "2.0", method: "server.files.delete_file", params:
|
||||
{path: "gcodes/<file_name>"}, id: <request id>}`
|
||||
|
||||
If the gcode file exists within a subdirectory, the relative
|
||||
path should be included in the file name.
|
||||
|
||||
- Returns:\
|
||||
The HTTP request returns the name of the deleted file.
|
||||
@@ -585,7 +721,8 @@ to delete a file in a subdirectory.
|
||||
`DELETE /server/files/config/<file_name>`
|
||||
|
||||
- Websocket command:\
|
||||
Not Available
|
||||
`{jsonrpc: "2.0", method: "server.files.delete_file", params:
|
||||
{path: "config/<file_name>}, id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
The HTTP request returns the name of the deleted file.
|
||||
@@ -600,6 +737,16 @@ to delete a file in a subdirectory.
|
||||
- Returns:\
|
||||
The requested file
|
||||
|
||||
### Download Klipper documentation
|
||||
- HTTP command:\
|
||||
`GET /server/files/docs/<file_name>`
|
||||
|
||||
- Websocket command:\
|
||||
Not Available
|
||||
|
||||
- Returns:\
|
||||
The requested file
|
||||
|
||||
### Download klippy.log
|
||||
- HTTP command:\
|
||||
`GET /server/files/klippy.log`
|
||||
@@ -666,6 +813,262 @@ only be used once, making them relatively for inclusion in the query string.
|
||||
to any API endpoint. The query string should be added in the form of:
|
||||
`?token=randomly_generated_token`
|
||||
|
||||
## Update Manager APIs
|
||||
The following endpoints are availabe when the `[update_manager]` plugin has
|
||||
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.
|
||||
|
||||
- HTTP command:\
|
||||
`GET /machine/update/status?refresh=false`
|
||||
|
||||
If the query string is omitted then "refresh" will default
|
||||
to false.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.update.status",
|
||||
params: {refresh: false} , id: <request id>}`
|
||||
|
||||
If the "params" are omitted then "refresh" will default to false.
|
||||
|
||||
- Returns:\
|
||||
Status information in the following format:
|
||||
```json
|
||||
{
|
||||
'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>,
|
||||
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>,
|
||||
detached: <bool>,
|
||||
debug_enabled: <bool>
|
||||
},
|
||||
'client': {
|
||||
name: <string>,
|
||||
version: <string>,
|
||||
remote_version: <string>
|
||||
},
|
||||
'system': {
|
||||
package_count: <int>,
|
||||
package_list: <array>
|
||||
}
|
||||
},
|
||||
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
|
||||
- `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".
|
||||
- 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
|
||||
- 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
|
||||
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`.
|
||||
|
||||
- HTTP command:\
|
||||
`POST /machine/update/moonraker?include_deps=false`
|
||||
|
||||
If the query string is omitted then "include_deps" will default
|
||||
to false.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.update.moonraker",
|
||||
params: {include_deps: false}, id: <request id>}`
|
||||
|
||||
If the "params" are omitted then "include_deps" will default to false.
|
||||
|
||||
- Returns:\
|
||||
`ok` when complete
|
||||
|
||||
### Update Klipper
|
||||
Pulls the most recent version of Klipper from GitHub and restarts
|
||||
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.
|
||||
|
||||
- HTTP command:\
|
||||
`POST /machine/update/klipper?include_deps=false`
|
||||
|
||||
If the query string is omitted then "include_deps" will default
|
||||
to false.
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.update.klipper",
|
||||
params: {include_deps: false}, id: <request id>}`
|
||||
|
||||
If the "params" are omitted then "include_deps" will default to false.
|
||||
|
||||
- Returns:\
|
||||
`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.
|
||||
|
||||
- HTTP command:\
|
||||
`POST /machine/update/client`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.update.client",
|
||||
id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok` when complete
|
||||
|
||||
### Update System Packages
|
||||
Upgrades the system packages. Currently only `apt-get` is supported.
|
||||
|
||||
- HTTP command:\
|
||||
`POST /machine/update/system`
|
||||
|
||||
- Websocket command:\
|
||||
`{jsonrpc: "2.0", method: "machine.update.system",
|
||||
id: <request id>}`
|
||||
|
||||
- Returns:\
|
||||
`ok` when complete
|
||||
|
||||
## Power APIs
|
||||
The APIs below are available when the `[power]` plugin has been configured.
|
||||
|
||||
### Get Devices
|
||||
- HTTP command:\
|
||||
`GET /machine/device_power/devices`
|
||||
|
||||
- Websocket command:\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`
|
||||
|
||||
- Returns:\
|
||||
An array of objects containing info for each configured device.
|
||||
```json
|
||||
{
|
||||
devices: [
|
||||
{
|
||||
device: <device_name>,
|
||||
status: <device_status>,
|
||||
type: <device_type>
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Get Device Status
|
||||
- HTTP command:\
|
||||
`GET /machine/device_power/status?dev_one&dev_two`
|
||||
|
||||
- Websocket command:\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
|
||||
"params":{"dev_one":null, "dev_two": null}}`
|
||||
|
||||
- Returns:\
|
||||
An object containing status for each requested device
|
||||
```json
|
||||
{
|
||||
dev_one: <device_status>,
|
||||
dev_two: <device_status>,
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Power On Device(s)
|
||||
- HTTP command:\
|
||||
`POST /machine/device_power/on?dev_one&dev_two`
|
||||
|
||||
- Websocket command:\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
|
||||
"params":{"dev_one":null, "dev_two": null}}`
|
||||
|
||||
- Returns:\
|
||||
An object containing status for each requested device
|
||||
```json
|
||||
{
|
||||
dev_one: <device_status>,
|
||||
dev_two: <device_status>,
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Power Off Device(s)
|
||||
- HTTP command:\
|
||||
`POST /machine/device_power/off?dev_one&dev_two`
|
||||
|
||||
- Websocket command:\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
|
||||
"params":{"dev_one":null, "dev_two": null}}`
|
||||
|
||||
- Returns:\
|
||||
An object containing status for each requested device
|
||||
```json
|
||||
{
|
||||
dev_one: <device_status>,
|
||||
dev_two: <device_status>,
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Websocket notifications
|
||||
Printer generated events are sent over the websocket as JSON-RPC 2.0
|
||||
notifications. These notifications are sent to all connected clients
|
||||
@@ -696,6 +1099,16 @@ Status Subscriptions arrive as a "notify_status_update" notification:
|
||||
The structure of the status data is identical to the structure that is
|
||||
returned from an object query's "status" attribute.
|
||||
|
||||
### Klippy Ready:
|
||||
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
|
||||
|
||||
@@ -777,9 +1190,35 @@ Where `metadata` is an object in the following format:
|
||||
}
|
||||
```
|
||||
|
||||
### Update Manager Responses
|
||||
The update manager will send asyncronous messages to the client during an
|
||||
update:
|
||||
|
||||
`{jsonrpc: "2.0", method: "notify_update_response", params: [response]}`
|
||||
|
||||
Where `response` is an object int he following format:
|
||||
```json
|
||||
{
|
||||
application: <string>,
|
||||
proc_id: <int>,
|
||||
message: <string>,
|
||||
complete: <boolean>
|
||||
}
|
||||
```
|
||||
- The `application` field contains the name of application currently being
|
||||
updated. Generally this will be either "moonraker", "klipper", "system",
|
||||
or "client".
|
||||
- The `proc_id` field contains a unique id associated with the current update
|
||||
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.
|
||||
|
||||
# Appendix
|
||||
|
||||
### Websocket setup
|
||||
## Websocket setup
|
||||
All transmissions over the websocket are done via json using the JSON-RPC 2.0
|
||||
protocol. While the websever expects a json encoded string, one limitation
|
||||
of Eventlet's websocket is that it can not send string encoded frames. Thus
|
||||
@@ -800,13 +1239,13 @@ ws://host:port/websocket?token=<32 character base32 string>
|
||||
```
|
||||
|
||||
This is necessary as it isn't currently possible to add `X-Api-Key` to a
|
||||
websocket's request header.
|
||||
Websocket object's request header.
|
||||
|
||||
The following startup sequence is recommened for clients which make use of
|
||||
the websocket:
|
||||
1) Attempt to connect to `/websocket` until successful using a timer-like
|
||||
mechanism
|
||||
2) Once connected, query `/printer/info` (or `get_printer_info`) for the ready
|
||||
2) Once connected, query `/printer/info` (or `printer.info`) for the ready
|
||||
status.
|
||||
- If the response returns an error (such as 404), set a timeout for
|
||||
2 seconds and try again.
|
||||
@@ -818,8 +1257,121 @@ the websocket:
|
||||
get a description of the error from the `state_message` attribute
|
||||
- If `state == "shutdown"` then Klippy is in a shutdown state.
|
||||
- If `state == "startup"` then re-request printer info in 2s.
|
||||
- Repeat step 2s until Klipper reports ready. T
|
||||
- Client's should watch for the `notify_klippy_state_changed` event. If it reports
|
||||
- Repeat step 2 until Klipper reports ready.
|
||||
- Client's should watch for the `notify_klippy_disconnected` event. If it reports
|
||||
disconnected then Klippy has either been stopped or restarted. In this
|
||||
instance the client should repeat the steps above to determine when
|
||||
klippy is ready.
|
||||
klippy is ready.
|
||||
|
||||
## Basic Print Status
|
||||
An advanced client will likely use subscriptions and notifications
|
||||
to interact with Moonraker, however simple clients such as home automation
|
||||
software and embedded devices (ie: ESP32) may only wish to monitor the
|
||||
status of a print. Below is a high level walkthrough for receiving print state
|
||||
via polling.
|
||||
|
||||
- Set up a timer to poll at the desired interval. Depending on your use
|
||||
case, 1 to 2 seconds is recommended.
|
||||
- On each cycle, issue the following request:
|
||||
- `GET http://host/printer/objects/query?webhooks&virtual_sdcard&print_stats`\
|
||||
Or via json-rpc:\
|
||||
`{'jsonrpc': "2.0", 'method': "printer.objects.query", 'params':
|
||||
{'objects': {'webhooks': null, 'virtual_sdcard': null,
|
||||
'print_stats': null}}, id: <request id>}`
|
||||
- If the request returns an error or the returned `result.status` is an empty
|
||||
object printer objects are not available for query. Each queried object
|
||||
should be available in `result.status`. The client should check to make
|
||||
sure that all objects are received before proceeding.
|
||||
- Inspect `webhooks.ready`. If the value is not "ready" the printer
|
||||
is not available. `webhooks.message` contains a message pertaining
|
||||
to the current state.
|
||||
- If the printer is ready, inspect `print_stats.state`. It may be one
|
||||
of the following values:
|
||||
- "standby": No print in progress
|
||||
- "printing": The printer is currently printing
|
||||
- "paused": A print in progress has been paused
|
||||
- "error": The print exited with an error. `print_stats.message`
|
||||
contains a related error message
|
||||
- "complete": The last print has completed
|
||||
- If `print_stats.state` is not "standby" then `print_stats.filename`
|
||||
will report the name of the currently loaded file.
|
||||
- `print_stats.filename` can be used to fetch file metadata. It
|
||||
is only necessary to fetch metadata once per print.\
|
||||
`GET http://host/server/files/metadata?filename=<filename>`\
|
||||
Or via json-rpc:\
|
||||
`{jsonrpc: "2.0", method: "server.files.metadata",
|
||||
params: {filename: "filename"}
|
||||
, id: <request id>}`\
|
||||
If metadata extraction failed then this request will return an error.
|
||||
Some metadata fields are only populated for specific slicers, and
|
||||
unsupported slicers will only return the size and modifed date.
|
||||
- There are multiple ways to calculate the ETA, this example will use
|
||||
file progress, as it is possible calculate the ETA with or without
|
||||
metadata.
|
||||
- If `metadata.estimated_time` is available, the eta calculation can
|
||||
be done as:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let vsd = result.status.virtual_sdcard;
|
||||
let prog_time = vsd.progress * metadata.estimated_time;
|
||||
let eta = metadata.estimated_time - prog_time
|
||||
```
|
||||
Alternatively, one can simply subtract the print duration from
|
||||
the estimated time:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let pstats = result.status.print_status;
|
||||
let eta = metadata.estimated_time - pstats.print_duration;
|
||||
if (eta < 0)
|
||||
eta = 0;
|
||||
```
|
||||
- If no metadata is available, print duration and progress can be used to
|
||||
calculate the ETA:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let vsd = result.status.virtual_sdcard;
|
||||
let pstats = result.status.print_stats;
|
||||
let total_time = pstats.print_duration / vsd.progress;
|
||||
let eta = total_time - pstats.print_duration;
|
||||
```
|
||||
- It is possible to query additional object if a client wishes to display
|
||||
more information (ie: temperatures). See
|
||||
[printer_objects.md](printer_objects.md) for more information.
|
||||
|
||||
## Bed Mesh Coordinates
|
||||
The [bed_mesh](printer_objects.md#bed_mesh) printer object may be used
|
||||
to generate three dimensional coordinates of a probed area (or mesh).
|
||||
Below is an example (in javascript) of how to transform the data received
|
||||
from a bed_mesh object query into an array of 3D coordinates.
|
||||
```javascript
|
||||
// assume that we have executed an object query for bed_mesh and have the
|
||||
// result. This example generates 3D coordinates for the probed matrix,
|
||||
// however it would work with the mesh matrix as well
|
||||
function process_mesh(result) {
|
||||
let bed_mesh = result.status.bed_mesh
|
||||
let matrix = bed_mesh.probed_matrix;
|
||||
if (!(matrix instanceof Array) || matrix.length < 3 ||
|
||||
!(matrix[0] instanceof Array) || matrix[0].length < 3)
|
||||
// make sure that the matrix is valid
|
||||
return;
|
||||
let coordinates = [];
|
||||
let x_distance = (bed_mesh.mesh_max[0] - bed_mesh.mesh_min[0]) /
|
||||
(matrix[0].length - 1);
|
||||
let y_distance = (bed_mesh.mesh_max[1] - bed_mesh.mesh_min[1]) /
|
||||
(matrix.length - 1);
|
||||
let x_idx = 0;
|
||||
let y_idx = 0;
|
||||
for (const x_axis of matrix) {
|
||||
x_idx = 0;
|
||||
let y_coord = bed_mesh.mesh_min[1] + (y_idx * y_distance);
|
||||
for (const z_coord of x_axis) {
|
||||
let x_coord = bed_mesh.mesh_min[0] + (x_idx * x_distance);
|
||||
x_idx++;
|
||||
coordinates.push([x_coord, y_coord, z_coord]);
|
||||
}
|
||||
y_idx++;
|
||||
}
|
||||
}
|
||||
// Use the array of coordinates visualize the probed area
|
||||
// or mesh..
|
||||
```
|
||||
+119
-117
@@ -9,44 +9,48 @@ import mimetypes
|
||||
import logging
|
||||
import tornado
|
||||
from inspect import isclass
|
||||
from tornado.escape import url_unescape
|
||||
from tornado.routing import Rule, PathMatches, AnyMatches
|
||||
from utils import ServerError
|
||||
from websockets import WebsocketManager, WebSocket
|
||||
from websockets import WebRequest, WebsocketManager, WebSocket
|
||||
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
|
||||
from authorization import Authorization
|
||||
|
||||
# Max Upload Size of 200MB
|
||||
MAX_UPLOAD_SIZE = 200 * 1024 * 1024
|
||||
|
||||
# These endpoints are reserved for klippy/server communication only and are
|
||||
# not exposed via http or the websocket
|
||||
RESERVED_ENDPOINTS = [
|
||||
"list_endpoints", "gcode/subscribe_output"
|
||||
"list_endpoints", "gcode/subscribe_output",
|
||||
"register_remote_method"
|
||||
]
|
||||
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
|
||||
|
||||
# Status objects require special parsing
|
||||
def _status_parser(request):
|
||||
query_args = request.query_arguments
|
||||
def _status_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key, vals in query_args.items():
|
||||
parsed = []
|
||||
for v in vals:
|
||||
if v:
|
||||
parsed += v.decode().split(',')
|
||||
if parsed == []:
|
||||
parsed = None
|
||||
args[key] = parsed
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
val = request_handler.get_argument(key)
|
||||
if not val:
|
||||
args[key] = None
|
||||
else:
|
||||
args[key] = val.split(',')
|
||||
logging.debug(f"Parsed Arguments: {args}")
|
||||
return {'objects': args}
|
||||
|
||||
# Built-in Query String Parser
|
||||
def _default_parser(request):
|
||||
query_args = request.query_arguments
|
||||
def _default_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key, vals in query_args.items():
|
||||
if len(vals) != 1:
|
||||
raise tornado.web.HTTPError(404, "Invalid Query String")
|
||||
args[key] = vals[0].decode()
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
args[key] = request_handler.get_argument(key)
|
||||
return args
|
||||
|
||||
class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
@@ -82,11 +86,11 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
logging.exception(f"Unable to remove rule: {pattern}")
|
||||
|
||||
class APIDefinition:
|
||||
def __init__(self, endpoint, http_uri, ws_method,
|
||||
def __init__(self, endpoint, http_uri, ws_methods,
|
||||
request_methods, parser):
|
||||
self.endpoint = endpoint
|
||||
self.uri = http_uri
|
||||
self.ws_method = ws_method
|
||||
self.ws_methods = ws_methods
|
||||
if not isinstance(request_methods, list):
|
||||
request_methods = [request_methods]
|
||||
self.request_methods = request_methods
|
||||
@@ -98,6 +102,8 @@ class MoonrakerApp:
|
||||
self.tornado_server = None
|
||||
self.api_cache = {}
|
||||
self.registered_base_handlers = []
|
||||
self.max_upload_size = config.getint('max_upload_size', 200)
|
||||
self.max_upload_size *= 1024 * 1024
|
||||
|
||||
# Set Up Websocket and Authorization Managers
|
||||
self.wsm = WebsocketManager(self.server)
|
||||
@@ -106,86 +112,92 @@ class MoonrakerApp:
|
||||
mimetypes.add_type('text/plain', '.log')
|
||||
mimetypes.add_type('text/plain', '.gcode')
|
||||
mimetypes.add_type('text/plain', '.cfg')
|
||||
|
||||
debug = config.getboolean('enable_debug_logging', True)
|
||||
enable_cors = config.getboolean('enable_cors', False)
|
||||
|
||||
# Set up HTTP only requests
|
||||
self.mutable_router = MutableRouter(self)
|
||||
app_handlers = [
|
||||
(AnyMatches(), self.mutable_router),
|
||||
(r"/websocket", WebSocket,
|
||||
{'wsm': self.wsm, 'auth': self.auth}),
|
||||
(r"/api/version", EmulateOctoprintHandler,
|
||||
{'server': self.server, 'auth': self.auth})]
|
||||
(r"/websocket", WebSocket),
|
||||
(r"/api/version", EmulateOctoprintHandler)]
|
||||
|
||||
self.app = tornado.web.Application(
|
||||
app_handlers,
|
||||
serve_traceback=debug,
|
||||
websocket_ping_interval=10,
|
||||
websocket_ping_timeout=30,
|
||||
enable_cors=enable_cors)
|
||||
parent=self)
|
||||
self.get_handler_delegate = self.app.get_handler_delegate
|
||||
|
||||
# Register handlers
|
||||
logfile = config['cmd_args'].get('logfile')
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
logfile = config['system_args'].get('logfile')
|
||||
if logfile:
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
self.register_static_file_handler(
|
||||
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
|
||||
self.auth.register_handlers(self)
|
||||
|
||||
def listen(self, host, port):
|
||||
self.tornado_server = self.app.listen(
|
||||
port, address=host, max_body_size=MAX_UPLOAD_SIZE,
|
||||
port, address=host, max_body_size=self.max_upload_size,
|
||||
xheaders=True)
|
||||
|
||||
def get_server(self):
|
||||
return self.server
|
||||
|
||||
def get_auth(self):
|
||||
return self.auth
|
||||
|
||||
def get_websocket_manager(self):
|
||||
return self.wsm
|
||||
|
||||
async def close(self):
|
||||
if self.tornado_server is not None:
|
||||
self.tornado_server.stop()
|
||||
await self.tornado_server.close_all_connections()
|
||||
await self.wsm.close()
|
||||
self.auth.close()
|
||||
|
||||
def register_remote_handler(self, endpoint):
|
||||
if endpoint in RESERVED_ENDPOINTS:
|
||||
return
|
||||
api_def = self.api_cache.get(
|
||||
endpoint, self._create_api_definition(endpoint))
|
||||
api_def = self._create_api_definition(endpoint)
|
||||
if api_def.uri in self.registered_base_handlers:
|
||||
# reserved handler or already registered
|
||||
return
|
||||
logging.info(
|
||||
f"Registering remote endpoint: "
|
||||
f"({' '.join(api_def.request_methods)}) {api_def.uri}")
|
||||
self.wsm.register_handler(api_def)
|
||||
f"Registering remote endpoint - "
|
||||
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
|
||||
f"Websocket: {', '.join(api_def.ws_methods)}")
|
||||
self.wsm.register_remote_handler(api_def)
|
||||
params = {}
|
||||
params['server'] = self.server
|
||||
params['auth'] = self.auth
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['remote_callback'] = api_def.endpoint
|
||||
self.mutable_router.add_handler(
|
||||
api_def.uri, RemoteRequestHandler, params)
|
||||
self.registered_base_handlers.append(api_def.uri)
|
||||
|
||||
def register_local_handler(self, uri, ws_method, request_methods,
|
||||
callback, http_only=False):
|
||||
def register_local_handler(self, uri, request_methods,
|
||||
callback, protocol=["http", "websocket"]):
|
||||
if uri in self.registered_base_handlers:
|
||||
return
|
||||
api_def = self._create_api_definition(
|
||||
uri, ws_method, request_methods)
|
||||
logging.info(
|
||||
f"Registering local endpoint: "
|
||||
f"({' '.join(request_methods)}) {uri}")
|
||||
if not http_only:
|
||||
self.wsm.register_handler(api_def, callback)
|
||||
params = {}
|
||||
params['server'] = self.server
|
||||
params['auth'] = self.auth
|
||||
params['methods'] = request_methods
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['callback'] = callback
|
||||
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
|
||||
self.registered_base_handlers.append(uri)
|
||||
uri, request_methods, is_remote=False)
|
||||
msg = "Registering local endpoint"
|
||||
if "http" in protocol:
|
||||
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
|
||||
params = {}
|
||||
params['methods'] = request_methods
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['callback'] = callback
|
||||
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
|
||||
self.registered_base_handlers.append(uri)
|
||||
if "websocket" in protocol:
|
||||
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
|
||||
self.wsm.register_local_handler(api_def, callback)
|
||||
logging.info(msg)
|
||||
|
||||
def register_static_file_handler(self, pattern, file_path,
|
||||
can_delete=False, op_check_cb=None):
|
||||
def register_static_file_handler(self, pattern, file_path):
|
||||
if pattern[0] != "/":
|
||||
pattern = "/server/files/" + pattern
|
||||
if os.path.isfile(file_path):
|
||||
@@ -198,17 +210,11 @@ class MoonrakerApp:
|
||||
logging.info(f"Invalid file path: {file_path}")
|
||||
return
|
||||
logging.debug(f"Registering static file: ({pattern}) {file_path}")
|
||||
methods = ['GET']
|
||||
if can_delete:
|
||||
methods.append('DELETE')
|
||||
params = {
|
||||
'server': self.server, 'auth': self.auth,
|
||||
'path': file_path, 'methods': methods, 'op_check_cb': op_check_cb}
|
||||
params = {'path': file_path}
|
||||
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
|
||||
|
||||
def register_upload_handler(self, pattern):
|
||||
params = {'server': self.server, 'auth': self.auth}
|
||||
self.mutable_router.add_handler(pattern, FileUploadHandler, params)
|
||||
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
|
||||
|
||||
def remove_handler(self, endpoint):
|
||||
api_def = self.api_cache.get(endpoint)
|
||||
@@ -216,29 +222,49 @@ class MoonrakerApp:
|
||||
self.wsm.remove_handler(api_def.uri)
|
||||
self.mutable_router.remove_handler(api_def.ws_method)
|
||||
|
||||
def _create_api_definition(self, endpoint, ws_method=None,
|
||||
request_methods=['GET', 'POST']):
|
||||
def _create_api_definition(self, endpoint, request_methods=[],
|
||||
is_remote=True):
|
||||
if endpoint in self.api_cache:
|
||||
return self.api_cache[endpoint]
|
||||
if endpoint[0] == '/':
|
||||
uri = endpoint
|
||||
else:
|
||||
elif is_remote:
|
||||
uri = "/printer/" + endpoint
|
||||
if ws_method is None:
|
||||
ws_method = uri[1:].replace('/', '_')
|
||||
else:
|
||||
uri = "/server/" + endpoint
|
||||
ws_methods = []
|
||||
if is_remote:
|
||||
# Remote requests accept both GET and POST requests. These
|
||||
# requests execute the same callback, thus they resolve to
|
||||
# only a single websocket method.
|
||||
ws_methods.append(uri[1:].replace('/', '.'))
|
||||
request_methods = ['GET', 'POST']
|
||||
else:
|
||||
name_parts = uri[1:].split('/')
|
||||
if len(request_methods) > 1:
|
||||
for req_mthd in request_methods:
|
||||
func_name = req_mthd.lower() + "_" + name_parts[-1]
|
||||
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
|
||||
else:
|
||||
ws_methods.append(".".join(name_parts))
|
||||
if not is_remote and len(request_methods) != len(ws_methods):
|
||||
raise self.server.error(
|
||||
"Invalid API definition. Number of websocket methods must "
|
||||
"match the number of request methods")
|
||||
if endpoint.startswith("objects/"):
|
||||
parser = _status_parser
|
||||
else:
|
||||
parser = _default_parser
|
||||
api_def = APIDefinition(endpoint, uri, ws_method,
|
||||
|
||||
api_def = APIDefinition(endpoint, uri, ws_methods,
|
||||
request_methods, parser)
|
||||
self.api_cache[endpoint] = api_def
|
||||
return api_def
|
||||
|
||||
# ***** Dynamic Handlers*****
|
||||
class RemoteRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, remote_callback, server, auth, arg_parser):
|
||||
super(RemoteRequestHandler, self).initialize(server, auth)
|
||||
def initialize(self, remote_callback, arg_parser):
|
||||
super(RemoteRequestHandler, self).initialize()
|
||||
self.remote_callback = remote_callback
|
||||
self.query_parser = arg_parser
|
||||
|
||||
@@ -249,21 +275,19 @@ class RemoteRequestHandler(AuthorizedRequestHandler):
|
||||
await self._process_http_request()
|
||||
|
||||
async def _process_http_request(self):
|
||||
args = {}
|
||||
if self.request.query:
|
||||
args = self.query_parser(self.request)
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.server.make_request(
|
||||
self.remote_callback, args)
|
||||
WebRequest(self.remote_callback, args, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, callback, server, auth,
|
||||
methods, arg_parser):
|
||||
super(LocalRequestHandler, self).initialize(server, auth)
|
||||
def initialize(self, callback, methods, arg_parser):
|
||||
super(LocalRequestHandler, self).initialize()
|
||||
self.callback = callback
|
||||
self.methods = methods
|
||||
self.query_parser = arg_parser
|
||||
@@ -287,11 +311,11 @@ class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def _process_http_request(self, method):
|
||||
args = {}
|
||||
if self.request.query:
|
||||
args = self.query_parser(self.request)
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.callback(self.request.path, method, args)
|
||||
result = await self.callback(
|
||||
WebRequest(self.request.path, args, method, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
@@ -299,13 +323,6 @@ class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
|
||||
|
||||
class FileRequestHandler(AuthorizedFileHandler):
|
||||
def initialize(self, server, auth, path, methods,
|
||||
op_check_cb=None, default_filename=None):
|
||||
super(FileRequestHandler, self).initialize(
|
||||
server, auth, path, default_filename)
|
||||
self.methods = methods
|
||||
self.op_check_cb = op_check_cb
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
# The call below shold never return an empty string,
|
||||
# as the path should have already been validated to be
|
||||
@@ -315,35 +332,20 @@ class FileRequestHandler(AuthorizedFileHandler):
|
||||
"Content-Disposition", f"attachment; filename={basename}")
|
||||
|
||||
async def delete(self, path):
|
||||
if 'DELETE' not in self.methods:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
# Use the same method Tornado uses to validate the path
|
||||
self.path = self.parse_url_path(path)
|
||||
del path # make sure we don't refer to path instead of self.path again
|
||||
absolute_path = self.get_absolute_path(self.root, self.path)
|
||||
self.absolute_path = self.validate_absolute_path(
|
||||
self.root, absolute_path)
|
||||
|
||||
if self.op_check_cb is not None:
|
||||
try:
|
||||
await self.op_check_cb(self.absolute_path)
|
||||
except ServerError as e:
|
||||
if e.status_code == 403:
|
||||
raise tornado.web.HTTPError(
|
||||
403, "File is loaded, DELETE not permitted")
|
||||
|
||||
os.remove(self.absolute_path)
|
||||
base = self.request.path.lstrip("/").split("/")[2]
|
||||
filename = self.path.lstrip("/")
|
||||
path = self.request.path.lstrip("/").split("/", 2)[-1]
|
||||
path = url_unescape(path, plus=False)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
file_manager.notify_filelist_changed('delete_file', filename, base)
|
||||
try:
|
||||
filename = await file_manager.delete_file(path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise tornado.web.HTTPError(
|
||||
403, "File is loaded, DELETE not permitted")
|
||||
else:
|
||||
raise tornado.web.HTTPError(e.status_code, str(e))
|
||||
self.finish({'result': filename})
|
||||
|
||||
class FileUploadHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, server, auth):
|
||||
super(FileUploadHandler, self).initialize(server, auth)
|
||||
|
||||
async def post(self):
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
try:
|
||||
|
||||
+84
-38
@@ -8,6 +8,7 @@ import uuid
|
||||
import os
|
||||
import time
|
||||
import ipaddress
|
||||
import re
|
||||
import logging
|
||||
import tornado
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
@@ -26,6 +27,11 @@ class Authorization:
|
||||
self.trusted_connections = {}
|
||||
self.access_tokens = {}
|
||||
|
||||
# Get allowed cors domains
|
||||
cors_cfg = config.get('cors_domains', "").strip()
|
||||
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
|
||||
for d in cors_cfg.split('\n')if d.strip()]
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
@@ -52,11 +58,13 @@ class Authorization:
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges])
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Auth Enabled: {self.auth_enabled}\n"
|
||||
f"Trusted Clients:\n{t_clients}")
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
@@ -65,18 +73,19 @@ class Authorization:
|
||||
def register_handlers(self, app):
|
||||
# Register Authorization Endpoints
|
||||
app.register_local_handler(
|
||||
"/access/api_key", None, ['GET', 'POST'],
|
||||
self._handle_apikey_request, http_only=True)
|
||||
"/access/api_key", ['GET', 'POST'],
|
||||
self._handle_apikey_request, protocol=['http'])
|
||||
app.register_local_handler(
|
||||
"/access/oneshot_token", None, ['GET'],
|
||||
self._handle_token_request, http_only=True)
|
||||
"/access/oneshot_token", ['GET'],
|
||||
self._handle_token_request, protocol=['http'])
|
||||
|
||||
async def _handle_apikey_request(self, path, method, args):
|
||||
if method.upper() == 'POST':
|
||||
async def _handle_apikey_request(self, web_request):
|
||||
action = web_request.get_action()
|
||||
if action.upper() == 'POST':
|
||||
self.api_key = self._create_api_key()
|
||||
return self.api_key
|
||||
|
||||
async def _handle_token_request(self, path, method, args):
|
||||
async def _handle_token_request(self, web_request):
|
||||
return self.get_access_token()
|
||||
|
||||
def _read_api_key(self):
|
||||
@@ -175,63 +184,100 @@ class Authorization:
|
||||
return True
|
||||
return False
|
||||
|
||||
def check_cors(self, origin, request=None):
|
||||
if origin is None:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
if match is not None:
|
||||
if match.group() == origin:
|
||||
logging.debug(f"CORS Pattern Matched, origin: {origin} "
|
||||
f" | pattern: {regex}")
|
||||
self._set_cors_headers(origin, request)
|
||||
return True
|
||||
else:
|
||||
logging.debug(f"Partial Cors Match: {match.group()}")
|
||||
else:
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def _set_cors_headers(self, origin, request):
|
||||
if request is None:
|
||||
return
|
||||
request.set_header("Access-Control-Allow-Origin", origin)
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def close(self):
|
||||
self.prune_handler.stop()
|
||||
|
||||
class AuthorizedRequestHandler(tornado.web.RequestHandler):
|
||||
def initialize(self, server, auth):
|
||||
self.server = server
|
||||
self.auth = auth
|
||||
def initialize(self):
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
self.wsm = app.get_websocket_manager()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
# it is necessary to look up the parent app here,
|
||||
# as initialize() may not yet be called
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def set_default_headers(self):
|
||||
if self.settings['enable_cors']:
|
||||
self.set_header("Access-Control-Allow-Origin", "*")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.settings['enable_cors']:
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedRequestHandler, self).options()
|
||||
|
||||
def get_associated_websocket(self):
|
||||
# Return associated websocket connection if an id
|
||||
# was provided by the request
|
||||
conn = None
|
||||
conn_id = self.get_argument('connection_id', None)
|
||||
if conn_id is not None:
|
||||
try:
|
||||
conn_id = int(conn_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
conn = self.wsm.get_websocket(conn_id)
|
||||
return conn
|
||||
|
||||
# Due to the way Python treats multiple inheritance its best
|
||||
# to create a separate authorized handler for serving files
|
||||
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
|
||||
def initialize(self, server, auth, path, default_filename=None):
|
||||
def initialize(self, path, default_filename=None):
|
||||
super(AuthorizedFileHandler, self).initialize(path, default_filename)
|
||||
self.server = server
|
||||
self.auth = auth
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def set_default_headers(self):
|
||||
if self.settings['enable_cors']:
|
||||
self.set_header("Access-Control-Allow-Origin", "*")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.settings['enable_cors']:
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
|
||||
@@ -31,6 +31,15 @@ class ConfigHelper:
|
||||
def __contains__(self, key):
|
||||
return key in self.config
|
||||
|
||||
def get_name(self):
|
||||
return self.section
|
||||
|
||||
def get_options(self):
|
||||
return dict(self.config[self.section])
|
||||
|
||||
def get_prefix_sections(self, prefix):
|
||||
return [s for s in self.sections() if s.startswith(prefix)]
|
||||
|
||||
def getsection(self, section):
|
||||
if section not in self.config:
|
||||
raise ConfigError(f"No section [{section}] in config")
|
||||
@@ -64,9 +73,19 @@ class ConfigHelper:
|
||||
return self._get_item(
|
||||
self.config[self.section].getfloat, option, default)
|
||||
|
||||
def get_configuration(server, cmd_line_args):
|
||||
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 get_configuration(server, system_args):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(
|
||||
cmd_line_args.configfile))
|
||||
system_args.configfile))
|
||||
if not os.path.isfile(cfg_file_path):
|
||||
raise ConfigError(f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
@@ -83,5 +102,7 @@ def get_configuration(server, cmd_line_args):
|
||||
if server_cfg.get('enable_debug_logging', True):
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
|
||||
config['cmd_args'] = {'logfile': cmd_line_args.logfile}
|
||||
config['system_args'] = {
|
||||
'logfile': system_args.logfile,
|
||||
'software_version': system_args.software_version}
|
||||
return ConfigHelper(server, config, 'server')
|
||||
Regular → Executable
+196
-83
@@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
@@ -13,7 +14,8 @@ import logging
|
||||
import json
|
||||
import confighelper
|
||||
import utils
|
||||
from tornado import iostream
|
||||
import asyncio
|
||||
from tornado import iostream, gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.util import TimeoutError
|
||||
from tornado.locks import Event
|
||||
@@ -26,7 +28,7 @@ MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
|
||||
CORE_PLUGINS = [
|
||||
'file_manager', 'klippy_apis', 'machine',
|
||||
'temperature_store', 'shell_command']
|
||||
'data_store', 'shell_command']
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
@@ -46,17 +48,12 @@ class Server:
|
||||
'klippy_uds_address', "/tmp/klippy_uds")
|
||||
self.klippy_connection = KlippyConnection(
|
||||
self.process_command, self.on_connection_closed)
|
||||
self.klippy_info = {}
|
||||
self.init_list = []
|
||||
self.init_handle = None
|
||||
self.init_attempts = 0
|
||||
self.klippy_state = "disconnected"
|
||||
|
||||
# XXX - currently moonraker maintains a superset of all
|
||||
# subscriptions, the results of which are forwarded to all
|
||||
# connected websockets. A better implementation would open a
|
||||
# unique unix domain socket for each websocket client and
|
||||
# allow Klipper to forward only those subscriptions back to
|
||||
# correct client.
|
||||
self.all_subscriptions = {}
|
||||
self.subscriptions = {}
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
@@ -66,15 +63,23 @@ class Server:
|
||||
self.register_upload_handler = app.register_upload_handler
|
||||
self.ioloop = IOLoop.current()
|
||||
|
||||
self.register_endpoint(
|
||||
"/server/info", ['GET'], self._handle_info_request)
|
||||
self.register_endpoint(
|
||||
"/server/restart", ['POST'], self._handle_server_restart)
|
||||
|
||||
# Setup remote methods accessable to Klippy. Note that all
|
||||
# registered remote methods should be of the notification type,
|
||||
# they do not return a response to Klippy after execution
|
||||
self.pending_requests = {}
|
||||
self.remote_methods = {}
|
||||
self.klippy_reg_methods = []
|
||||
self.register_remote_method(
|
||||
'process_gcode_response', self._process_gcode_response)
|
||||
'process_gcode_response', self._process_gcode_response,
|
||||
need_klippy_reg=False)
|
||||
self.register_remote_method(
|
||||
'process_status_update', self._process_status_update)
|
||||
'process_status_update', self._process_status_update,
|
||||
need_klippy_reg=False)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
@@ -82,8 +87,10 @@ class Server:
|
||||
self._load_plugins(config)
|
||||
|
||||
def start(self):
|
||||
hostname, hostport = self.get_host_info()
|
||||
logging.info(
|
||||
f"Starting Moonraker on ({self.host}, {self.port})")
|
||||
f"Starting Moonraker on ({self.host}, {hostport}), "
|
||||
f"Hostname: {hostname}")
|
||||
self.moonraker_app.listen(self.host, self.port)
|
||||
self.server_running = True
|
||||
self.ioloop.spawn_callback(self._connect_klippy)
|
||||
@@ -95,10 +102,10 @@ class Server:
|
||||
self.load_plugin(config, plugin)
|
||||
|
||||
# check for optional plugins
|
||||
opt_sections = set(config.sections()) - \
|
||||
set(['server', 'authorization', 'cmd_args'])
|
||||
opt_sections = set([s.split()[0] for s in config.sections()]) - \
|
||||
set(['server', 'authorization', 'system_args'])
|
||||
for section in opt_sections:
|
||||
self.load_plugin(config[section], section, None)
|
||||
self.load_plugin(config, section, None)
|
||||
|
||||
def load_plugin(self, config, plugin_name, default=Sentinel):
|
||||
if plugin_name in self.plugins:
|
||||
@@ -114,11 +121,16 @@ class Server:
|
||||
return default
|
||||
module = importlib.import_module("plugins." + plugin_name)
|
||||
try:
|
||||
load_func = getattr(module, "load_plugin")
|
||||
func_name = "load_plugin"
|
||||
if hasattr(module, "load_plugin_multi"):
|
||||
func_name = "load_plugin_multi"
|
||||
if plugin_name not in CORE_PLUGINS and func_name == "load_plugin":
|
||||
config = config[plugin_name]
|
||||
load_func = getattr(module, func_name)
|
||||
plugin = load_func(config)
|
||||
except Exception:
|
||||
msg = f"Unable to load plugin ({plugin_name})"
|
||||
logging.info(msg)
|
||||
logging.exception(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
@@ -140,15 +152,27 @@ class Server:
|
||||
for evt in events:
|
||||
self.ioloop.spawn_callback(evt, *args)
|
||||
|
||||
def register_remote_method(self, method_name, cb):
|
||||
def register_remote_method(self, method_name, cb, need_klippy_reg=True):
|
||||
if method_name in self.remote_methods:
|
||||
# XXX - may want to raise an exception here
|
||||
logging.info(f"Remote method ({method_name}) already registered")
|
||||
return
|
||||
self.remote_methods[method_name] = cb
|
||||
if need_klippy_reg:
|
||||
# These methods need to be registered with Klippy
|
||||
self.klippy_reg_methods.append(method_name)
|
||||
|
||||
def get_host_info(self):
|
||||
hostname = socket.gethostname()
|
||||
return hostname, self.port
|
||||
|
||||
def get_klippy_info(self):
|
||||
return dict(self.klippy_info)
|
||||
|
||||
# ***** Klippy Connection *****
|
||||
async def _connect_klippy(self):
|
||||
if not self.server_running:
|
||||
return
|
||||
ret = await self.klippy_connection.connect(self.klippy_address)
|
||||
if not ret:
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
@@ -160,10 +184,10 @@ class Server:
|
||||
method = cmd.get('method', None)
|
||||
if method is not None:
|
||||
# This is a remote method called from klippy
|
||||
cb = self.remote_methods.get(method, None)
|
||||
if cb is not None:
|
||||
if method in self.remote_methods:
|
||||
params = cmd.get('params', {})
|
||||
cb(**params)
|
||||
self.ioloop.spawn_callback(
|
||||
self._execute_method, method, **params)
|
||||
else:
|
||||
logging.info(f"Unknown method received: {method}")
|
||||
return
|
||||
@@ -184,17 +208,31 @@ class Server:
|
||||
result = ServerError(err, 400)
|
||||
request.notify(result)
|
||||
|
||||
async def _execute_method(self, method_name, **kwargs):
|
||||
try:
|
||||
ret = self.remote_methods[method_name](**kwargs)
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(f"Error running remote method: {method_name}")
|
||||
|
||||
def on_connection_closed(self):
|
||||
self.init_list = []
|
||||
self.klippy_state = "disconnected"
|
||||
for request in self.pending_requests.values():
|
||||
request.notify(ServerError("Klippy Disconnected", 503))
|
||||
self.pending_requests = {}
|
||||
self.subscriptions = {}
|
||||
logging.info("Klippy Connection Removed")
|
||||
self.send_event("server:klippy_disconnect")
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
if self.init_handle is not None:
|
||||
self.ioloop.remove_timeout(self.init_handle)
|
||||
if self.server_running:
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
|
||||
async def _initialize(self):
|
||||
if not self.server_running:
|
||||
return
|
||||
await self._check_ready()
|
||||
await self._request_endpoints()
|
||||
# Subscribe to "webhooks"
|
||||
@@ -217,14 +255,16 @@ class Server:
|
||||
else:
|
||||
logging.info("GCode Output Subscribed")
|
||||
self.init_list.append("gcode_output_sub")
|
||||
if "klippy_ready" in self.init_list:
|
||||
# Moonraker is enabled in the Klippy module
|
||||
# and Klippy is ready. We can stop the init
|
||||
# procedure.
|
||||
if "klippy_ready" in self.init_list or \
|
||||
not self.klippy_connection.is_connected():
|
||||
# Either Klippy is ready or the connection dropped
|
||||
# during initialization. Exit initialization
|
||||
self.init_attempts = 0
|
||||
self.init_handle = None
|
||||
else:
|
||||
self.init_attempts += 1
|
||||
self.ioloop.call_later(INIT_TIME, self._initialize)
|
||||
self.init_handle = self.ioloop.call_later(
|
||||
INIT_TIME, self._initialize)
|
||||
|
||||
async def _request_endpoints(self):
|
||||
result = await self.klippy_apis.list_endpoints(default=None)
|
||||
@@ -246,20 +286,21 @@ class Server:
|
||||
f"Klippy may have experienced an error during startup.\n"
|
||||
f"Please check klippy.log for more information")
|
||||
return
|
||||
self.klippy_info = dict(result)
|
||||
self.klippy_state = result.get('state', "unknown")
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
# Update filemanager fixed paths
|
||||
fixed_paths = {k: result[k] for k in
|
||||
['klipper_path', 'python_path',
|
||||
'log_file', 'config_file']}
|
||||
file_manager = self.lookup_plugin('file_manager')
|
||||
file_manager.update_fixed_paths(fixed_paths)
|
||||
is_ready = result.get('state', "") == "ready"
|
||||
if is_ready:
|
||||
self.send_event("server:klippy_identified")
|
||||
if self.klippy_state == "ready":
|
||||
await self._verify_klippy_requirements()
|
||||
logging.info("Klippy ready")
|
||||
self.klippy_state = "ready"
|
||||
self.init_list.append('klippy_ready')
|
||||
# register methods with klippy
|
||||
for method in self.klippy_reg_methods:
|
||||
try:
|
||||
await self.klippy_apis.register_method(method)
|
||||
except ServerError:
|
||||
logging.exception(f"Unable to register method '{method}'")
|
||||
self.send_event("server:klippy_ready")
|
||||
elif self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
|
||||
self.init_attempts <= MAX_LOG_ATTEMPTS:
|
||||
@@ -292,8 +333,7 @@ class Server:
|
||||
vsd_path = vsd_config.get('path', None)
|
||||
if vsd_path is not None:
|
||||
file_manager = self.lookup_plugin('file_manager')
|
||||
file_manager.register_directory(
|
||||
'gcodes', vsd_path, can_delete=True)
|
||||
file_manager.register_directory('gcodes', vsd_path)
|
||||
else:
|
||||
logging.info(
|
||||
"Configuration for [virtual_sdcard] not found,"
|
||||
@@ -311,49 +351,104 @@ class Server:
|
||||
logging.info("Klippy has shutdown")
|
||||
self.send_event("server:klippy_shutdown")
|
||||
self.klippy_state = state
|
||||
self.send_event("server:status_update", status)
|
||||
for conn, sub in self.subscriptions.items():
|
||||
conn_status = {}
|
||||
for name, fields in sub.items():
|
||||
if name in status:
|
||||
val = status[name]
|
||||
if fields is None:
|
||||
conn_status[name] = dict(val)
|
||||
else:
|
||||
conn_status[name] = {
|
||||
k: v for k, v in val.items() if k in fields}
|
||||
conn.send_status(conn_status)
|
||||
|
||||
async def make_request(self, rpc_method, params):
|
||||
# XXX - This adds the "response_template" to a subscription
|
||||
# request and tracks all subscriptions so that each
|
||||
# client gets what its requesting. In the future we should
|
||||
# track subscriptions per client and send clients only
|
||||
# the data they are asking for.
|
||||
async def make_request(self, web_request):
|
||||
rpc_method = web_request.get_endpoint()
|
||||
if rpc_method == "objects/subscribe":
|
||||
for obj, items in params.get('objects', {}).items():
|
||||
if obj in self.all_subscriptions:
|
||||
pi = self.all_subscriptions[obj]
|
||||
return await self._request_subscripton(web_request)
|
||||
else:
|
||||
return await self._request_standard(web_request)
|
||||
|
||||
async def _request_subscripton(self, web_request):
|
||||
args = web_request.get_args()
|
||||
conn = web_request.get_connection()
|
||||
|
||||
# Build the subscription request from a superset of all client
|
||||
# subscriptions
|
||||
sub = args.get('objects', {})
|
||||
if conn is None:
|
||||
raise self.error(
|
||||
"No connection associated with subscription request")
|
||||
self.subscriptions[conn] = sub
|
||||
all_subs = {}
|
||||
# request superset of all client subscriptions
|
||||
for sub in self.subscriptions.values():
|
||||
for obj, items in sub.items():
|
||||
if obj in all_subs:
|
||||
pi = all_subs[obj]
|
||||
if items is None or pi is None:
|
||||
self.all_subscriptions[obj] = None
|
||||
all_subs[obj] = None
|
||||
else:
|
||||
uitems = list(set(pi) | set(items))
|
||||
self.all_subscriptions[obj] = uitems
|
||||
all_subs[obj] = uitems
|
||||
else:
|
||||
self.all_subscriptions[obj] = items
|
||||
params['objects'] = dict(self.all_subscriptions)
|
||||
params['response_template'] = {'method': "process_status_update"}
|
||||
all_subs[obj] = items
|
||||
args['objects'] = all_subs
|
||||
args['response_template'] = {'method': "process_status_update"}
|
||||
|
||||
base_request = BaseRequest(rpc_method, params)
|
||||
result = await self._request_standard(web_request)
|
||||
|
||||
# prune the status response
|
||||
pruned_status = {}
|
||||
all_status = result['status']
|
||||
sub = self.subscriptions.get(conn, {})
|
||||
for obj, fields in all_status.items():
|
||||
if obj in sub:
|
||||
valid_fields = sub[obj]
|
||||
if valid_fields is None:
|
||||
pruned_status[obj] = fields
|
||||
else:
|
||||
pruned_status[obj] = {k: v for k, v in fields.items()
|
||||
if k in valid_fields}
|
||||
result['status'] = pruned_status
|
||||
return result
|
||||
|
||||
async def _request_standard(self, web_request):
|
||||
rpc_method = web_request.get_endpoint()
|
||||
args = web_request.get_args()
|
||||
# Create a base klippy request
|
||||
base_request = BaseRequest(rpc_method, args)
|
||||
self.pending_requests[base_request.id] = base_request
|
||||
self.ioloop.spawn_callback(
|
||||
self.klippy_connection.send_request, base_request)
|
||||
result = await base_request.wait()
|
||||
return result
|
||||
return await base_request.wait()
|
||||
|
||||
def remove_subscription(self, conn):
|
||||
self.subscriptions.pop(conn, None)
|
||||
|
||||
async def _stop_server(self):
|
||||
# XXX - Currently this function is not used.
|
||||
# Should I expose functionality to shutdown
|
||||
# or restart the server, or simply remove this?
|
||||
logging.info(
|
||||
"Shutting Down Webserver")
|
||||
for plugin in self.plugins:
|
||||
self.server_running = False
|
||||
for name, plugin in self.plugins.items():
|
||||
if hasattr(plugin, "close"):
|
||||
await plugin.close()
|
||||
ret = plugin.close()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.klippy_connection.close()
|
||||
if self.server_running:
|
||||
self.server_running = False
|
||||
await self.moonraker_app.close()
|
||||
self.ioloop.stop()
|
||||
while self.klippy_state != "disconnected":
|
||||
await gen.sleep(.1)
|
||||
await self.moonraker_app.close()
|
||||
self.ioloop.stop()
|
||||
|
||||
async def _handle_server_restart(self, web_request):
|
||||
self.ioloop.spawn_callback(self._stop_server)
|
||||
return "ok"
|
||||
|
||||
async def _handle_info_request(self, web_request):
|
||||
return {
|
||||
'klippy_connected': self.klippy_connection.is_connected(),
|
||||
'klippy_state': self.klippy_state,
|
||||
'plugins': list(self.plugins.keys())}
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, on_recd, on_close):
|
||||
@@ -456,12 +551,21 @@ def main():
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
cmd_line_args = parser.parse_args()
|
||||
parser.add_argument(
|
||||
"-n", "--nologfile", action='store_true',
|
||||
help="disable logging to a file")
|
||||
system_args = parser.parse_args()
|
||||
|
||||
# Setup Logging
|
||||
log_file = os.path.normpath(os.path.expanduser(cmd_line_args.logfile))
|
||||
cmd_line_args.logfile = log_file
|
||||
ql = utils.setup_logging(log_file)
|
||||
version = utils.get_software_version()
|
||||
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)
|
||||
|
||||
if sys.version_info < (3, 7):
|
||||
msg = f"Moonraker requires Python 3.7 or above. " \
|
||||
@@ -473,20 +577,29 @@ def main():
|
||||
|
||||
# Start IOLoop and Server
|
||||
io_loop = IOLoop.current()
|
||||
try:
|
||||
server = Server(cmd_line_args)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
ql.stop()
|
||||
exit(1)
|
||||
try:
|
||||
server.start()
|
||||
io_loop.start()
|
||||
except Exception:
|
||||
logging.exception("Server Running Error")
|
||||
estatus = 0
|
||||
while True:
|
||||
try:
|
||||
server = Server(system_args)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
estatus = 1
|
||||
break
|
||||
try:
|
||||
server.start()
|
||||
io_loop.start()
|
||||
except Exception:
|
||||
logging.exception("Server Running Error")
|
||||
estatus = 1
|
||||
break
|
||||
# Since we are running outside of the the server
|
||||
# it is ok to use a blocking sleep here
|
||||
time.sleep(.5)
|
||||
logging.info("Attempting Server Restart...")
|
||||
io_loop.close(True)
|
||||
logging.info("Server Shutdown")
|
||||
ql.stop()
|
||||
exit(estatus)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
# Heater sensor temperature storage
|
||||
# Klipper data logging and storage storage
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
import time
|
||||
from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
TEMPERATURE_UPDATE_MS = 1000
|
||||
TEMPERATURE_STORE_SIZE = 20 * 60
|
||||
|
||||
class TemperatureStore:
|
||||
MAX_GCODE_LINES = 1000
|
||||
|
||||
class DataStore:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps = {}
|
||||
self.gcode_queue = deque(maxlen=MAX_GCODE_LINES)
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
@@ -23,13 +27,18 @@ class TemperatureStore:
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self._update_gcode_store)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_sensors)
|
||||
|
||||
# Register endpoint
|
||||
# Register endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/temperature_store", "server_temperature_store", ['GET'],
|
||||
"/server/temperature_store", ['GET'],
|
||||
self._handle_temp_store_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/gcode_store", ['GET'],
|
||||
self._handle_gcode_store_request)
|
||||
|
||||
async def _init_sensors(self):
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
@@ -89,7 +98,7 @@ class TemperatureStore:
|
||||
self.temperature_store[sensor]['temperatures'].append(temp)
|
||||
self.temperature_store[sensor]['targets'].append(target)
|
||||
|
||||
async def _handle_temp_store_request(self, path, method, args):
|
||||
async def _handle_temp_store_request(self, web_request):
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
store[name] = {k: list(v) for k, v in sensor.items()}
|
||||
@@ -98,5 +107,17 @@ class TemperatureStore:
|
||||
async def close(self):
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _update_gcode_store(self, response):
|
||||
curtime = time.time()
|
||||
self.gcode_queue.append({'message': response, 'time': curtime})
|
||||
|
||||
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:]
|
||||
else:
|
||||
res = list(self.gcode_queue)
|
||||
return {'gcode_store': res}
|
||||
|
||||
def load_plugin(config):
|
||||
return TemperatureStore(config)
|
||||
return DataStore(config)
|
||||
+335
-182
@@ -6,59 +6,64 @@
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import time
|
||||
import io
|
||||
import zipfile
|
||||
import logging
|
||||
import json
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.locks import Lock
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.locks import Event
|
||||
|
||||
VALID_GCODE_EXTS = ['gcode', 'g', 'gco']
|
||||
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
|
||||
FULL_ACCESS_ROOTS = ["gcodes", "config"]
|
||||
METADATA_SCRIPT = os.path.join(
|
||||
os.path.dirname(__file__), "../../scripts/extract_metadata.py")
|
||||
METADATA_SCRIPT = os.path.normpath(os.path.join(
|
||||
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
|
||||
|
||||
class FileManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.file_paths = {}
|
||||
self.file_lists = {}
|
||||
self.gcode_metadata = MetadataStorage(self.server)
|
||||
self.fixed_path_args = {}
|
||||
|
||||
# Register file management endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/files/list", "file_list", ['GET'],
|
||||
self._handle_filelist_request)
|
||||
"/server/files/list", ['GET'], self._handle_filelist_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/metadata", "file_metadata", ['GET'],
|
||||
self._handle_metadata_request)
|
||||
"/server/files/metadata", ['GET'], self._handle_metadata_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/directory", "directory", ['GET', 'POST', 'DELETE'],
|
||||
"/server/files/directory", ['GET', 'POST', 'DELETE'],
|
||||
self._handle_directory_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/move", "file_move", ['POST'],
|
||||
self._handle_file_move_copy)
|
||||
"/server/files/move", ['POST'], self._handle_file_move_copy)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/copy", "file_copy", ['POST'],
|
||||
self._handle_file_move_copy)
|
||||
"/server/files/copy", ['POST'], self._handle_file_move_copy)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
|
||||
protocol=["websocket"])
|
||||
# Register APIs to handle file uploads
|
||||
self.server.register_upload_handler("/server/files/upload")
|
||||
self.server.register_upload_handler("/api/files/local")
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_identified", self._update_fixed_paths)
|
||||
|
||||
# Register Klippy Configuration Path
|
||||
config_path = config.get('config_path', None)
|
||||
if config_path is not None:
|
||||
ret = self.register_directory(
|
||||
'config', config_path, can_delete=True)
|
||||
ret = self.register_directory('config', config_path)
|
||||
if not ret:
|
||||
raise config.error(
|
||||
"Option 'config_path' is not a valid directory")
|
||||
|
||||
def update_fixed_paths(self, paths):
|
||||
def _update_fixed_paths(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
paths = {k: kinfo.get(k) for k in
|
||||
['klipper_path', 'python_path',
|
||||
'log_file', 'config_file']}
|
||||
if paths == self.fixed_path_args:
|
||||
# No change in fixed paths
|
||||
return
|
||||
self.fixed_path_args = dict(paths)
|
||||
self.fixed_path_args = paths
|
||||
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
|
||||
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
|
||||
|
||||
@@ -67,36 +72,44 @@ class FileManager:
|
||||
if klipper_path is not None:
|
||||
example_cfg_path = os.path.join(klipper_path, "config")
|
||||
self.register_directory("config_examples", example_cfg_path)
|
||||
docs_path = os.path.join(klipper_path, "docs")
|
||||
self.register_directory("docs", docs_path)
|
||||
|
||||
# Register log path
|
||||
log_file = paths.get('log_file')
|
||||
log_path = os.path.normpath(os.path.expanduser(log_file))
|
||||
self.server.register_static_file_handler("klippy.log", log_path)
|
||||
|
||||
def register_directory(self, base, path, can_delete=False):
|
||||
op_check_cb = None
|
||||
if base == 'gcodes':
|
||||
op_check_cb = self._handle_operation_check
|
||||
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:
|
||||
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 ({base}) 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
|
||||
if path != self.file_paths.get(base, ""):
|
||||
self.file_paths[base] = path
|
||||
self.server.register_static_file_handler(
|
||||
base, path, can_delete=can_delete, op_check_cb=op_check_cb)
|
||||
try:
|
||||
self._update_file_list(base=base)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Unable to initialize file list: <{base}>")
|
||||
permissions = os.R_OK
|
||||
if root in FULL_ACCESS_ROOTS:
|
||||
permissions |= os.W_OK
|
||||
if not os.access(path, permissions):
|
||||
logging.info(
|
||||
f"\nMoonraker does not have permission to access path "
|
||||
f"({path}) for ({root}).")
|
||||
return False
|
||||
if path != self.file_paths.get(root, ""):
|
||||
self.file_paths[root] = path
|
||||
self.server.register_static_file_handler(root, path)
|
||||
if root == "gcodes":
|
||||
# scan metadata
|
||||
self.gcode_metadata.update_gcode_path(path)
|
||||
try:
|
||||
self.get_file_list("gcodes")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Unable to initialize gcode metadata")
|
||||
return True
|
||||
|
||||
def get_sd_directory(self):
|
||||
@@ -105,55 +118,68 @@ class FileManager:
|
||||
def get_fixed_path_args(self):
|
||||
return dict(self.fixed_path_args)
|
||||
|
||||
async def _handle_filelist_request(self, path, method, args):
|
||||
root = args.get('root', "gcodes")
|
||||
return self.get_file_list(format_list=True, base=root)
|
||||
async def _handle_filelist_request(self, web_request):
|
||||
root = web_request.get_str('root', "gcodes")
|
||||
return self.get_file_list(root, list_format=True, notify=True)
|
||||
|
||||
async def _handle_metadata_request(self, path, method, args):
|
||||
requested_file = args.get('filename')
|
||||
metadata = self.gcode_metadata.get(requested_file)
|
||||
async def _handle_metadata_request(self, web_request):
|
||||
requested_file = web_request.get_str('filename')
|
||||
metadata = self.gcode_metadata.get(requested_file, None)
|
||||
if metadata is None:
|
||||
raise self.server.error(
|
||||
f"Metadata not available for <{requested_file}>", 404)
|
||||
metadata['filename'] = requested_file
|
||||
return metadata
|
||||
|
||||
async def _handle_directory_request(self, path, method, args):
|
||||
directory = args.get('path', "gcodes")
|
||||
base, url_path, dir_path = self._convert_path(directory)
|
||||
method = method.upper()
|
||||
if method == 'GET':
|
||||
async def _handle_directory_request(self, web_request):
|
||||
directory = web_request.get_str('path', "gcodes")
|
||||
root, rel_path, dir_path = self._convert_path(directory)
|
||||
action = web_request.get_action()
|
||||
if action == 'GET':
|
||||
is_extended = web_request.get_boolean('extended', False)
|
||||
# Get list of files and subdirectories for this target
|
||||
return self._list_directory(dir_path)
|
||||
elif method == 'POST' and base in FULL_ACCESS_ROOTS:
|
||||
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)
|
||||
return dir_info
|
||||
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
|
||||
# Create a new directory
|
||||
try:
|
||||
os.mkdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed("create_dir", url_path, base)
|
||||
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
|
||||
self.notify_filelist_changed("create_dir", rel_path, root)
|
||||
elif action == 'DELETE' and root in FULL_ACCESS_ROOTS:
|
||||
# Remove a directory
|
||||
if directory.strip("/") == base:
|
||||
if directory.strip("/") == root:
|
||||
raise self.server.error(
|
||||
"Cannot delete root directory")
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
f"Directory does not exist ({directory})")
|
||||
force = args.get('force', False)
|
||||
if isinstance(force, str):
|
||||
force = force.lower() == "true"
|
||||
force = web_request.get_boolean('force', False)
|
||||
if force:
|
||||
# Make sure that the directory does not contain a file
|
||||
# loaded by the virtual_sdcard
|
||||
await self._handle_operation_check(dir_path)
|
||||
shutil.rmtree(dir_path)
|
||||
if root == "gcodes":
|
||||
self.gcode_metadata.prune_metadata()
|
||||
else:
|
||||
try:
|
||||
os.rmdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed("delete_dir", url_path, base)
|
||||
self.notify_filelist_changed("delete_dir", rel_path, root)
|
||||
else:
|
||||
raise self.server.error("Operation Not Supported", 405)
|
||||
return "ok"
|
||||
@@ -177,51 +203,58 @@ class FileManager:
|
||||
ongoing = state in ["printing", "paused"]
|
||||
return ongoing
|
||||
|
||||
def _convert_path(self, url_path):
|
||||
parts = url_path.strip("/").split("/")
|
||||
def _convert_path(self, request_path):
|
||||
# Parse the root, relative path, and disk path from a remote request
|
||||
parts = request_path.strip("/").split("/")
|
||||
if not parts:
|
||||
raise self.server.error(f"Invalid path: {url_path}")
|
||||
base = parts[0]
|
||||
if base not in self.file_paths:
|
||||
raise self.server.error(f"Invalid base path ({base})")
|
||||
root_path = local_path = self.file_paths[base]
|
||||
url_path = ""
|
||||
raise self.server.error(f"Invalid path: {request_path}")
|
||||
root = parts[0]
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(f"Invalid root path ({root})")
|
||||
disk_path = self.file_paths[root]
|
||||
rel_path = ""
|
||||
if len(parts) > 1:
|
||||
url_path = "/".join(parts[1:])
|
||||
local_path = os.path.join(root_path, url_path)
|
||||
return base, url_path, local_path
|
||||
rel_path = "/".join(parts[1:])
|
||||
disk_path = os.path.join(disk_path, rel_path)
|
||||
return root, rel_path, disk_path
|
||||
|
||||
async def _handle_file_move_copy(self, path, method, args):
|
||||
source = args.get("source")
|
||||
destination = args.get("dest")
|
||||
async def _handle_file_move_copy(self, web_request):
|
||||
source = web_request.get_str("source")
|
||||
destination = web_request.get_str("dest")
|
||||
ep = web_request.get_endpoint()
|
||||
if source is None:
|
||||
raise self.server.error("File move/copy request issing source")
|
||||
if destination is None:
|
||||
raise self.server.error(
|
||||
"File move/copy request missing destination")
|
||||
source_base, src_url_path, source_path = self._convert_path(source)
|
||||
dest_base, dst_url_path, dest_path = self._convert_path(destination)
|
||||
if dest_base not in FULL_ACCESS_ROOTS:
|
||||
source_root, src_rel_path, source_path = self._convert_path(source)
|
||||
dest_root, dst_rel_path, dest_path = self._convert_path(destination)
|
||||
if dest_root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Destination path is read-only: {dest_base}")
|
||||
f"Destination path is read-only: {dest_root}")
|
||||
if not os.path.exists(source_path):
|
||||
raise self.server.error(f"File {source_path} does not exist")
|
||||
# make sure the destination is not in use
|
||||
if os.path.exists(dest_path):
|
||||
await self._handle_operation_check(dest_path)
|
||||
action = op_result = ""
|
||||
if path == "/server/files/move":
|
||||
if source_base not in FULL_ACCESS_ROOTS:
|
||||
if ep == "/server/files/move":
|
||||
if source_root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Source path is read-only, cannot move: {source_base}")
|
||||
f"Source path is read-only, cannot move: {source_root}")
|
||||
# if moving the file, make sure the source is not in use
|
||||
await self._handle_operation_check(source_path)
|
||||
try:
|
||||
op_result = shutil.move(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
if source_root == "gcodes":
|
||||
if os.path.isdir(op_result):
|
||||
self.gcode_metadata.prune_metadata()
|
||||
else:
|
||||
self.gcode_metadata.remove_file(src_rel_path)
|
||||
action = "move_item"
|
||||
elif path == "/server/files/copy":
|
||||
elif ep == "/server/files/copy":
|
||||
try:
|
||||
if os.path.isdir(source_path):
|
||||
op_result = shutil.copytree(source_path, dest_path)
|
||||
@@ -231,11 +264,11 @@ class FileManager:
|
||||
raise self.server.error(str(e))
|
||||
action = "copy_item"
|
||||
if op_result != dest_path:
|
||||
dst_url_path = os.path.join(
|
||||
dst_url_path, os.path.basename(op_result))
|
||||
dst_rel_path = os.path.join(
|
||||
dst_rel_path, os.path.basename(op_result))
|
||||
self.notify_filelist_changed(
|
||||
action, dst_url_path, dest_base,
|
||||
{'path': src_url_path, 'root': source_base})
|
||||
action, dst_rel_path, dest_root,
|
||||
{'path': src_rel_path, 'root': source_root})
|
||||
return "ok"
|
||||
|
||||
def _list_directory(self, path):
|
||||
@@ -255,37 +288,11 @@ class FileManager:
|
||||
return flist
|
||||
|
||||
def _get_path_info(self, path):
|
||||
modified = time.ctime(os.path.getmtime(path))
|
||||
modified = os.path.getmtime(path)
|
||||
size = os.path.getsize(path)
|
||||
path_info = {'modified': modified, 'size': size}
|
||||
return path_info
|
||||
|
||||
def _update_file_list(self, base='gcodes', do_notify=False):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
path = self.file_paths.get(base, None)
|
||||
if path is None:
|
||||
msg = f"No known path for root: {base}"
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
elif not os.path.isdir(path):
|
||||
msg = f"Cannot generate file list for root: {base}"
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info(f"Updating File List <{base}>...")
|
||||
new_list = {}
|
||||
for root, dirs, files in os.walk(path, followlinks=True):
|
||||
for name in files:
|
||||
ext = name[name.rfind('.')+1:]
|
||||
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root, name)
|
||||
r_path = full_path[len(path) + 1:]
|
||||
new_list[r_path] = self._get_path_info(full_path)
|
||||
self.file_lists[base] = new_list
|
||||
if base == 'gcodes':
|
||||
self.gcode_metadata.refresh_metadata(new_list, path, do_notify)
|
||||
return dict(new_list)
|
||||
|
||||
async def process_file_upload(self, request):
|
||||
# lookup root file path
|
||||
root = self._get_argument(request, 'root', "gcodes")
|
||||
@@ -299,15 +306,20 @@ class FileManager:
|
||||
|
||||
async def _do_gcode_upload(self, request):
|
||||
start_print = print_ongoing = False
|
||||
base_path = self.file_paths.get("gcodes", "")
|
||||
if not base_path:
|
||||
root_path = self.file_paths.get("gcodes", "")
|
||||
if not root_path:
|
||||
raise self.server.error("Gcodes root not available")
|
||||
start_print = self._get_argument(request, 'print', "false") == "true"
|
||||
upload = self._get_upload_info(request, base_path)
|
||||
upload = self._get_upload_info(request, root_path)
|
||||
fparts = os.path.splitext(upload['full_path'])
|
||||
is_ufp = fparts[-1].lower() == ".ufp"
|
||||
# Verify that the operation can be done if attempting to upload a gcode
|
||||
try:
|
||||
check_path = upload['full_path']
|
||||
if is_ufp:
|
||||
check_path = fparts[0] + ".gcode"
|
||||
print_ongoing = await self._handle_operation_check(
|
||||
upload['full_path'])
|
||||
check_path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise self.server.error(
|
||||
@@ -318,7 +330,12 @@ class FileManager:
|
||||
start_print = False
|
||||
# Don't start if another print is currently in progress
|
||||
start_print = start_print and not print_ongoing
|
||||
self._write_file(upload)
|
||||
self._write_file(upload, is_ufp)
|
||||
# Fetch Metadata
|
||||
finfo = self._get_path_info(upload['full_path'])
|
||||
evt = self.gcode_metadata.parse_metadata(
|
||||
upload['filename'], finfo['size'], finfo['modified'])
|
||||
await evt.wait()
|
||||
if start_print:
|
||||
# Make a Klippy Request to "Start Print"
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
@@ -346,7 +363,7 @@ class FileManager:
|
||||
return args[0].decode().strip()
|
||||
return default
|
||||
|
||||
def _get_upload_info(self, request, base_path):
|
||||
def _get_upload_info(self, request, root_path):
|
||||
# check relative path
|
||||
dir_path = self._get_argument(request, 'path', "")
|
||||
# fetch the upload from the request
|
||||
@@ -358,17 +375,17 @@ class FileManager:
|
||||
raise self.server.error(
|
||||
"Bad Request, can only process a single file upload")
|
||||
upload = f_list[0]
|
||||
if os.path.isfile(base_path):
|
||||
filename = os.path.basename(base_path)
|
||||
full_path = base_path
|
||||
if os.path.isfile(root_path):
|
||||
filename = os.path.basename(root_path)
|
||||
full_path = root_path
|
||||
dir_path = ""
|
||||
else:
|
||||
filename = "_".join(upload['filename'].strip().split()).lstrip("/")
|
||||
filename = upload['filename'].strip().lstrip("/")
|
||||
if dir_path:
|
||||
filename = os.path.join(dir_path, filename)
|
||||
full_path = os.path.normpath(os.path.join(base_path, filename))
|
||||
full_path = os.path.normpath(os.path.join(root_path, filename))
|
||||
# Validate the path. Don't allow uploads to a parent of the root
|
||||
if not full_path.startswith(base_path):
|
||||
if not full_path.startswith(root_path):
|
||||
raise self.server.error(
|
||||
f"Cannot write to path: {full_path}")
|
||||
return {
|
||||
@@ -377,23 +394,91 @@ class FileManager:
|
||||
'dir_path': dir_path,
|
||||
'full_path': full_path}
|
||||
|
||||
def _write_file(self, upload):
|
||||
def _write_file(self, upload, unzip_ufp=False):
|
||||
try:
|
||||
if upload['dir_path']:
|
||||
os.makedirs(os.path.dirname(upload['full_path']), exist_ok=True)
|
||||
with open(upload['full_path'], 'wb') as fh:
|
||||
fh.write(upload['body'])
|
||||
os.makedirs(os.path.dirname(
|
||||
upload['full_path']), exist_ok=True)
|
||||
if unzip_ufp:
|
||||
self._unzip_ufp(upload)
|
||||
else:
|
||||
with open(upload['full_path'], 'wb') as fh:
|
||||
fh.write(upload['body'])
|
||||
except Exception:
|
||||
raise self.server.error("Unable to save file", 500)
|
||||
|
||||
def get_file_list(self, format_list=False, base='gcodes'):
|
||||
try:
|
||||
filelist = self._update_file_list(base)
|
||||
except Exception:
|
||||
msg = "Unable to update file list"
|
||||
logging.exception(msg)
|
||||
# UFP Extraction Implementation inspired by by GitHub user @cdkeito
|
||||
def _unzip_ufp(self, upload):
|
||||
base_name = os.path.splitext(
|
||||
os.path.basename(upload['filename']))[0]
|
||||
working_dir = os.path.dirname(upload['full_path'])
|
||||
thumb_dir = os.path.join(working_dir, "thumbs")
|
||||
ufp_bytes = io.BytesIO(upload['body'])
|
||||
gc_bytes = img_bytes = None
|
||||
with zipfile.ZipFile(ufp_bytes) as zf:
|
||||
gc_bytes = zf.read("/3D/model.gcode")
|
||||
try:
|
||||
img_bytes = zf.read("/Metadata/thumbnail.png")
|
||||
except Exception:
|
||||
img_bytes = None
|
||||
if gc_bytes is not None:
|
||||
gc_name = base_name + ".gcode"
|
||||
gc_path = os.path.join(working_dir, gc_name)
|
||||
with open(gc_path, "wb") as gc_file:
|
||||
gc_file.write(gc_bytes)
|
||||
# update upload file name to extracted gcode file
|
||||
upload['full_path'] = gc_path
|
||||
upload['filename'] = os.path.join(
|
||||
os.path.dirname(upload['filename']), gc_name)
|
||||
else:
|
||||
raise self.server.error(
|
||||
f"UFP file {upload['filename']} does not "
|
||||
"contain a gcode file")
|
||||
if img_bytes is not None:
|
||||
thumb_name = base_name + ".png"
|
||||
thumb_path = os.path.join(thumb_dir, thumb_name)
|
||||
try:
|
||||
if not os.path.exists(thumb_dir):
|
||||
os.mkdir(thumb_dir)
|
||||
with open(thumb_path, "wb") as thumb_file:
|
||||
thumb_file.write(img_bytes)
|
||||
except Exception:
|
||||
logging.exception("Unable to write Image")
|
||||
|
||||
def get_file_list(self, root, list_format=False, notify=False):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
filelist = {}
|
||||
path = self.file_paths.get(root, None)
|
||||
if path is None or not os.path.isdir(path):
|
||||
msg = f"Failed to build file list, invalid path: {root}: {path}"
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
if format_list:
|
||||
logging.info(f"Updating File List <{root}>...")
|
||||
st = os.stat(path)
|
||||
visited_dirs = {(st.st_dev, st.st_ino)}
|
||||
for dir_path, dir_names, files in os.walk(path, followlinks=True):
|
||||
scan_dirs = []
|
||||
# Filter out directories that have already been visted. This
|
||||
# prevents infinite recrusion "followlinks" is set to True
|
||||
for dname in dir_names:
|
||||
st = os.stat(os.path.join(dir_path, dname))
|
||||
key = (st.st_dev, st.st_ino)
|
||||
if key not in visited_dirs:
|
||||
visited_dirs.add(key)
|
||||
scan_dirs.append(dname)
|
||||
dir_names[:] = scan_dirs
|
||||
for name in files:
|
||||
ext = os.path.splitext(name)[-1].lower()
|
||||
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(dir_path, name)
|
||||
fname = full_path[len(path) + 1:]
|
||||
finfo = self._get_path_info(full_path)
|
||||
filelist[fname] = finfo
|
||||
if root == 'gcodes':
|
||||
self.gcode_metadata.parse_metadata(
|
||||
fname, finfo['size'], finfo['modified'], notify)
|
||||
if list_format:
|
||||
flist = []
|
||||
for fname in sorted(filelist, key=str.lower):
|
||||
fdict = {'filename': fname}
|
||||
@@ -411,7 +496,7 @@ class FileManager:
|
||||
if filename.startswith('gcodes/'):
|
||||
filename = filename[7:]
|
||||
|
||||
flist = self.get_file_list()
|
||||
flist = self.get_file_list("gcodes")
|
||||
return self.gcode_metadata.get(filename, flist.get(filename, {}))
|
||||
|
||||
def list_dir(self, directory, simple_format=False):
|
||||
@@ -439,45 +524,86 @@ class FileManager:
|
||||
simple_list.append("*" + dirobj['dirname'])
|
||||
for fileobj in flist['files']:
|
||||
fname = fileobj['filename']
|
||||
ext = fname[fname.rfind('.')+1:]
|
||||
ext = os.path.splitext(fname)[-1].lower()
|
||||
if root == "gcodes" and ext in VALID_GCODE_EXTS:
|
||||
simple_list.append(fname)
|
||||
return simple_list
|
||||
return flist
|
||||
|
||||
def delete_file(self, path):
|
||||
parts = path.split("/", 1)
|
||||
async def _handle_file_delete(self, web_request):
|
||||
file_path = web_request.get_str("path")
|
||||
return await self.delete_file(file_path)
|
||||
|
||||
async def delete_file(self, path):
|
||||
parts = path.lstrip("/").split("/", 1)
|
||||
if len(parts) != 2:
|
||||
raise self.server.error(
|
||||
f"Path not available for DELETE: {path}", 405)
|
||||
root = parts[0]
|
||||
if root not in self.file_paths or len(parts) != 2:
|
||||
raise self.server.error(f"Invalid file path: {path}")
|
||||
filename = parts[1]
|
||||
if root not in self.file_paths or root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Path not available for DELETE: {path}", 405)
|
||||
root_path = self.file_paths[root]
|
||||
full_path = os.path.join(root_path, parts[1])
|
||||
full_path = os.path.join(root_path, filename)
|
||||
if not os.path.isfile(full_path):
|
||||
raise self.server.error(f"Invalid file path: {path}")
|
||||
if root == "gcodes":
|
||||
try:
|
||||
await self._handle_operation_check(full_path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise
|
||||
self.gcode_metadata.remove_file(filename)
|
||||
os.remove(full_path)
|
||||
self.notify_filelist_changed('delete_file', filename, root)
|
||||
return filename
|
||||
|
||||
def notify_filelist_changed(self, action, fname, base, source_item={}):
|
||||
self._update_file_list(base, do_notify=True)
|
||||
file_info = dict(self.file_lists[base].get(
|
||||
fname, {'size': 0, 'modified': ""}))
|
||||
file_info.update({'path': fname, 'root': base})
|
||||
def notify_filelist_changed(self, action, fname, root, source_item={}):
|
||||
flist = self.get_file_list(root, notify=True)
|
||||
file_info = flist.get(fname, {'size': 0, 'modified': 0})
|
||||
file_info.update({'path': fname, 'root': root})
|
||||
result = {'action': action, 'item': file_info}
|
||||
if source_item:
|
||||
result.update({'source_item': source_item})
|
||||
self.server.send_event("file_manager:filelist_changed", result)
|
||||
|
||||
def close(self):
|
||||
self.gcode_metadata.close()
|
||||
|
||||
|
||||
METADATA_PRUNE_TIME = 600000
|
||||
|
||||
class MetadataStorage:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.lock = Lock()
|
||||
self.metadata = {}
|
||||
self.pending_requests = {}
|
||||
self.events = {}
|
||||
self.script_response = None
|
||||
self.busy = False
|
||||
self.gc_path = os.path.expanduser("~")
|
||||
self.prune_cb = PeriodicCallback(
|
||||
self.prune_metadata, METADATA_PRUNE_TIME)
|
||||
|
||||
def update_gcode_path(self, path):
|
||||
if path == self.gc_path:
|
||||
return
|
||||
self.metadata = {}
|
||||
self.gc_path = path
|
||||
if not self.prune_cb.is_running():
|
||||
self.prune_cb.start()
|
||||
|
||||
def close(self):
|
||||
self.prune_cb.stop()
|
||||
|
||||
def get(self, key, default=None):
|
||||
return self.metadata.get(key, default)
|
||||
if key not in self.metadata:
|
||||
return default
|
||||
return dict(self.metadata[key])
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.metadata[key]
|
||||
return dict(self.metadata[key])
|
||||
|
||||
def _handle_script_response(self, result):
|
||||
try:
|
||||
@@ -492,40 +618,64 @@ class MetadataStorage:
|
||||
if 'file' in proc_resp:
|
||||
self.script_response = proc_resp
|
||||
|
||||
def refresh_metadata(self, filelist, gc_path, do_notify=False):
|
||||
IOLoop.current().spawn_callback(
|
||||
self._do_metadata_update, filelist, gc_path, do_notify)
|
||||
def prune_metadata(self):
|
||||
for fname in list(self.metadata.keys()):
|
||||
fpath = os.path.join(self.gc_path, fname)
|
||||
if not os.path.exists(fpath):
|
||||
del self.metadata[fname]
|
||||
logging.info(f"Pruned file: {fname}")
|
||||
continue
|
||||
|
||||
async def _do_metadata_update(self, filelist, gc_path, do_notify=False):
|
||||
async with self.lock:
|
||||
exisiting_data = {}
|
||||
update_list = []
|
||||
for fname, fdata in filelist.items():
|
||||
mdata = self.metadata.get(fname, {})
|
||||
if mdata.get('size', "") == fdata.get('size') \
|
||||
and mdata.get('modified', "") == fdata.get('modified'):
|
||||
# file metadata has already been extracted
|
||||
exisiting_data[fname] = mdata
|
||||
else:
|
||||
update_list.append(fname)
|
||||
self.metadata = exisiting_data
|
||||
for fname in update_list:
|
||||
retries = 3
|
||||
while retries:
|
||||
try:
|
||||
await self._extract_metadata(fname, gc_path, do_notify)
|
||||
except Exception:
|
||||
logging.exception("Error running extract_metadata.py")
|
||||
retries -= 1
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logging.info(
|
||||
f"Unable to extract medatadata from file: {fname}")
|
||||
def _has_valid_data(self, fname, fsize, modified):
|
||||
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
|
||||
return mdata['size'] == fsize and mdata['modified'] == modified
|
||||
|
||||
async def _extract_metadata(self, filename, path, do_notify=False):
|
||||
def remove_file(self, fname):
|
||||
self.metadata.pop(fname)
|
||||
|
||||
def parse_metadata(self, fname, fsize, modified, notify=False):
|
||||
evt = Event()
|
||||
if fname in self.pending_requests or \
|
||||
self._has_valid_data(fname, fsize, modified):
|
||||
# request already pending or not necessary
|
||||
evt.set()
|
||||
return evt
|
||||
self.pending_requests[fname] = (fsize, modified, notify, evt)
|
||||
if self.busy:
|
||||
return evt
|
||||
self.busy = True
|
||||
IOLoop.current().spawn_callback(self._process_metadata_update)
|
||||
return evt
|
||||
|
||||
async def _process_metadata_update(self):
|
||||
while self.pending_requests:
|
||||
fname, (fsize, modified, notify, evt) = \
|
||||
self.pending_requests.popitem()
|
||||
if self._has_valid_data(fname, fsize, modified):
|
||||
evt.set()
|
||||
continue
|
||||
retries = 3
|
||||
while retries:
|
||||
try:
|
||||
await self._run_extract_metadata(fname, notify)
|
||||
except Exception:
|
||||
logging.exception("Error running extract_metadata.py")
|
||||
retries -= 1
|
||||
else:
|
||||
break
|
||||
else:
|
||||
self.metadata[fname] = {'size': fsize, 'modified': modified}
|
||||
logging.info(
|
||||
f"Unable to extract medatadata from file: {fname}")
|
||||
evt.set()
|
||||
self.busy = False
|
||||
|
||||
async def _run_extract_metadata(self, filename, notify):
|
||||
# Escape single quotes in the file name so that it may be
|
||||
# properly loaded
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
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)
|
||||
@@ -535,9 +685,12 @@ class MetadataStorage:
|
||||
raise self.server.error("Unable to extract metadata")
|
||||
path = self.script_response['file']
|
||||
metadata = self.script_response['metadata']
|
||||
if not metadata:
|
||||
# This indicates an error, do not add metadata for this
|
||||
raise self.server.error("Unable to extract metadata")
|
||||
self.metadata[path] = dict(metadata)
|
||||
metadata['filename'] = path
|
||||
if do_notify:
|
||||
if notify:
|
||||
self.server.send_event(
|
||||
"file_manager:metadata_update", metadata)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import utils
|
||||
from websockets import WebRequest
|
||||
|
||||
INFO_ENDPOINT = "info"
|
||||
ESTOP_ENDPOINT = "emergency_stop"
|
||||
@@ -13,6 +14,7 @@ GCODE_ENDPOINT = "gcode/script"
|
||||
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
|
||||
STATUS_ENDPOINT = "objects/query"
|
||||
OBJ_LIST_ENDPOINT = "objects/list"
|
||||
REG_METHOD_ENDPOINT = "register_remote_method"
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
@@ -21,48 +23,47 @@ class KlippyAPI:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
|
||||
# Maintain a subscription for all moonraker requests, as
|
||||
# we do not want to overwrite them
|
||||
self.host_subscription = {}
|
||||
|
||||
# Register GCode Aliases
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/pause", "printer_print_pause", ['POST'],
|
||||
self._gcode_pause)
|
||||
"/printer/print/pause", ['POST'], self._gcode_pause)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", "printer_print_resume", ['POST'],
|
||||
self._gcode_resume)
|
||||
"/printer/print/resume", ['POST'], self._gcode_resume)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", "printer_print_cancel", ['POST'],
|
||||
self._gcode_cancel)
|
||||
"/printer/print/cancel", ['POST'], self._gcode_cancel)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", "printer_print_start", ['POST'],
|
||||
self._gcode_start_print)
|
||||
"/printer/print/start", ['POST'], self._gcode_start_print)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", "printer_restart", ['POST'],
|
||||
self._gcode_restart)
|
||||
"/printer/restart", ['POST'], self._gcode_restart)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
|
||||
self._gcode_firmware_restart)
|
||||
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
|
||||
|
||||
async def _gcode_pause(self, path, method, args):
|
||||
async def _gcode_pause(self, web_request):
|
||||
return await self.run_gcode("PAUSE")
|
||||
|
||||
async def _gcode_resume(self, path, method, args):
|
||||
async def _gcode_resume(self, web_request):
|
||||
return await self.run_gcode("RESUME")
|
||||
|
||||
async def _gcode_cancel(self, path, method, args):
|
||||
async def _gcode_cancel(self, web_request):
|
||||
return await self.run_gcode("CANCEL_PRINT")
|
||||
|
||||
async def _gcode_start_print(self, path, method, args):
|
||||
filename = args.get('filename')
|
||||
async def _gcode_start_print(self, web_request):
|
||||
filename = web_request.get_str('filename')
|
||||
return await self.start_print(filename)
|
||||
|
||||
async def _gcode_restart(self, path, method, args):
|
||||
async def _gcode_restart(self, web_request):
|
||||
return await self.do_restart("RESTART")
|
||||
|
||||
async def _gcode_firmware_restart(self, path, method, args):
|
||||
async def _gcode_firmware_restart(self, web_request):
|
||||
return await self.do_restart("FIRMWARE_RESTART")
|
||||
|
||||
async def _send_klippy_request(self, method, params, default=Sentinel):
|
||||
try:
|
||||
result = await self.server.make_request(method, params)
|
||||
result = await self.server.make_request(
|
||||
WebRequest(method, params, conn=self))
|
||||
except self.server.error as e:
|
||||
if default == Sentinel:
|
||||
raise
|
||||
@@ -79,7 +80,9 @@ class KlippyAPI:
|
||||
# XXX - validate that file is on disk
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
script = "SDCARD_PRINT_FILE FILENAME=" + filename
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
|
||||
return await self.run_gcode(script)
|
||||
|
||||
async def do_restart(self, gc):
|
||||
@@ -122,7 +125,17 @@ class KlippyAPI:
|
||||
return result
|
||||
|
||||
async def subscribe_objects(self, objects, default=Sentinel):
|
||||
params = {'objects': objects}
|
||||
for obj, items in objects.items():
|
||||
if obj in self.host_subscription:
|
||||
prev = self.host_subscription[obj]
|
||||
if items is None or prev is None:
|
||||
self.host_subscription[obj] = None
|
||||
else:
|
||||
uitems = list(set(prev) | set(items))
|
||||
self.host_subscription[obj] = uitems
|
||||
else:
|
||||
self.host_subscription[obj] = items
|
||||
params = {'objects': self.host_subscription}
|
||||
result = await self._send_klippy_request(
|
||||
SUBSCRIPTION_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and 'status' in result:
|
||||
@@ -135,5 +148,14 @@ class KlippyAPI:
|
||||
return await self._send_klippy_request(
|
||||
GC_OUTPUT_ENDPOINT, template, default)
|
||||
|
||||
async def register_method(self, method_name):
|
||||
return await self._send_klippy_request(
|
||||
REG_METHOD_ENDPOINT,
|
||||
{'response_template': {"method": method_name},
|
||||
'remote_method': method_name})
|
||||
|
||||
def send_status(self, status):
|
||||
self.server.send_event("server:status_update", status)
|
||||
|
||||
def load_plugin(config):
|
||||
return KlippyAPI(config)
|
||||
@@ -4,31 +4,61 @@
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
class Machine:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.server.register_endpoint(
|
||||
"/machine/reboot", "machine_reboot", ['POST'],
|
||||
self._handle_machine_request)
|
||||
"/machine/reboot", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/shutdown", "machine_shutdown", ['POST'],
|
||||
self._handle_machine_request)
|
||||
"/machine/shutdown", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/restart", ['POST'],
|
||||
self._handle_service_restart)
|
||||
|
||||
async def _handle_machine_request(self, path, method, args):
|
||||
if path == "/machine/shutdown":
|
||||
cmd = "sudo shutdown now"
|
||||
elif path == "/machine/reboot":
|
||||
cmd = "sudo reboot now"
|
||||
# Register remote methods
|
||||
self.server.register_remote_method(
|
||||
"shutdown_machine", self.shutdown_machine)
|
||||
self.server.register_remote_method(
|
||||
"reboot_machine", self.reboot_machine)
|
||||
|
||||
async def _handle_machine_request(self, web_request):
|
||||
ep = web_request.get_endpoint()
|
||||
if ep == "/machine/shutdown":
|
||||
await self.shutdown_machine()
|
||||
elif ep == "/machine/reboot":
|
||||
await self.reboot_machine()
|
||||
else:
|
||||
raise self.server.error("Unsupported machine request")
|
||||
return "ok"
|
||||
|
||||
async def shutdown_machine(self):
|
||||
await self._execute_cmd("sudo shutdown now")
|
||||
|
||||
async def reboot_machine(self):
|
||||
await self._execute_cmd("sudo shutdown -r now")
|
||||
|
||||
async def _handle_service_restart(self, web_request):
|
||||
name = web_request.get('service')
|
||||
if name == "klipper":
|
||||
await self._execute_cmd(f'sudo systemctl restart {name}')
|
||||
elif name == "moonraker":
|
||||
IOLoop.current().spawn_callback(
|
||||
self._execute_cmd, f'sudo systemctl restart {name}')
|
||||
else:
|
||||
raise self.sever.error(
|
||||
f"Invalid argument recevied for 'name': {name}")
|
||||
return "ok"
|
||||
|
||||
async def _execute_cmd(self, cmd):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
try:
|
||||
await scmd.run(timeout=2., verbose=False)
|
||||
except Exception:
|
||||
logging.exception(f"Error running cmd '{cmd}'")
|
||||
return "ok"
|
||||
raise
|
||||
|
||||
def load_plugin(config):
|
||||
return Machine(config)
|
||||
+196
-134
@@ -9,16 +9,19 @@ 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
|
||||
|
||||
|
||||
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
|
||||
|
||||
class SerialConnection:
|
||||
@@ -27,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)
|
||||
@@ -41,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()
|
||||
@@ -67,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:
|
||||
@@ -81,49 +93,51 @@ 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):
|
||||
@@ -139,6 +153,8 @@ class PanelDue:
|
||||
self.last_gcode_response = None
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
self.enable_checksum = config.getboolean('enable_checksum', True)
|
||||
self.debug_queue = deque(maxlen=100)
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state = {
|
||||
@@ -149,12 +165,16 @@ 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 = ""
|
||||
self.mbox_sequence = 0
|
||||
self.beep_sequence = 0
|
||||
self.available_macros = {}
|
||||
self.confirmed_macros = {
|
||||
"RESTART": "RESTART",
|
||||
@@ -189,6 +209,9 @@ class PanelDue:
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self.handle_gcode_response)
|
||||
|
||||
self.server.register_remote_method(
|
||||
"paneldue_beep", self.paneldue_beep)
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# make a request to Klippy
|
||||
self.direct_gcodes = {
|
||||
@@ -271,98 +294,97 @@ 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
|
||||
if "gcode_macro PANELDUE_BEEP" in status:
|
||||
# This only processes a paneldue beep when the macro's
|
||||
# variables have changed
|
||||
params = self.printer_state["gcode_macro PANELDUE_BEEP"]
|
||||
try:
|
||||
self.handle_paneldue_beep(**params)
|
||||
except Exception:
|
||||
logging.exception("Unable to process PANELDUE_BEEP")
|
||||
|
||||
def handle_paneldue_beep(self, sequence, frequency, duration):
|
||||
if sequence != self.beep_sequence:
|
||||
self.beep_sequence = sequence
|
||||
duration = int(duration * 1000.)
|
||||
self.ioloop.spawn_callback(
|
||||
self.write_response,
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
def paneldue_beep(self, frequency, duration):
|
||||
duration = int(duration * 1000.)
|
||||
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
|
||||
|
||||
# Get line number
|
||||
line_index = line.find(' ')
|
||||
try:
|
||||
line_no = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
if self.enable_checksum:
|
||||
# Get line number
|
||||
line_index = line.find(' ')
|
||||
try:
|
||||
line_no = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
|
||||
# Verify checksum
|
||||
cs_index = line.rfind('*')
|
||||
try:
|
||||
checksum = int(line[cs_index+1:])
|
||||
except Exception:
|
||||
# Invalid checksum, do not process
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.exception("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
# Verify checksum
|
||||
cs_index = line.rfind('*')
|
||||
try:
|
||||
checksum = int(line[cs_index+1:])
|
||||
except Exception:
|
||||
# Invalid checksum, do not process
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.exception("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
# Checksum is calculated by XORing every byte in the line other
|
||||
# than the checksum itself
|
||||
calculated_cs = 0
|
||||
for c in line[:cs_index]:
|
||||
calculated_cs ^= ord(c)
|
||||
if calculated_cs & 0xFF != checksum:
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
# Checksum is calculated by XORing every byte in the line other
|
||||
# than the checksum itself
|
||||
calculated_cs = 0
|
||||
for c in line[:cs_index]:
|
||||
calculated_cs ^= ord(c)
|
||||
if calculated_cs & 0xFF != checksum:
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
await self._run_gcode(line[line_index+1:cs_index])
|
||||
|
||||
async def _run_gcode(self, script):
|
||||
script = line[line_index+1:cs_index]
|
||||
else:
|
||||
script = line
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
# require special handling
|
||||
parts = script.split()
|
||||
cmd = parts[0].strip()
|
||||
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
|
||||
arg = script[len(cmd):].strip()
|
||||
parts = [cmd, arg]
|
||||
|
||||
# Check for commands that query state and require immediate response
|
||||
if cmd in self.direct_gcodes:
|
||||
params = {}
|
||||
for p in parts[1:]:
|
||||
arg = p[0].lower() if p[0].lower() in "psr" else "p"
|
||||
if p[0] not in "PSR":
|
||||
params["arg_p"] = p.strip(" \"\t\n")
|
||||
continue
|
||||
arg = p[0].lower()
|
||||
try:
|
||||
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
|
||||
val = int(p[1:].strip()) if arg in "sr" \
|
||||
else p[1:].strip(" \"\t\n")
|
||||
except Exception:
|
||||
msg = 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
|
||||
@@ -372,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:]
|
||||
@@ -400,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)
|
||||
@@ -445,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
|
||||
@@ -459,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:
|
||||
@@ -472,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':
|
||||
@@ -482,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
|
||||
@@ -612,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(
|
||||
@@ -652,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
|
||||
@@ -666,9 +723,9 @@ class PanelDue:
|
||||
|
||||
if not path.startswith("gcodes/"):
|
||||
path = "gcodes/" + path
|
||||
self.file_manager.delete_file(path)
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
async def _run_paneldue_M36(self, arg_p=None):
|
||||
def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
@@ -683,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
|
||||
|
||||
@@ -701,7 +759,7 @@ class PanelDue:
|
||||
response['err'] = 0
|
||||
response['size'] = metadata['size']
|
||||
# workaround for PanelDue replacing the first "T" found
|
||||
response['lastModified'] = "T" + metadata['modified']
|
||||
response['lastModified'] = "T" + time.ctime(metadata['modified'])
|
||||
slicer = metadata.get('slicer')
|
||||
if slicer is not None:
|
||||
response['generatedBy'] = slicer
|
||||
@@ -719,10 +777,14 @@ class PanelDue:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def close(self):
|
||||
def close(self):
|
||||
self.ser_conn.disconnect()
|
||||
msg = "\nPanelDue GCode Dump:"
|
||||
for i, gc in enumerate(self.debug_queue):
|
||||
msg += f"\nSequence {i}: {gc}"
|
||||
logging.debug(msg)
|
||||
|
||||
def load_plugin(config):
|
||||
return PanelDue(config)
|
||||
+368
-133
@@ -6,169 +6,404 @@
|
||||
|
||||
import logging
|
||||
import os
|
||||
import asyncio
|
||||
import json
|
||||
import struct
|
||||
import socket
|
||||
import gpiod
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.iostream import IOStream
|
||||
from tornado import gen
|
||||
from tornado.httpclient import AsyncHTTPClient
|
||||
from tornado.escape import json_decode
|
||||
|
||||
class PrinterPower:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/devices", "power_devices", ['GET'],
|
||||
"/machine/device_power/devices", ['GET'],
|
||||
self._handle_list_devices)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/status", "power_status", ['GET'],
|
||||
"/machine/device_power/status", ['GET'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/on", "power_on", ['POST'],
|
||||
"/machine/device_power/on", ['POST'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/off", "power_off", ['POST'],
|
||||
"/machine/device_power/off", ['POST'],
|
||||
self._handle_power_request)
|
||||
self.server.register_remote_method(
|
||||
"set_device_power", self.set_device_power)
|
||||
|
||||
self.chip_factory = GpioChipFactory()
|
||||
self.current_dev = None
|
||||
self.devices = {}
|
||||
dev_names = config.get('devices')
|
||||
dev_names = [d.strip() for d in dev_names.split(',') if d.strip()]
|
||||
logging.info("Power plugin loading devices: " + str(dev_names))
|
||||
devices = {}
|
||||
for dev in dev_names:
|
||||
pin = config.getint(dev + "_pin")
|
||||
name = config.get(dev + "_name", dev)
|
||||
active_low = config.getboolean(dev + "_active_low", False)
|
||||
devices[dev] = {
|
||||
"name": name,
|
||||
"pin": pin,
|
||||
"active_low": int(active_low),
|
||||
"status": None
|
||||
}
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(self.initialize_devices, 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 _handle_list_devices(self, path, method, args):
|
||||
output = {"devices": []}
|
||||
for dev in self.devices:
|
||||
output['devices'].append({
|
||||
"name": self.devices[dev]["name"],
|
||||
"id": dev
|
||||
})
|
||||
async def _handle_list_devices(self, web_request):
|
||||
dev_list = [d.get_device_info() for d in self.devices.values()]
|
||||
output = {"devices": dev_list}
|
||||
return output
|
||||
|
||||
async def _handle_power_request(self, path, method, args):
|
||||
if len(args) == 0:
|
||||
if path == "/printer/power/status":
|
||||
args = self.devices
|
||||
else:
|
||||
return "no_devices"
|
||||
|
||||
async def _handle_power_request(self, web_request):
|
||||
args = web_request.get_args()
|
||||
ep = web_request.get_endpoint()
|
||||
if not args:
|
||||
raise self.server.error("No arguments provided")
|
||||
requsted_devs = {k: self.devices.get(k, None) for k in args}
|
||||
result = {}
|
||||
for dev in args:
|
||||
if dev not in self.devices:
|
||||
result[dev] = "device_not_found"
|
||||
continue
|
||||
|
||||
await GPIO.verify_pin(self.devices[dev]["pin"],
|
||||
self.devices[dev]["active_low"])
|
||||
if path == "/printer/power/on":
|
||||
GPIO.set_pin_value(self.devices[dev]["pin"], 1)
|
||||
elif path == "/printer/power/off":
|
||||
GPIO.set_pin_value(self.devices[dev]["pin"], 0)
|
||||
elif path != "/printer/power/status":
|
||||
raise self.server.error("Unsupported power request")
|
||||
|
||||
self.devices[dev]["status"] = GPIO.is_pin_on(
|
||||
self.devices[dev]["pin"])
|
||||
|
||||
result[dev] = self.devices[dev]["status"]
|
||||
req = ep.split("/")[-1]
|
||||
for name, device in requsted_devs.items():
|
||||
if device is not None:
|
||||
result[name] = await self._process_request(device, req)
|
||||
else:
|
||||
result[name] = "device_not_found"
|
||||
return result
|
||||
|
||||
async def initialize_devices(self, devices):
|
||||
for name, device in devices.items():
|
||||
try:
|
||||
logging.debug(
|
||||
f"Attempting to configure pin GPIO{device['pin']}")
|
||||
await GPIO.setup_pin(device["pin"], device["active_low"])
|
||||
device["status"] = GPIO.is_pin_on(device["pin"])
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Power plugin: ERR Problem configuring the output pin for"
|
||||
f" device {name}. Removing device")
|
||||
continue
|
||||
self.devices[name] = device
|
||||
async def _process_request(self, device, req):
|
||||
if req in ["on", "off"]:
|
||||
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)
|
||||
elif req == "status":
|
||||
ret = device.refresh_status()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
dev_info = device.get_device_info()
|
||||
else:
|
||||
raise self.server.error(f"Unsupported power request: {req}")
|
||||
return dev_info['status']
|
||||
|
||||
class GPIO:
|
||||
gpio_root = "/sys/class/gpio"
|
||||
|
||||
@staticmethod
|
||||
def _set_gpio_option(pin, option, value):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, f"gpio{pin}", option),
|
||||
value
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_gpio_option(pin, option):
|
||||
return GPIO._read(
|
||||
os.path.join(GPIO.gpio_root, f"gpio{pin}", option)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _write(file, data):
|
||||
with open(file, 'w') as f:
|
||||
f.write(str(data))
|
||||
f.flush()
|
||||
|
||||
@staticmethod
|
||||
def _read(file):
|
||||
with open(file, 'r') as f:
|
||||
f.seek(0)
|
||||
return f.read().strip()
|
||||
|
||||
@staticmethod
|
||||
async def verify_pin(pin, active_low=1):
|
||||
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
|
||||
if not os.path.exists(gpiopath):
|
||||
logging.info(f"Re-intializing GPIO{pin}")
|
||||
await GPIO.setup_pin(pin, active_low)
|
||||
def set_device_power(self, device, state):
|
||||
status = None
|
||||
if isinstance(state, bool):
|
||||
status = "on" if state else "off"
|
||||
elif isinstance(state, str):
|
||||
status = state.lower()
|
||||
if status in ["true", "false"]:
|
||||
status = "on" if status == "true" else "off"
|
||||
if status not in ["on", "off"]:
|
||||
logging.info(f"Invalid state received: {state}")
|
||||
return
|
||||
if device not in self.devices:
|
||||
logging.info(f"No device found: {device}")
|
||||
return
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(
|
||||
self._process_request, self.devices[device], status)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
async def add_device(self, name, device):
|
||||
if name in self.devices:
|
||||
raise self.server.error(
|
||||
f"Device [{name}] already configured")
|
||||
ret = device.initialize()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.devices[name] = device
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
|
||||
@staticmethod
|
||||
async def setup_pin(pin, active_low=1):
|
||||
pin = int(pin)
|
||||
active_low = 1 if active_low == 1 else 0
|
||||
|
||||
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
|
||||
if not os.path.exists(gpiopath):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, "export"),
|
||||
pin)
|
||||
logging.info(f"Waiting for GPIO{pin} to initialize")
|
||||
while os.stat(os.path.join(
|
||||
GPIO.gpio_root, f"gpio{pin}",
|
||||
"active_low")).st_gid == 0:
|
||||
await gen.sleep(.1)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
async def close(self):
|
||||
for device in self.devices.values():
|
||||
if hasattr(device, "close"):
|
||||
ret = device.close()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.chip_factory.close()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def is_pin_on(pin):
|
||||
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
|
||||
class GpioChipFactory:
|
||||
def __init__(self):
|
||||
self.chips = {}
|
||||
|
||||
@staticmethod
|
||||
def set_pin_value(pin, active):
|
||||
value = 1 if (active == 1) else 0
|
||||
GPIO._set_gpio_option(pin, "value", value)
|
||||
def get_gpio_chip(self, chip_name):
|
||||
if chip_name in self.chips:
|
||||
return self.chips[chip_name]
|
||||
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
|
||||
self.chips[chip_name] = chip
|
||||
return chip
|
||||
|
||||
def close(self):
|
||||
for chip in self.chips.values():
|
||||
chip.close()
|
||||
|
||||
class GpioDevice:
|
||||
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"
|
||||
pin, chip_id, invert = self._parse_pin(config)
|
||||
try:
|
||||
chip = chip_factory.get_gpio_chip(chip_id)
|
||||
self.line = chip.get_line(pin)
|
||||
if invert:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT,
|
||||
flags=gpiod.LINE_REQ_FLAG_ACTIVE_LOW)
|
||||
else:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT)
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
logging.exception(
|
||||
f"Unable to init {pin}. Make sure the gpio is not in "
|
||||
"use by another program or exported by sysfs.")
|
||||
raise config.error("Power GPIO Config Error")
|
||||
initial_state = config.getboolean('initial_state', False)
|
||||
self.set_power("on" if initial_state else "off")
|
||||
|
||||
def _parse_pin(self, config):
|
||||
pin = cfg_pin = config.get("pin")
|
||||
invert = False
|
||||
if pin[0] == "!":
|
||||
pin = pin[1:]
|
||||
invert = True
|
||||
chip_id = "gpiochip0"
|
||||
pin_parts = pin.split("/")
|
||||
if len(pin_parts) == 2:
|
||||
chip_id, pin = pin_parts
|
||||
elif len(pin_parts) == 1:
|
||||
pin = pin_parts[0]
|
||||
# Verify pin
|
||||
if not chip_id.startswith("gpiochip") or \
|
||||
not chip_id[-1].isdigit() or \
|
||||
not pin.startswith("gpio") or \
|
||||
not pin[4:].isdigit():
|
||||
raise config.error(
|
||||
f"Invalid Power Pin configuration: {cfg_pin}")
|
||||
pin = int(pin[4:])
|
||||
return pin, chip_id, invert
|
||||
|
||||
def initialize(self):
|
||||
pass
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'type': "gpio"
|
||||
}
|
||||
|
||||
def refresh_status(self):
|
||||
try:
|
||||
val = self.line.get_value()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if val else "off"
|
||||
|
||||
def set_power(self, state):
|
||||
try:
|
||||
self.line.set_value(int(state == "on"))
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Toggling Device Power: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
def close(self):
|
||||
self.line.release()
|
||||
|
||||
|
||||
def load_plugin(config):
|
||||
# This implementation based off the work tplink_smartplug
|
||||
# script by Lubomir Stroetmann available at:
|
||||
#
|
||||
# https://github.com/softScheck/tplink-smartplug
|
||||
#
|
||||
# Copyright 2016 softScheck GmbH
|
||||
class TPLinkSmartPlug:
|
||||
START_KEY = 0xAB
|
||||
def __init__(self, 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 = {}
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = {'system': {'set_relay_state':
|
||||
{'state': int(command == "on")}}}
|
||||
elif command == "info":
|
||||
out_cmd = {'system': {'get_sysinfo': {}}}
|
||||
else:
|
||||
raise self.server.error(f"Invalid tplink command: {command}")
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
stream = IOStream(s)
|
||||
try:
|
||||
await stream.connect((self.addr, self.port))
|
||||
await stream.write(self._encrypt(out_cmd))
|
||||
data = await stream.read_bytes(2048, partial=True)
|
||||
length = struct.unpack(">I", data[:4])[0]
|
||||
data = data[4:]
|
||||
retries = 5
|
||||
remaining = length - len(data)
|
||||
while remaining and retries:
|
||||
data += await stream.read_bytes(remaining)
|
||||
remaining = length - len(data)
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Unable to read tplink packet")
|
||||
except Exception:
|
||||
msg = f"Error sending tplink command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
finally:
|
||||
stream.close()
|
||||
return json.loads(self._decrypt(data))
|
||||
|
||||
def _encrypt(self, data):
|
||||
data = json.dumps(data)
|
||||
key = self.START_KEY
|
||||
res = struct.pack(">I", len(data))
|
||||
for c in data:
|
||||
val = key ^ ord(c)
|
||||
key = val
|
||||
res += bytes([val])
|
||||
return res
|
||||
|
||||
def _decrypt(self, data):
|
||||
key = self.START_KEY
|
||||
res = ""
|
||||
for c in data:
|
||||
val = key ^ c
|
||||
key = c
|
||||
res += chr(val)
|
||||
return res
|
||||
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'type': "tplink_smartplug"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_tplink_command("info")
|
||||
state = res['system']['get_sysinfo']['relay_state']
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_tplink_command(state)
|
||||
err = res['system']['set_relay_state']['err_code']
|
||||
except Exception:
|
||||
err = 1
|
||||
logging.exception(f"Power Toggle Error: {self.name}")
|
||||
if err:
|
||||
self.state = "error"
|
||||
raise self.server.error(
|
||||
f"Error Toggling Device Power: {self.name}")
|
||||
self.state = state
|
||||
|
||||
|
||||
class Tasmota:
|
||||
def __init__(self, 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 = f"Power{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid tasmota command: {command}")
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password=" \
|
||||
f"{self.password}&cmnd={out_cmd}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
response = await http_client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending tplink command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'type': "tasmota"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_tasmota_command("info")
|
||||
state = res[f"POWER{self.output_id}"].lower()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_tasmota_command(state)
|
||||
state = res[f"POWER{self.output_id}"].lower()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Setting Device Status: {self.name} to {state}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
# The power plugin has multiple configuration sections
|
||||
def load_plugin_multi(config):
|
||||
return PrinterPower(config)
|
||||
@@ -12,13 +12,15 @@ from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
class ShellCommand:
|
||||
def __init__(self, cmd, callback=None):
|
||||
def __init__(self, cmd, callback):
|
||||
self.io_loop = IOLoop.current()
|
||||
self.name = cmd
|
||||
self.output_cb = callback
|
||||
cmd = os.path.expanduser(cmd)
|
||||
self.command = shlex.split(cmd)
|
||||
self.partial_output = b""
|
||||
self.cancelled = False
|
||||
self.return_code = None
|
||||
|
||||
def _process_output(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
@@ -28,19 +30,27 @@ class ShellCommand:
|
||||
except Exception:
|
||||
return
|
||||
data = self.partial_output + data
|
||||
if b'\n' not in data:
|
||||
self.partial_output = data
|
||||
return
|
||||
elif data[-1] != b'\n':
|
||||
split = data.rfind(b'\n') + 1
|
||||
self.partial_output = data[split:]
|
||||
data = data[:split]
|
||||
try:
|
||||
self.output_cb(data)
|
||||
except Exception:
|
||||
logging.exception("Error writing command output")
|
||||
lines = data.split(b'\n')
|
||||
self.partial_output = lines.pop()
|
||||
for line in lines:
|
||||
try:
|
||||
self.output_cb(line)
|
||||
except Exception:
|
||||
logging.exception("Error writing command output")
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
def get_return_code(self):
|
||||
return self.return_code
|
||||
|
||||
async def run(self, timeout=2., verbose=True):
|
||||
self.return_code = fd = None
|
||||
self.partial_output = b""
|
||||
self.cancelled = False
|
||||
if timeout is None:
|
||||
# Never timeout
|
||||
timeout = 9999999999999999.
|
||||
if not timeout or self.output_cb is None:
|
||||
# Fire and forget commands cannot be verbose as we can't
|
||||
# clean up after the process terminates
|
||||
@@ -51,14 +61,14 @@ 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(
|
||||
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
|
||||
elif not timeout:
|
||||
# fire and forget, return from execution
|
||||
return
|
||||
return True
|
||||
sleeptime = 0
|
||||
complete = False
|
||||
while sleeptime < timeout:
|
||||
@@ -67,21 +77,45 @@ class ShellCommand:
|
||||
if proc.poll() is not None:
|
||||
complete = True
|
||||
break
|
||||
if self.cancelled:
|
||||
break
|
||||
if not complete:
|
||||
proc.terminate()
|
||||
if verbose:
|
||||
if self.partial_output:
|
||||
self.output_cb(self.partial_output)
|
||||
self.partial_output = b""
|
||||
if complete:
|
||||
msg = f"Command ({self.name}) finished"
|
||||
else:
|
||||
msg = f"Command ({self.name}) timed out"
|
||||
logging.info(msg)
|
||||
self.io_loop.remove_handler(fd)
|
||||
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.):
|
||||
result = []
|
||||
|
||||
def cb(data):
|
||||
data = data.strip()
|
||||
if data:
|
||||
result.append(data.decode())
|
||||
prev_cb = self.output_cb
|
||||
self.output_cb = cb
|
||||
await self.run(timeout)
|
||||
self.output_cb = prev_cb
|
||||
return "\n".join(result)
|
||||
|
||||
|
||||
class ShellCommandFactory:
|
||||
def build_shell_command(self, cmd, callback):
|
||||
def build_shell_command(self, cmd, callback=None):
|
||||
return ShellCommand(cmd, callback)
|
||||
|
||||
def load_plugin(config):
|
||||
|
||||
@@ -0,0 +1,731 @@
|
||||
# Provides updates for Klipper and Moonraker
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
import json
|
||||
import sys
|
||||
import shutil
|
||||
import zipfile
|
||||
import io
|
||||
import asyncio
|
||||
import time
|
||||
import tornado.gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.httpclient import AsyncHTTPClient
|
||||
from tornado.locks import Event
|
||||
|
||||
MOONRAKER_PATH = os.path.normpath(os.path.join(
|
||||
os.path.dirname(__file__), "../.."))
|
||||
SUPPLEMENTAL_CFG_PATH = os.path.join(
|
||||
MOONRAKER_PATH, "scripts/update_manager.conf")
|
||||
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
|
||||
SUPPORTED_DISTROS = ["debian"]
|
||||
|
||||
class UpdateManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.config = config
|
||||
self.config.read_supplemental_config(SUPPLEMENTAL_CFG_PATH)
|
||||
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
|
||||
self.http_client = AsyncHTTPClient()
|
||||
self.repo_debug = config.getboolean('enable_repo_debug', False)
|
||||
self.distro = config.get('distro', "debian").lower()
|
||||
if self.distro not in SUPPORTED_DISTROS:
|
||||
raise config.error(f"Unsupported distro: {self.distro}")
|
||||
if self.repo_debug:
|
||||
logging.warn("UPDATE MANAGER: REPO DEBUG ENABLED")
|
||||
env = sys.executable
|
||||
self.updaters = {
|
||||
"system": PackageUpdater(self),
|
||||
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
|
||||
}
|
||||
self.current_update = None
|
||||
client_repo = config.get("client_repo", None)
|
||||
if client_repo is not None:
|
||||
client_path = os.path.expanduser(config.get("client_path"))
|
||||
if os.path.islink(client_path):
|
||||
raise config.error(
|
||||
"Option 'client_path' cannot be set to a symbolic link")
|
||||
self.updaters['client'] = ClientUpdater(
|
||||
self, client_repo, client_path)
|
||||
|
||||
# GitHub API Rate Limit Tracking
|
||||
self.gh_rate_limit = None
|
||||
self.gh_limit_remaining = None
|
||||
self.gh_limit_reset_time = None
|
||||
self.gh_init_evt = Event()
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/moonraker", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/klipper", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/system", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/client", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/status", ["GET"],
|
||||
self._handle_status_request)
|
||||
|
||||
# Register Ready Event
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_identified", self._set_klipper_repo)
|
||||
# Initialize GitHub API Rate Limits
|
||||
IOLoop.current().spawn_callback(self._init_api_rate_limit)
|
||||
|
||||
async def _set_klipper_repo(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
if not kinfo:
|
||||
logging.info("No valid klippy info received")
|
||||
return
|
||||
kpath = kinfo['klipper_path']
|
||||
env = kinfo['python_path']
|
||||
kupdater = self.updaters.get('klipper', None)
|
||||
if kupdater is not None and kupdater.repo_path == kpath and \
|
||||
kupdater.env == env:
|
||||
# Current Klipper Updater is valid
|
||||
return
|
||||
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
|
||||
|
||||
async def _handle_update_request(self, web_request):
|
||||
app = web_request.get_endpoint().split("/")[-1]
|
||||
inc_deps = web_request.get_boolean('include_deps', False)
|
||||
if self.current_update:
|
||||
raise self.server.error("A current update is in progress")
|
||||
updater = self.updaters.get(app, None)
|
||||
if updater is None:
|
||||
raise self.server.error(f"Updater {app} not available")
|
||||
self.current_update = (app, id(web_request))
|
||||
try:
|
||||
await updater.update(inc_deps)
|
||||
except Exception:
|
||||
self.current_update = None
|
||||
raise
|
||||
self.current_update = None
|
||||
return "ok"
|
||||
|
||||
async def _handle_status_request(self, web_request):
|
||||
refresh = web_request.get_boolean('refresh', False)
|
||||
vinfo = {}
|
||||
for name, updater in self.updaters.items():
|
||||
await updater.check_initialized(120.)
|
||||
if refresh:
|
||||
ret = updater.refresh()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
if hasattr(updater, "get_update_status"):
|
||||
vinfo[name] = updater.get_update_status()
|
||||
return {
|
||||
'version_info': vinfo,
|
||||
'github_rate_limit': self.gh_rate_limit,
|
||||
'github_requests_remaining': self.gh_limit_remaining,
|
||||
'github_limit_reset_time': self.gh_limit_reset_time,
|
||||
'busy': self.current_update is not None}
|
||||
|
||||
async def execute_cmd(self, cmd, timeout=10., notify=False, retries=1):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
cb = self.notify_update_response if notify else None
|
||||
scmd = shell_command.build_shell_command(cmd, callback=cb)
|
||||
while retries:
|
||||
if await scmd.run(timeout=timeout, verbose=notify):
|
||||
break
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Shell Command Error")
|
||||
|
||||
async def execute_cmd_with_response(self, cmd, timeout=10.):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
return await scmd.run_with_response(timeout)
|
||||
|
||||
async def _init_api_rate_limit(self):
|
||||
url = "https://api.github.com/rate_limit"
|
||||
while 1:
|
||||
try:
|
||||
resp = await self.github_api_request(url, is_init=True)
|
||||
core = resp['resources']['core']
|
||||
self.gh_rate_limit = core['limit']
|
||||
self.gh_limit_remaining = core['remaining']
|
||||
self.gh_limit_reset_time = core['reset']
|
||||
except Exception:
|
||||
logging.exception("Error Initializing GitHub API Rate Limit")
|
||||
await tornado.gen.sleep(30.)
|
||||
else:
|
||||
reset_time = time.ctime(self.gh_limit_reset_time)
|
||||
logging.info(
|
||||
"GitHub API Rate Limit Initialized\n"
|
||||
f"Rate Limit: {self.gh_rate_limit}\n"
|
||||
f"Rate Limit Remaining: {self.gh_limit_remaining}\n"
|
||||
f"Rate Limit Reset Time: {reset_time}, "
|
||||
f"Seconds Since Epoch: {self.gh_limit_reset_time}")
|
||||
break
|
||||
self.gh_init_evt.set()
|
||||
|
||||
async def github_api_request(self, url, etag=None, is_init=False):
|
||||
if not is_init:
|
||||
timeout = time.time() + 30.
|
||||
try:
|
||||
await self.gh_init_evt.wait(timeout)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
"Timeout while waiting for GitHub "
|
||||
"API Rate Limit initialization")
|
||||
if self.gh_limit_remaining == 0:
|
||||
curtime = time.time()
|
||||
if curtime < self.gh_limit_reset_time:
|
||||
raise self.server.error(
|
||||
f"GitHub Rate Limit Reached\nRequest: {url}\n"
|
||||
f"Limit Reset Time: {time.ctime(self.gh_limit_remaining)}")
|
||||
headers = {"Accept": "application/vnd.github.v3+json"}
|
||||
if etag is not None:
|
||||
headers['If-None-Match'] = etag
|
||||
retries = 5
|
||||
while retries:
|
||||
try:
|
||||
resp = await self.http_client.fetch(
|
||||
url, headers=headers, connect_timeout=5.,
|
||||
request_timeout=5., raise_error=False)
|
||||
except Exception:
|
||||
retries -= 1
|
||||
msg = f"Error Processing GitHub API request: {url}"
|
||||
if not retries:
|
||||
raise self.server.error(msg)
|
||||
logging.exception(msg)
|
||||
await tornado.gen.sleep(1.)
|
||||
continue
|
||||
etag = resp.headers.get('etag', None)
|
||||
if etag is not None:
|
||||
if etag[:2] == "W/":
|
||||
etag = etag[2:]
|
||||
logging.info(
|
||||
"GitHub API Request Processed\n"
|
||||
f"URL: {url}\n"
|
||||
f"Response Code: {resp.code}\n"
|
||||
f"Response Reason: {resp.reason}\n"
|
||||
f"ETag: {etag}")
|
||||
if resp.code == 403:
|
||||
raise self.server.error(
|
||||
f"Forbidden GitHub Request: {resp.reason}")
|
||||
elif resp.code == 304:
|
||||
logging.info(f"Github Request not Modified: {url}")
|
||||
return None
|
||||
if resp.code != 200:
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error(
|
||||
f"Github Request failed: {resp.code} {resp.reason}")
|
||||
logging.info(
|
||||
f"Github request error, {retries} retries remaining")
|
||||
await tornado.gen.sleep(1.)
|
||||
continue
|
||||
# Update rate limit on return success
|
||||
if 'X-Ratelimit-Limit' in resp.headers and not is_init:
|
||||
self.gh_rate_limit = int(resp.headers['X-Ratelimit-Limit'])
|
||||
self.gh_limit_remaining = int(
|
||||
resp.headers['X-Ratelimit-Remaining'])
|
||||
self.gh_limit_reset_time = float(
|
||||
resp.headers['X-Ratelimit-Reset'])
|
||||
decoded = json.loads(resp.body)
|
||||
decoded['etag'] = etag
|
||||
return decoded
|
||||
|
||||
async def http_download_request(self, url):
|
||||
retries = 5
|
||||
while retries:
|
||||
try:
|
||||
resp = await self.http_client.fetch(
|
||||
url, headers={"Accept": "application/zip"},
|
||||
connect_timeout=5., request_timeout=120.)
|
||||
except Exception:
|
||||
retries -= 1
|
||||
logging.exception("Error Processing Download")
|
||||
if not retries:
|
||||
raise
|
||||
await tornado.gen.sleep(1.)
|
||||
continue
|
||||
return resp.body
|
||||
|
||||
def notify_update_response(self, resp, is_complete=False):
|
||||
resp = resp.strip()
|
||||
if isinstance(resp, bytes):
|
||||
resp = resp.decode()
|
||||
notification = {
|
||||
'message': resp,
|
||||
'application': None,
|
||||
'proc_id': None,
|
||||
'complete': is_complete}
|
||||
if self.current_update is not None:
|
||||
notification['application'] = self.current_update[0]
|
||||
notification['proc_id'] = self.current_update[1]
|
||||
self.server.send_event(
|
||||
"update_manager:update_response", notification)
|
||||
|
||||
def close(self):
|
||||
self.http_client.close()
|
||||
|
||||
|
||||
class GitUpdater:
|
||||
def __init__(self, umgr, name, path, env):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.execute_cmd_with_response = umgr.execute_cmd_with_response
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
distro = umgr.distro
|
||||
config = umgr.config
|
||||
self.repo_info = config[f"repo_info {name}"].get_options()
|
||||
self.dist_info = config[f"dist_info {distro} {name}"].get_options()
|
||||
self.name = name
|
||||
self.repo_path = path
|
||||
self.env = env
|
||||
self.version = self.cur_hash = "?"
|
||||
self.remote_version = self.remote_hash = "?"
|
||||
self.init_evt = Event()
|
||||
self.debug = umgr.repo_debug
|
||||
self.remote = "origin"
|
||||
self.branch = "master"
|
||||
self.is_valid = self.is_dirty = self.detached = False
|
||||
IOLoop.current().spawn_callback(self.refresh)
|
||||
|
||||
def _get_version_info(self):
|
||||
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
|
||||
vinfo = {}
|
||||
if os.path.isfile(ver_path):
|
||||
data = ""
|
||||
with open(ver_path, 'r') as f:
|
||||
data = f.read()
|
||||
try:
|
||||
entries = [e.strip() for e in data.split('\n') if e.strip()]
|
||||
vinfo = dict([i.split('=') for i in entries])
|
||||
vinfo = {k: tuple(re.findall(r"\d+", v)) for k, v in
|
||||
vinfo.items()}
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
self._log_info(f"Version Info Found: {vinfo}")
|
||||
vinfo['version'] = tuple(re.findall(r"\d+", self.version))
|
||||
return vinfo
|
||||
|
||||
def _log_exc(self, msg, traceback=True):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
if traceback:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return self.server.error(msg)
|
||||
|
||||
def _log_info(self, msg):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.info(log_msg)
|
||||
|
||||
def _notify_status(self, msg, is_complete=False):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.debug(log_msg)
|
||||
self.notify_update_response(log_msg, is_complete)
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
if self.init_evt.is_set():
|
||||
return
|
||||
if timeout is not None:
|
||||
timeout = IOLoop.current().time() + timeout
|
||||
await self.init_evt.wait(timeout)
|
||||
|
||||
async def refresh(self):
|
||||
await self._check_version()
|
||||
self.init_evt.set()
|
||||
|
||||
async def _check_version(self, need_fetch=True):
|
||||
self.is_valid = self.detached = False
|
||||
self.cur_hash = self.branch = self.remote = "?"
|
||||
self.version = self.remote_version = "?"
|
||||
try:
|
||||
blist = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} branch --list")
|
||||
if blist.startswith("fatal:"):
|
||||
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
|
||||
return
|
||||
branch = None
|
||||
for b in blist.split("\n"):
|
||||
b = b.strip()
|
||||
if b[0] == "*":
|
||||
branch = b[2:]
|
||||
break
|
||||
if branch is None:
|
||||
self._log_info(
|
||||
"Unable to retreive current branch from branch list\n"
|
||||
f"{blist}")
|
||||
return
|
||||
if "HEAD detached" in branch:
|
||||
bparts = branch.split()[-1].strip("()")
|
||||
self.remote, self.branch = bparts.split("/")
|
||||
self.detached = True
|
||||
else:
|
||||
self.branch = branch.strip()
|
||||
self.remote = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} config --get"
|
||||
f" branch.{self.branch}.remote")
|
||||
if need_fetch:
|
||||
await self.execute_cmd(
|
||||
f"git -C {self.repo_path} fetch {self.remote} --prune -q",
|
||||
retries=3)
|
||||
remote_url = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} remote get-url {self.remote}")
|
||||
cur_hash = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse HEAD")
|
||||
remote_hash = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse "
|
||||
f"{self.remote}/{self.branch}")
|
||||
repo_version = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} describe --always "
|
||||
"--tags --long --dirty")
|
||||
remote_version = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} describe {self.remote}/{self.branch}"
|
||||
" --always --tags --long")
|
||||
except Exception:
|
||||
self._log_exc("Error retreiving git info")
|
||||
return
|
||||
|
||||
self.is_dirty = repo_version.endswith("dirty")
|
||||
versions = []
|
||||
for ver in [repo_version, remote_version]:
|
||||
tag_version = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
versions.append(tag_version)
|
||||
self.version, self.remote_version = versions
|
||||
self.cur_hash = cur_hash.strip()
|
||||
self.remote_hash = remote_hash.strip()
|
||||
self._log_info(
|
||||
f"Repo Detected:\nPath: {self.repo_path}\nRemote: {self.remote}\n"
|
||||
f"Branch: {self.branch}\nRemote URL: {remote_url}\n"
|
||||
f"Current SHA: {self.cur_hash}\n"
|
||||
f"Remote SHA: {self.remote_hash}\nVersion: {self.version}\n"
|
||||
f"Remote Version: {self.remote_version}\n"
|
||||
f"Is Dirty: {self.is_dirty}\nIs Detached: {self.detached}")
|
||||
if self.debug:
|
||||
self.is_valid = True
|
||||
self._log_info("Debug enabled, bypassing official repo check")
|
||||
elif self.branch == "master" and self.remote == "origin":
|
||||
if self.detached:
|
||||
self._log_info("Detached HEAD detected, repo invalid")
|
||||
return
|
||||
remote_url = remote_url.lower()
|
||||
if remote_url[-4:] != ".git":
|
||||
remote_url += ".git"
|
||||
if remote_url == self.repo_info['origin']:
|
||||
self.is_valid = True
|
||||
self._log_info("Validity check for git repo passed")
|
||||
else:
|
||||
self._log_info(f"Invalid git origin url '{remote_url}'")
|
||||
else:
|
||||
self._log_info(
|
||||
"Git repo not on offical remote/branch: "
|
||||
f"{self.remote}/{self.branch}")
|
||||
|
||||
async def update(self, update_deps=False):
|
||||
if not self.is_valid:
|
||||
raise self._log_exc("Update aborted, repo is not valid", False)
|
||||
if self.is_dirty:
|
||||
raise self._log_exc(
|
||||
"Update aborted, repo is has been modified", False)
|
||||
if self.remote_hash == self.cur_hash:
|
||||
# No need to update
|
||||
return
|
||||
self._notify_status("Updating Repo...")
|
||||
try:
|
||||
if self.detached:
|
||||
await self.execute_cmd(
|
||||
f"git -C {self.repo_path} fetch {self.remote} -q",
|
||||
retries=3)
|
||||
await self.execute_cmd(
|
||||
f"git -C {self.repo_path} checkout"
|
||||
f" {self.remote}/{self.branch} -q")
|
||||
else:
|
||||
await self.execute_cmd(
|
||||
f"git -C {self.repo_path} pull -q", retries=3)
|
||||
except Exception:
|
||||
raise self._log_exc("Error running 'git pull'")
|
||||
# Check Semantic Versions
|
||||
vinfo = self._get_version_info()
|
||||
cur_version = vinfo.get('version', ())
|
||||
update_deps |= cur_version < vinfo.get('deps_version', ())
|
||||
need_env_rebuild = cur_version < vinfo.get('env_version', ())
|
||||
if update_deps:
|
||||
await self._install_packages()
|
||||
await self._update_virtualenv(need_env_rebuild)
|
||||
elif need_env_rebuild:
|
||||
await self._update_virtualenv(True)
|
||||
# Refresh local repo state
|
||||
await self._check_version(need_fetch=False)
|
||||
if self.name == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
self._notify_status("Update Finished...",
|
||||
is_complete=True)
|
||||
IOLoop.current().call_later(.1, self.restart_service)
|
||||
else:
|
||||
await self.restart_service()
|
||||
self._notify_status("Update Finished...", is_complete=True)
|
||||
|
||||
async def _install_packages(self):
|
||||
# Open install file file and read
|
||||
inst_script = self.dist_info['install_script']
|
||||
inst_path = os.path.join(self.repo_path, inst_script)
|
||||
if not os.path.isfile(inst_path):
|
||||
self._log_info(f"Unable to open install script: {inst_path}")
|
||||
return
|
||||
with open(inst_path, 'r') as f:
|
||||
data = f.read()
|
||||
packages = re.findall(r'PKGLIST="(.*)"', data)
|
||||
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
|
||||
if not packages:
|
||||
self._log_info(f"No packages found in script: {inst_path}")
|
||||
return
|
||||
# TODO: Log and notify that packages will be installed
|
||||
pkgs = " ".join(packages)
|
||||
logging.debug(f"Repo {self.name}: Detected Packages: {pkgs}")
|
||||
self._notify_status("Installing system dependencies...")
|
||||
# Install packages with apt-get
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} install --yes {pkgs}", timeout=3600.,
|
||||
notify=True)
|
||||
except Exception:
|
||||
self._log_exc("Error updating packages via apt-get")
|
||||
return
|
||||
|
||||
async def _update_virtualenv(self, rebuild_env=False):
|
||||
# Update python dependencies
|
||||
bin_dir = os.path.dirname(self.env)
|
||||
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
|
||||
if rebuild_env:
|
||||
env_args = self.repo_info['venv_args']
|
||||
self._notify_status(f"Creating virtualenv at: {env_path}...")
|
||||
if os.path.exists(env_path):
|
||||
shutil.rmtree(env_path)
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"virtualenv {env_args} {env_path}", timeout=300.)
|
||||
except Exception:
|
||||
self._log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
if not os.path.expanduser(self.env):
|
||||
raise self._log_exc("Failed to create new virtualenv", False)
|
||||
reqs = os.path.join(
|
||||
self.repo_path, self.repo_info['requirements'])
|
||||
if not os.path.isfile(reqs):
|
||||
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
|
||||
return
|
||||
pip = os.path.join(bin_dir, "pip")
|
||||
self._notify_status("Updating python packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{pip} install -r {reqs}", timeout=1200., notify=True,
|
||||
retries=3)
|
||||
except Exception:
|
||||
self._log_exc("Error updating python requirements")
|
||||
self._install_python_dist_requirements(env_path)
|
||||
|
||||
def _install_python_dist_requirements(self, env_path):
|
||||
dist_reqs = self.dist_info.get('python_dist_packages', None)
|
||||
if dist_reqs is None:
|
||||
return
|
||||
dist_reqs = [r.strip() for r in dist_reqs.split("\n")
|
||||
if r.strip()]
|
||||
dist_path = self.dist_info['python_dist_path']
|
||||
site_path = os.path.join(env_path, self.dist_info['env_package_path'])
|
||||
for pkg in dist_reqs:
|
||||
for f in os.listdir(dist_path):
|
||||
if f.startswith(pkg):
|
||||
src = os.path.join(dist_path, f)
|
||||
dest = os.path.join(site_path, f)
|
||||
self._notify_status(f"Linking to dist package: {pkg}")
|
||||
if os.path.islink(dest):
|
||||
os.remove(dest)
|
||||
elif os.path.exists(dest):
|
||||
self._notify_status(
|
||||
f"Error symlinking dist package: {pkg}, "
|
||||
f"file already exists: {dest}")
|
||||
continue
|
||||
os.symlink(src, dest)
|
||||
break
|
||||
|
||||
async def restart_service(self):
|
||||
self._notify_status("Restarting Service...")
|
||||
try:
|
||||
await self.execute_cmd(f"sudo systemctl restart {self.name}")
|
||||
except Exception:
|
||||
raise self._log_exc("Error restarting service")
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'remote_alias': self.remote,
|
||||
'branch': self.branch,
|
||||
'version': self.version,
|
||||
'remote_version': self.remote_version,
|
||||
'current_hash': self.cur_hash,
|
||||
'remote_hash': self.remote_hash,
|
||||
'is_dirty': self.is_dirty,
|
||||
'is_valid': self.is_valid,
|
||||
'detached': self.detached,
|
||||
'debug_enabled': self.debug}
|
||||
|
||||
|
||||
class PackageUpdater:
|
||||
def __init__(self, umgr):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.execute_cmd_with_response = umgr.execute_cmd_with_response
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
self.available_packages = []
|
||||
self.init_evt = Event()
|
||||
IOLoop.current().spawn_callback(self.refresh)
|
||||
|
||||
async def refresh(self):
|
||||
# TODO: Use python-apt python lib rather than command line for updates
|
||||
try:
|
||||
await self.execute_cmd(f"{APT_CMD} update", timeout=300.)
|
||||
res = await self.execute_cmd_with_response(
|
||||
"apt list --upgradable")
|
||||
except Exception:
|
||||
logging.exception("Error Refreshing System Packages")
|
||||
else:
|
||||
pkg_list = [p.strip() for p in res.split("\n") if p.strip()]
|
||||
if pkg_list:
|
||||
pkg_list = pkg_list[2:]
|
||||
self.available_packages = [p.split("/", maxsplit=1)[0]
|
||||
for p in pkg_list]
|
||||
pkg_list = "\n".join(self.available_packages)
|
||||
logging.info(
|
||||
f"Detected {len(self.available_packages)} package updates:"
|
||||
f"\n{pkg_list}")
|
||||
self.init_evt.set()
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
if self.init_evt.is_set():
|
||||
return
|
||||
if timeout is not None:
|
||||
timeout = IOLoop.current().time() + timeout
|
||||
await self.init_evt.wait(timeout)
|
||||
|
||||
async def update(self, *args):
|
||||
self.notify_update_response("Updating packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
|
||||
except Exception:
|
||||
raise self.server.error("Error updating system packages")
|
||||
self.available_packages = []
|
||||
self.notify_update_response("Package update finished...",
|
||||
is_complete=True)
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'package_count': len(self.available_packages),
|
||||
'package_list': self.available_packages
|
||||
}
|
||||
|
||||
class ClientUpdater:
|
||||
def __init__(self, umgr, repo, path):
|
||||
self.umgr = umgr
|
||||
self.server = umgr.server
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
self.repo = repo.strip().strip("/")
|
||||
self.name = self.repo.split("/")[-1]
|
||||
self.path = path
|
||||
self.version = self.remote_version = self.dl_url = "?"
|
||||
self.etag = None
|
||||
self.init_evt = Event()
|
||||
self._get_local_version()
|
||||
logging.info(f"\nInitializing Client Updater: '{self.name}',"
|
||||
f"\nversion: {self.version}"
|
||||
f"\npath: {self.path}")
|
||||
IOLoop.current().spawn_callback(self.refresh)
|
||||
|
||||
def _get_local_version(self):
|
||||
version_path = os.path.join(self.path, ".version")
|
||||
if os.path.isfile(os.path.join(self.path, ".version")):
|
||||
with open(version_path, "r") as f:
|
||||
v = f.read()
|
||||
self.version = v.strip()
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
if self.init_evt.is_set():
|
||||
return
|
||||
if timeout is not None:
|
||||
timeout = IOLoop.current().time() + timeout
|
||||
await self.init_evt.wait(timeout)
|
||||
|
||||
async def refresh(self):
|
||||
# Local state
|
||||
self._get_local_version()
|
||||
|
||||
# Remote state
|
||||
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
|
||||
try:
|
||||
result = await self.umgr.github_api_request(url, etag=self.etag)
|
||||
except Exception:
|
||||
logging.exception(f"Client {self.repo}: Github Request Error")
|
||||
result = {}
|
||||
if result is None:
|
||||
# No change, update not necessary
|
||||
return None
|
||||
self.etag = result.get('etag', None)
|
||||
self.remote_version = result.get('name', "?")
|
||||
release_assets = result.get('assets', [{}])[0]
|
||||
self.dl_url = release_assets.get('browser_download_url', "?")
|
||||
logging.info(
|
||||
f"Github client Info Received:\nRepo: {self.name}\n"
|
||||
f"Local Version: {self.version}\n"
|
||||
f"Remote Version: {self.remote_version}\n"
|
||||
f"url: {self.dl_url}")
|
||||
self.init_evt.set()
|
||||
|
||||
async def update(self, *args):
|
||||
if self.remote_version == "?":
|
||||
await self.refresh()
|
||||
if self.remote_version == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Unable to locate update")
|
||||
if self.dl_url == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Invalid download url")
|
||||
if self.version == self.remote_version:
|
||||
# Already up to date
|
||||
return
|
||||
if os.path.isdir(self.path):
|
||||
shutil.rmtree(self.path)
|
||||
os.mkdir(self.path)
|
||||
self.notify_update_response(f"Downloading Client: {self.name}")
|
||||
archive = await self.umgr.http_download_request(self.dl_url)
|
||||
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
|
||||
zf.extractall(self.path)
|
||||
self.version = self.remote_version
|
||||
version_path = os.path.join(self.path, ".version")
|
||||
if not os.path.exists(version_path):
|
||||
with open(version_path, "w") as f:
|
||||
f.write(self.version)
|
||||
self.notify_update_response(f"Client Update Finished: {self.name}",
|
||||
is_complete=True)
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'version': self.version,
|
||||
'remote_version': self.remote_version
|
||||
}
|
||||
|
||||
def load_plugin(config):
|
||||
return UpdateManager(config)
|
||||
+19
-9
@@ -6,6 +6,7 @@
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
from queue import SimpleQueue as Queue
|
||||
@@ -28,10 +29,10 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
|
||||
self.handleError(record)
|
||||
|
||||
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
def __init__(self, filename, **kwargs):
|
||||
def __init__(self, software_version, filename, **kwargs):
|
||||
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
|
||||
self.header = "Moonraker Log Start...\n"
|
||||
self.header += "Git Version: " + get_software_version() + "\n"
|
||||
self.header += f"Git Version: {software_version}\n"
|
||||
self.header += "="*80 + "\n"
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
@@ -67,17 +68,26 @@ def get_software_version():
|
||||
|
||||
return "?"
|
||||
|
||||
def setup_logging(log_file):
|
||||
def setup_logging(log_file, software_version):
|
||||
root_logger = logging.getLogger()
|
||||
queue = Queue()
|
||||
queue_handler = LocalQueueHandler(queue)
|
||||
root_logger.addHandler(queue_handler)
|
||||
root_logger.setLevel(logging.INFO)
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
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)
|
||||
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
|
||||
+142
-44
@@ -14,6 +14,65 @@ from utils import ServerError
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class WebRequest:
|
||||
def __init__(self, endpoint, args, action="", conn=None):
|
||||
self.endpoint = endpoint
|
||||
self.action = action
|
||||
self.args = args
|
||||
self.conn = conn
|
||||
|
||||
def get_endpoint(self):
|
||||
return self.endpoint
|
||||
|
||||
def get_action(self):
|
||||
return self.action
|
||||
|
||||
def get_args(self):
|
||||
return self.args
|
||||
|
||||
def get_connection(self):
|
||||
return self.conn
|
||||
|
||||
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
|
||||
if key not in self.args:
|
||||
if default == Sentinel:
|
||||
raise ServerError(f"No data for argument: {key}")
|
||||
return default
|
||||
val = self.args[key]
|
||||
try:
|
||||
if dtype != bool:
|
||||
return dtype(val)
|
||||
else:
|
||||
if isinstance(val, str):
|
||||
val = val.lower()
|
||||
if val in ["true", "false"]:
|
||||
return True if val == "true" else False
|
||||
elif isinstance(val, bool):
|
||||
return val
|
||||
raise TypeError
|
||||
except Exception:
|
||||
raise ServerError(
|
||||
f"Unable to convert argument [{key}] to {dtype}: "
|
||||
f"value recieved: {val}")
|
||||
|
||||
def get(self, key, default=Sentinel):
|
||||
val = self.args.get(key, default)
|
||||
if val == Sentinel:
|
||||
raise ServerError(f"No data for argument: {key}")
|
||||
return val
|
||||
|
||||
def get_str(self, key, default=Sentinel):
|
||||
return self._get_converted_arg(key, default)
|
||||
|
||||
def get_int(self, key, default=Sentinel):
|
||||
return self._get_converted_arg(key, default, int)
|
||||
|
||||
def get_float(self, key, default=Sentinel):
|
||||
return self._get_converted_arg(key, default, float)
|
||||
|
||||
def get_boolean(self, key, default=Sentinel):
|
||||
return self._get_converted_arg(key, default, bool)
|
||||
|
||||
class JsonRPC:
|
||||
def __init__(self):
|
||||
self.methods = {}
|
||||
@@ -24,7 +83,7 @@ class JsonRPC:
|
||||
def remove_method(self, name):
|
||||
self.methods.pop(name, None)
|
||||
|
||||
async def dispatch(self, data):
|
||||
async def dispatch(self, data, ws):
|
||||
response = None
|
||||
try:
|
||||
request = json.loads(data)
|
||||
@@ -37,19 +96,19 @@ class JsonRPC:
|
||||
if isinstance(request, list):
|
||||
response = []
|
||||
for req in request:
|
||||
resp = await self.process_request(req)
|
||||
resp = await self.process_request(req, ws)
|
||||
if resp is not None:
|
||||
response.append(resp)
|
||||
if not response:
|
||||
response = None
|
||||
else:
|
||||
response = await self.process_request(request)
|
||||
response = await self.process_request(request, ws)
|
||||
if response is not None:
|
||||
response = json.dumps(response)
|
||||
logging.debug("Websocket Response::" + response)
|
||||
return response
|
||||
|
||||
async def process_request(self, request):
|
||||
async def process_request(self, request, ws):
|
||||
req_id = request.get('id', None)
|
||||
rpc_version = request.get('jsonrpc', "")
|
||||
method_name = request.get('method', None)
|
||||
@@ -61,20 +120,22 @@ class JsonRPC:
|
||||
if 'params' in request:
|
||||
params = request['params']
|
||||
if isinstance(params, list):
|
||||
response = await self.execute_method(method, req_id, *params)
|
||||
response = await self.execute_method(
|
||||
method, req_id, ws, *params)
|
||||
elif isinstance(params, dict):
|
||||
response = await self.execute_method(method, req_id, **params)
|
||||
response = await self.execute_method(
|
||||
method, req_id, ws, **params)
|
||||
else:
|
||||
return self.build_error(-32600, "Invalid Request", req_id)
|
||||
else:
|
||||
response = await self.execute_method(method, req_id)
|
||||
response = await self.execute_method(method, req_id, ws)
|
||||
return response
|
||||
|
||||
async def execute_method(self, method, req_id, *args, **kwargs):
|
||||
async def execute_method(self, method, req_id, ws, *args, **kwargs):
|
||||
try:
|
||||
result = await method(*args, **kwargs)
|
||||
result = await method(ws, *args, **kwargs)
|
||||
except TypeError as e:
|
||||
return self.build_error(-32603, "Invalid params", req_id)
|
||||
return self.build_error(-32603, f"Invalid params:\n{e}", req_id)
|
||||
except ServerError as e:
|
||||
return self.build_error(e.status_code, str(e), req_id)
|
||||
except Exception as e:
|
||||
@@ -106,17 +167,31 @@ class WebsocketManager:
|
||||
self.ws_lock = tornado.locks.Lock()
|
||||
self.rpc = JsonRPC()
|
||||
|
||||
self.rpc.register_method("server.websocket.id", self._handle_id_request)
|
||||
|
||||
# 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(
|
||||
"server:gcode_response", self._handle_gcode_response)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._handle_status_update)
|
||||
self.server.register_event_handler(
|
||||
"file_manager:filelist_changed", self._handle_filelist_changed)
|
||||
self.server.register_event_handler(
|
||||
"file_manager:metadata_update", self._handle_metadata_update)
|
||||
self.server.register_event_handler(
|
||||
"gpio_power:power_changed", self._handle_power_changed)
|
||||
self.server.register_event_handler(
|
||||
"update_manager:update_response", self._handle_update_response)
|
||||
|
||||
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")
|
||||
@@ -124,46 +199,56 @@ class WebsocketManager:
|
||||
async def _handle_gcode_response(self, response):
|
||||
await self.notify_websockets("gcode_response", response)
|
||||
|
||||
async def _handle_status_update(self, status):
|
||||
await self.notify_websockets("status_update", status)
|
||||
|
||||
async def _handle_filelist_changed(self, flist):
|
||||
await self.notify_websockets("filelist_changed", flist)
|
||||
|
||||
async def _handle_metadata_update(self, metadata):
|
||||
await self.notify_websockets("metadata_update", metadata)
|
||||
|
||||
def register_handler(self, api_def, callback=None):
|
||||
for r_method in api_def.request_methods:
|
||||
cmd = r_method.lower() + '_' + api_def.ws_method
|
||||
if callback is not None:
|
||||
# Callback is a local method
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, r_method, callback)
|
||||
else:
|
||||
# Callback is a remote method
|
||||
rpc_cb = self._generate_callback(api_def.endpoint)
|
||||
self.rpc.register_method(cmd, rpc_cb)
|
||||
async def _handle_power_changed(self, pstatus):
|
||||
await self.notify_websockets("power_changed", pstatus)
|
||||
|
||||
async def _handle_update_response(self, response):
|
||||
await self.notify_websockets("update_response", response)
|
||||
|
||||
def register_local_handler(self, api_def, callback):
|
||||
for ws_method, req_method in \
|
||||
zip(api_def.ws_methods, api_def.request_methods):
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, req_method, callback)
|
||||
self.rpc.register_method(ws_method, rpc_cb)
|
||||
|
||||
def register_remote_handler(self, api_def):
|
||||
ws_method = api_def.ws_methods[0]
|
||||
rpc_cb = self._generate_callback(api_def.endpoint)
|
||||
self.rpc.register_method(ws_method, rpc_cb)
|
||||
|
||||
def remove_handler(self, ws_method):
|
||||
for prefix in ["get", "post", "delete"]:
|
||||
self.rpc.remove_method(prefix + "_" + ws_method)
|
||||
self.rpc.remove_method(ws_method)
|
||||
|
||||
def _generate_callback(self, endpoint):
|
||||
async def func(**kwargs):
|
||||
result = await self.server.make_request(endpoint, kwargs)
|
||||
async def func(ws, **kwargs):
|
||||
result = await self.server.make_request(
|
||||
WebRequest(endpoint, kwargs, conn=ws))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _generate_local_callback(self, endpoint, request_method, callback):
|
||||
async def func(**kwargs):
|
||||
result = await callback(endpoint, request_method, kwargs)
|
||||
async def func(ws, **kwargs):
|
||||
result = await callback(
|
||||
WebRequest(endpoint, kwargs, request_method, ws))
|
||||
return result
|
||||
return func
|
||||
|
||||
async def _handle_id_request(self, ws, **kwargs):
|
||||
return {'websocket_id': ws.uid}
|
||||
|
||||
def has_websocket(self, ws_id):
|
||||
return ws_id in self.websockets
|
||||
|
||||
def get_websocket(self, ws_id):
|
||||
return self.websockets.get(ws_id, None)
|
||||
|
||||
async def add_websocket(self, ws):
|
||||
async with self.ws_lock:
|
||||
self.websockets[ws.uid] = ws
|
||||
@@ -173,17 +258,17 @@ class WebsocketManager:
|
||||
async with self.ws_lock:
|
||||
old_ws = self.websockets.pop(ws.uid, None)
|
||||
if old_ws is not None:
|
||||
self.server.remove_subscription(old_ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
|
||||
async def notify_websockets(self, name, data=Sentinel):
|
||||
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
|
||||
if data != Sentinel:
|
||||
msg['params'] = [data]
|
||||
notification = json.dumps(msg)
|
||||
async with self.ws_lock:
|
||||
for ws in list(self.websockets.values()):
|
||||
try:
|
||||
ws.write_message(notification)
|
||||
ws.write_message(msg)
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(ws.uid, None)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
@@ -198,9 +283,10 @@ class WebsocketManager:
|
||||
self.websockets = {}
|
||||
|
||||
class WebSocket(WebSocketHandler):
|
||||
def initialize(self, wsm, auth):
|
||||
self.wsm = wsm
|
||||
self.auth = auth
|
||||
def initialize(self):
|
||||
app = self.settings['parent']
|
||||
self.auth = app.get_auth()
|
||||
self.wsm = app.get_websocket_manager()
|
||||
self.rpc = self.wsm.rpc
|
||||
self.uid = id(self)
|
||||
|
||||
@@ -213,23 +299,35 @@ class WebSocket(WebSocketHandler):
|
||||
|
||||
async def _process_message(self, message):
|
||||
try:
|
||||
response = await self.rpc.dispatch(message)
|
||||
response = await self.rpc.dispatch(message, self)
|
||||
if response is not None:
|
||||
self.write_message(response)
|
||||
except Exception:
|
||||
logging.exception("Websocket Command Error")
|
||||
|
||||
def send_status(self, status):
|
||||
if not status:
|
||||
return
|
||||
try:
|
||||
self.write_message({
|
||||
'jsonrpc': "2.0",
|
||||
'method': "notify_status_update",
|
||||
'params': [status]})
|
||||
except WebSocketClosedError:
|
||||
logging.info(
|
||||
f"Websocket Closed During Status Update: {self.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {self.uid}")
|
||||
|
||||
def on_close(self):
|
||||
io_loop = IOLoop.current()
|
||||
io_loop.spawn_callback(self.wsm.remove_websocket, self)
|
||||
|
||||
def check_origin(self, origin):
|
||||
if self.settings['enable_cors']:
|
||||
# allow CORS
|
||||
return True
|
||||
else:
|
||||
return super(WebSocket, self).check_origin(origin)
|
||||
|
||||
if not super(WebSocket, self).check_origin(origin):
|
||||
return self.auth.check_cors(origin)
|
||||
return True
|
||||
# Check Authorized User
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
|
||||
+346
-103
@@ -9,8 +9,10 @@ import argparse
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import base64
|
||||
import traceback
|
||||
import io
|
||||
from PIL import Image
|
||||
|
||||
# regex helpers
|
||||
def _regex_find_floats(pattern, data, strict=False):
|
||||
@@ -38,69 +40,150 @@ def _regex_find_ints(pattern, data):
|
||||
pass
|
||||
return []
|
||||
|
||||
def _regex_find_first(pattern, data, cast=float):
|
||||
match = re.search(pattern, data)
|
||||
val = None
|
||||
if match:
|
||||
try:
|
||||
val = cast(match.group(1))
|
||||
except Exception:
|
||||
return None
|
||||
return val
|
||||
|
||||
# Slicer parsing implementations
|
||||
class BaseSlicer(object):
|
||||
def __init__(self, name, id_pattern):
|
||||
self.name = name
|
||||
self.id_pattern = id_pattern
|
||||
def __init__(self, file_path):
|
||||
self.path = file_path
|
||||
self.header_data = self.footer_data = self.log = None
|
||||
|
||||
def set_data(self, header_data, footer_data, log):
|
||||
def set_data(self, header_data, footer_data, fsize, log):
|
||||
self.header_data = header_data
|
||||
self.footer_data = footer_data
|
||||
self.size = fsize
|
||||
self.log = log
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_id_pattern(self):
|
||||
return self.id_pattern
|
||||
|
||||
def _parse_min_float(self, pattern, data):
|
||||
result = _regex_find_floats(pattern, data)
|
||||
def _parse_min_float(self, pattern, data, strict=False):
|
||||
result = _regex_find_floats(pattern, data, strict)
|
||||
if result:
|
||||
return min(result)
|
||||
else:
|
||||
return None
|
||||
|
||||
def _parse_max_float(self, pattern, data):
|
||||
result = _regex_find_floats(pattern, data)
|
||||
def _parse_max_float(self, pattern, data, strict=False):
|
||||
result = _regex_find_floats(pattern, data, strict)
|
||||
if result:
|
||||
return max(result)
|
||||
else:
|
||||
return None
|
||||
|
||||
class PrusaSlicer(BaseSlicer):
|
||||
def __init__(self, name="PrusaSlicer", id_pattern=r"PrusaSlicer\s.*\son"):
|
||||
super(PrusaSlicer, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
return None
|
||||
|
||||
def parse_gcode_start_byte(self):
|
||||
m = re.search(r"\n[MG]\d+\s.*\n", self.header_data)
|
||||
if m is None:
|
||||
return None
|
||||
return m.start()
|
||||
|
||||
def parse_gcode_end_byte(self):
|
||||
rev_data = self.footer_data[::-1]
|
||||
m = re.search(r"\n.*\s\d+[MG]\n", rev_data)
|
||||
if m is None:
|
||||
return None
|
||||
return self.size - m.start()
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return self._parse_min_float(
|
||||
r"; first_layer_height =.*", self.footer_data)
|
||||
return None
|
||||
|
||||
def parse_layer_height(self):
|
||||
return self._parse_min_float(r"; layer_height =.*", self.footer_data)
|
||||
return None
|
||||
|
||||
def parse_object_height(self):
|
||||
return None
|
||||
|
||||
def parse_filament_total(self):
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
return None
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return None
|
||||
|
||||
def parse_thumbnails(self):
|
||||
return None
|
||||
|
||||
class UnknownSlicer(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
return {'slicer': "Unknown"}
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M109 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
class PrusaSlicer(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"PrusaSlicer\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "PrusaSlicer",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return _regex_find_first(
|
||||
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
r"; layer_height = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
matches = re.findall(
|
||||
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
|
||||
if matches:
|
||||
try:
|
||||
matches = [float(m) for m in matches]
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
return max(matches)
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
return self._parse_max_float(
|
||||
r"filament\sused\s\[mm\]\s=\s\d+\.\d*", self.footer_data)
|
||||
return _regex_find_first(
|
||||
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self):
|
||||
time_matches = re.findall(
|
||||
time_match = re.search(
|
||||
r';\sestimated\sprinting\stime.*', self.footer_data)
|
||||
if not time_matches:
|
||||
if not time_match:
|
||||
return None
|
||||
total_time = 0
|
||||
time_match = time_matches[0]
|
||||
time_patterns = [(r"\d+d", 24*60*60), (r"\d+h", 60*60),
|
||||
(r"\d+m", 60), (r"\d+s", 1)]
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = _regex_find_ints(pattern, time_match)
|
||||
if t:
|
||||
total_time += max(t) * multiplier
|
||||
time_match = time_match.group()
|
||||
time_patterns = [(r"(\d+)d", 24*60*60), (r"(\d+)h", 60*60),
|
||||
(r"(\d+)m", 60), (r"(\d+)s", 1)]
|
||||
try:
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = re.search(pattern, time_match)
|
||||
if t:
|
||||
total_time += int(t.group(1)) * multiplier
|
||||
except Exception:
|
||||
return None
|
||||
return round(total_time, 2)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
@@ -126,48 +209,79 @@ class PrusaSlicer(BaseSlicer):
|
||||
parsed_matches.append({
|
||||
'width': info[0], 'height': info[1],
|
||||
'size': info[2], 'data': data})
|
||||
|
||||
return parsed_matches
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
class Slic3rPE(PrusaSlicer):
|
||||
def __init__(self, name="Slic3r PE",
|
||||
id_pattern=r"Slic3r\sPrusa\sEdition\s.*\son"):
|
||||
super(Slic3rPE, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "Slic3r PE",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_filament_total(self):
|
||||
return self._parse_max_float(
|
||||
r"filament\sused\s=\s\d+\.\d+mm", self.footer_data)
|
||||
return _regex_find_first(
|
||||
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
return None
|
||||
|
||||
class Slic3r(Slic3rPE):
|
||||
def __init__(self, name="Slic3r", id_pattern=r"Slic3r\s\d.*\son"):
|
||||
super(Slic3r, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Slic3r\s(\d.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "Slic3r",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
return None
|
||||
|
||||
class SuperSlicer(PrusaSlicer):
|
||||
def __init__(self, name="SuperSlicer", id_pattern=r"SuperSlicer\s.*\son"):
|
||||
super(SuperSlicer, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"SuperSlicer\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "SuperSlicer",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
class Cura(BaseSlicer):
|
||||
def __init__(self, name="Cura", id_pattern=r"Cura_SteamEngine.*"):
|
||||
super(Cura, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Cura_SteamEngine\s(.*)", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "Cura",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return self._parse_min_float(r";MINZ:.*", self.header_data)
|
||||
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return self._parse_min_float(r";Layer\sheight:.*", self.header_data)
|
||||
return _regex_find_first(
|
||||
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(r";MAXZ:.*", self.header_data)
|
||||
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
filament = self._parse_max_float(
|
||||
r";Filament\sused:.*", self.header_data)
|
||||
filament = _regex_find_first(
|
||||
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
|
||||
if filament is not None:
|
||||
filament *= 1000
|
||||
return filament
|
||||
@@ -175,55 +289,132 @@ class Cura(BaseSlicer):
|
||||
def parse_estimated_time(self):
|
||||
return self._parse_max_float(r";TIME:.*", self.header_data)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M109 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
return None
|
||||
thumbName = os.path.splitext(
|
||||
os.path.basename(self.path))[0] + ".png"
|
||||
thumbPath = os.path.join(
|
||||
os.path.dirname(self.path), "thumbs", thumbName)
|
||||
if not os.path.isfile(thumbPath):
|
||||
return None
|
||||
# read file
|
||||
thumbs = []
|
||||
try:
|
||||
with open(thumbPath, 'rb') as thumbFile:
|
||||
fbytes = thumbFile.read()
|
||||
with Image.open(io.BytesIO(fbytes)) as im:
|
||||
thumbFull = base64.b64encode(fbytes).decode()
|
||||
thumbs.append({
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbFull), 'data': thumbFull
|
||||
})
|
||||
# Create 32x32 thumbnail
|
||||
im.thumbnail((32, 32), Image.ANTIALIAS)
|
||||
tmpThumb = io.BytesIO()
|
||||
im.save(tmpThumb, format="PNG")
|
||||
thumbSmall = base64.b64encode(
|
||||
tmpThumb.getbuffer()).decode()
|
||||
tmpThumb.close()
|
||||
thumbs.insert(0, {
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbSmall), 'data': thumbSmall
|
||||
})
|
||||
except Exception as e:
|
||||
self.log.append(str(e))
|
||||
return None
|
||||
return thumbs
|
||||
|
||||
class Simplify3D(BaseSlicer):
|
||||
def __init__(self, name="Simplify3D", id_pattern=r"Simplify3D\(R\)"):
|
||||
super(Simplify3D, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "Simplify3D",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return self._parse_min_float(r";\s+layerHeight,.*", self.header_data)
|
||||
return _regex_find_first(
|
||||
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
return self._parse_max_float(
|
||||
r";\s+Filament\slength:.*mm", self.footer_data)
|
||||
return _regex_find_first(
|
||||
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self):
|
||||
time_matches = re.findall(
|
||||
time_match = re.search(
|
||||
r';\s+Build time:.*', self.footer_data)
|
||||
if not time_matches:
|
||||
if not time_match:
|
||||
return None
|
||||
total_time = 0
|
||||
time_match = time_matches[0]
|
||||
time_patterns = [(r"\d+\shours", 60*60), (r"\d+\smin", 60),
|
||||
(r"\d+\ssec", 1)]
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = _regex_find_ints(pattern, time_match)
|
||||
if t:
|
||||
total_time += max(t) * multiplier
|
||||
time_match = time_match.group()
|
||||
time_patterns = [(r"(\d+)\shours", 60*60), (r"(\d+)\smin", 60),
|
||||
(r"(\d+)\ssec", 1)]
|
||||
try:
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = re.search(pattern, time_match)
|
||||
if t:
|
||||
total_time += int(t.group(1)) * multiplier
|
||||
except Exception:
|
||||
return None
|
||||
return round(total_time, 2)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
def _get_temp_items(self, pattern):
|
||||
match = re.search(pattern, self.header_data)
|
||||
if match is None:
|
||||
return []
|
||||
return match.group().split(",")[1:]
|
||||
|
||||
def _get_first_layer_temp(self, heater):
|
||||
heaters = self._get_temp_items(r"temperatureName.*")
|
||||
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
|
||||
for h, temp in zip(heaters, temps):
|
||||
if h == heater:
|
||||
try:
|
||||
return float(temp)
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return self._get_first_layer_temp("Extruder 1")
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return self._get_first_layer_temp("Heated Bed")
|
||||
|
||||
class KISSlicer(BaseSlicer):
|
||||
def __init__(self, name="KISSlicer", id_pattern=r";\sKISSlicer"):
|
||||
super(KISSlicer, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r";\sKISSlicer", data)
|
||||
if match:
|
||||
ident = {'slicer': "KISSlicer"}
|
||||
vmatch = re.search(r";\sversion\s(.*)", data)
|
||||
if vmatch:
|
||||
version = vmatch.group(1).replace(" ", "-")
|
||||
ident['slicer_version'] = version
|
||||
return ident
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return self._parse_min_float(
|
||||
r";\s+first_layer_thickness_mm\s=\s\d.*", self.header_data)
|
||||
return _regex_find_first(
|
||||
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return self._parse_min_float(
|
||||
r";\s+max_layer_thickness_mm\s=\s\d.*", self.header_data)
|
||||
return _regex_find_first(
|
||||
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(
|
||||
@@ -237,18 +428,32 @@ class KISSlicer(BaseSlicer):
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
time = self._parse_max_float(
|
||||
r";\sCalculated.*Build\sTime:.*", self.footer_data)
|
||||
time = _regex_find_first(
|
||||
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
|
||||
self.footer_data)
|
||||
if time is not None:
|
||||
time *= 60
|
||||
return round(time, 2)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
return round(time, 2)
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; bed_C = (\d+\.?\d*)", self.header_data)
|
||||
|
||||
|
||||
class IdeaMaker(BaseSlicer):
|
||||
def __init__(self, name="IdeaMaker", id_pattern=r"\sideaMaker\s.*,",):
|
||||
super(IdeaMaker, self).__init__(name, id_pattern)
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"\sideaMaker\s(.*),", data)
|
||||
if match:
|
||||
return {
|
||||
'slicer': "IdeaMaker",
|
||||
'slicer_version': match.group(1)
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
layer_info = _regex_find_floats(
|
||||
@@ -266,7 +471,7 @@ class IdeaMaker(BaseSlicer):
|
||||
|
||||
def parse_object_height(self):
|
||||
bounds = _regex_find_floats(
|
||||
r";Bounding Box:.*", self.footer_data)
|
||||
r";Bounding Box:.*", self.header_data)
|
||||
if len(bounds) >= 6:
|
||||
return bounds[5]
|
||||
return None
|
||||
@@ -279,53 +484,91 @@ class IdeaMaker(BaseSlicer):
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
return self._parse_max_float(r";Print\sTime:.*", self.footer_data)
|
||||
return _regex_find_first(
|
||||
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M109 T0 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
class IceSL(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"; <IceSL.*>", data)
|
||||
if match:
|
||||
return {'slicer': "IceSL"}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
return _regex_find_first(
|
||||
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
|
||||
self.header_data, float)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
r"; z_layer_height_mm :\s+(\d+\.\d+)",
|
||||
self.header_data, float)
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(
|
||||
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
return _regex_find_first(
|
||||
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
|
||||
|
||||
|
||||
READ_SIZE = 512 * 1024
|
||||
SUPPORTED_SLICERS = [
|
||||
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
|
||||
Cura, Simplify3D, KISSlicer, IdeaMaker]
|
||||
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
|
||||
SUPPORTED_DATA = [
|
||||
'first_layer_height', 'layer_height', 'object_height',
|
||||
'filament_total', 'estimated_time', 'thumbnails']
|
||||
'filament_total', 'estimated_time', 'thumbnails',
|
||||
'first_layer_bed_temp', 'first_layer_extr_temp',
|
||||
'gcode_start_byte', 'gcode_end_byte']
|
||||
|
||||
def extract_metadata(file_path, log):
|
||||
metadata = {}
|
||||
slicers = [s() for s in SUPPORTED_SLICERS]
|
||||
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
|
||||
header_data = footer_data = slicer = None
|
||||
size = os.path.getsize(file_path)
|
||||
metadata['size'] = size
|
||||
metadata['modified'] = time.ctime(os.path.getmtime(file_path))
|
||||
metadata['modified'] = os.path.getmtime(file_path)
|
||||
with open(file_path, 'r') as f:
|
||||
# read the default size, which should be enough to
|
||||
# identify the slicer
|
||||
header_data = f.read(READ_SIZE)
|
||||
for s in slicers:
|
||||
if re.search(s.get_id_pattern(), header_data) is not None:
|
||||
ident = s.check_identity(header_data)
|
||||
if ident is not None:
|
||||
slicer = s
|
||||
metadata.update(ident)
|
||||
break
|
||||
if slicer is not None:
|
||||
metadata['slicer'] = slicer.get_name()
|
||||
if size > READ_SIZE * 2:
|
||||
f.seek(size - READ_SIZE)
|
||||
footer_data = f.read()
|
||||
elif size > READ_SIZE:
|
||||
remaining = size - READ_SIZE
|
||||
footer_data = header_data[remaining - READ_SIZE:] + f.read()
|
||||
else:
|
||||
footer_data = header_data
|
||||
slicer.set_data(header_data, footer_data, log)
|
||||
for key in SUPPORTED_DATA:
|
||||
func = getattr(slicer, "parse_" + key)
|
||||
result = func()
|
||||
if result is not None:
|
||||
metadata[key] = result
|
||||
else:
|
||||
if slicer is None:
|
||||
slicer = UnknownSlicer(file_path)
|
||||
metadata['slicer'] = "Unknown"
|
||||
if size > READ_SIZE * 2:
|
||||
f.seek(size - READ_SIZE)
|
||||
footer_data = f.read()
|
||||
elif size > READ_SIZE:
|
||||
remaining = size - READ_SIZE
|
||||
footer_data = header_data[remaining - READ_SIZE:] + f.read()
|
||||
else:
|
||||
footer_data = header_data
|
||||
slicer.set_data(header_data, footer_data, size, log)
|
||||
for key in SUPPORTED_DATA:
|
||||
func = getattr(slicer, "parse_" + key)
|
||||
result = func()
|
||||
if result is not None:
|
||||
metadata[key] = result
|
||||
return metadata
|
||||
|
||||
def main(path, filename):
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
# Raspbian/Raspberry Pi OS based distributions.
|
||||
|
||||
PYTHONDIR="${HOME}/moonraker-env"
|
||||
SYSTEMDDIR="/etc/systemd/system"
|
||||
REBUILD_ENV="n"
|
||||
FORCE_DEFAULTS="n"
|
||||
CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
|
||||
# Step 1: Verify Klipper has been installed
|
||||
check_klipper()
|
||||
@@ -16,10 +20,22 @@ check_klipper()
|
||||
|
||||
}
|
||||
|
||||
# Step 2: Install packages
|
||||
# Step 2: Clean up legacy installation
|
||||
cleanup_legacy() {
|
||||
if [ -f "/etc/init.d/moonraker" ]; then
|
||||
# Stop Moonraker Service
|
||||
echo "#### Cleanup legacy install script"
|
||||
sudo systemctl stop moonraker
|
||||
sudo update-rc.d -f moonraker remove
|
||||
sudo rm -f /etc/init.d/moonraker
|
||||
sudo rm -f /etc/default/moonraker
|
||||
fi
|
||||
}
|
||||
|
||||
# Step 3: Install packages
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-virtualenv python3-dev nginx"
|
||||
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
|
||||
|
||||
# Update system package info
|
||||
report_status "Running apt-get update..."
|
||||
@@ -30,52 +46,62 @@ install_packages()
|
||||
sudo apt-get install --yes ${PKGLIST}
|
||||
}
|
||||
|
||||
# Step 3: Create python virtual environment
|
||||
# Step 4: Create python virtual environment
|
||||
create_virtualenv()
|
||||
{
|
||||
report_status "Updating python virtual environment..."
|
||||
report_status "Installing python virtual environment..."
|
||||
|
||||
# Create virtualenv if it doesn't already exist
|
||||
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 ${PYTHONDIR}
|
||||
# If venv exists and user prompts a rebuild, then do so
|
||||
if [ -d ${PYTHONDIR} ] && [ $REBUILD_ENV = "y" ]; then
|
||||
report_status "Removing old virtualenv"
|
||||
rm -rf ${PYTHONDIR}
|
||||
fi
|
||||
|
||||
if [ ! -d ${PYTHONDIR} ]; then
|
||||
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
|
||||
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
|
||||
fi
|
||||
|
||||
# Install/update dependencies
|
||||
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
|
||||
}
|
||||
|
||||
# Step 4: Install startup script
|
||||
# Step 5: Install startup script
|
||||
install_script()
|
||||
{
|
||||
# Create systemd service file
|
||||
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
|
||||
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
report_status "Installing system start script..."
|
||||
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
|
||||
sudo update-rc.d moonraker defaults
|
||||
}
|
||||
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
|
||||
#Systemd service file for moonraker
|
||||
[Unit]
|
||||
Description=Starts Moonraker on startup
|
||||
After=network.target
|
||||
|
||||
# Step 5: Install startup script config
|
||||
install_config()
|
||||
{
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
[ -f $DEFAULTS_FILE ] && return
|
||||
|
||||
report_status "Installing system start configuration..."
|
||||
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
|
||||
# Configuration for /etc/init.d/moonraker
|
||||
|
||||
MOONRAKER_USER=$USER
|
||||
|
||||
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
|
||||
|
||||
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py"
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=$USER
|
||||
RemainAfterExit=yes
|
||||
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
EOF
|
||||
# Use systemctl to enable the klipper systemd service script
|
||||
sudo systemctl enable moonraker.service
|
||||
}
|
||||
|
||||
# Step 4: Start server
|
||||
|
||||
# Step 6: Start server
|
||||
start_software()
|
||||
{
|
||||
report_status "Launching Moonraker API Server..."
|
||||
sudo /etc/init.d/klipper stop
|
||||
sudo /etc/init.d/moonraker restart
|
||||
sudo /etc/init.d/klipper start
|
||||
sudo systemctl stop klipper
|
||||
sudo systemctl restart moonraker
|
||||
sudo systemctl start klipper
|
||||
}
|
||||
|
||||
# Helper functions
|
||||
@@ -98,11 +124,20 @@ set -e
|
||||
# Find SRCDIR from the pathname of this script
|
||||
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "rfc:" arg; do
|
||||
case $arg in
|
||||
r) REBUILD_ENV="y";;
|
||||
f) FORCE_DEFAULTS="y";;
|
||||
c) CONFIG_PATH=$OPTARG;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Run installation steps defined above
|
||||
verify_ready
|
||||
check_klipper
|
||||
cleanup_legacy
|
||||
install_packages
|
||||
create_virtualenv
|
||||
install_script
|
||||
install_config
|
||||
start_software
|
||||
@@ -1,3 +1,4 @@
|
||||
# Python dependencies for Moonraker
|
||||
tornado==6.0.4
|
||||
tornado==6.1.0
|
||||
pyserial==3.4
|
||||
pillow==8.0.1
|
||||
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
|
||||
@@ -20,6 +20,14 @@ remove_service() {
|
||||
|
||||
}
|
||||
|
||||
remove_sudo_fix() {
|
||||
echo
|
||||
echo "#### Removing sudo_fix"
|
||||
sudo gpasswd -d $USER mnrkrsudo
|
||||
sudo delgroup --only-if-empty mnrkrsudo
|
||||
sudo rm -f /etc/sudoers.d/020-sudo-for-moonraker
|
||||
}
|
||||
|
||||
remove_files() {
|
||||
# Remove API Key file from older versions
|
||||
if [ -e ~/.klippy_api_key ]; then
|
||||
@@ -61,3 +69,4 @@ verify_ready
|
||||
stop_service
|
||||
remove_service
|
||||
remove_files
|
||||
remove_sudo_fix
|
||||
@@ -0,0 +1,24 @@
|
||||
# Supplemental configuration for Moonraker's Update Manager
|
||||
# plugin. This file should not be modified.
|
||||
|
||||
[repo_info moonraker]
|
||||
origin: https://github.com/arksine/moonraker.git
|
||||
requirements: scripts/moonraker-requirements.txt
|
||||
venv_args: -p python3
|
||||
|
||||
[repo_info klipper]
|
||||
origin: https://github.com/kevinoconnor/klipper.git
|
||||
requirements: scripts/klippy-requirements.txt
|
||||
venv_args: -p python2
|
||||
|
||||
[dist_info debian moonraker]
|
||||
install_script: scripts/install-moonraker.sh
|
||||
python_dist_path: /usr/lib/python3/dist-packages
|
||||
env_package_path: lib/python3.7/site-packages
|
||||
python_dist_packages:
|
||||
gpiod
|
||||
|
||||
[dist_info debian klipper]
|
||||
install_script: scripts/install-octopi.sh
|
||||
python_dist_path: /usr/lib/python2.7/dist-packages
|
||||
env_package_path: lib/python2.7/site-packages
|
||||
@@ -0,0 +1,2 @@
|
||||
env_version=0.2.6
|
||||
deps_version=0.2.2
|
||||
Vendored
+8647
File diff suppressed because it is too large.
Load diff
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/*! jsTree - v3.3.10 - 2020-06-16 - (MIT) */
|
||||
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):"undefined"!=typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a,b){"use strict";if(!a.jstree){var c=0,d=!1,e=!1,f=!1,g=[],h=a("script:last").attr("src"),i=window.document,j=window.setImmediate,k=window.Promise;!j&&k&&(j=function(a,b){k.resolve(b).then(a)}),a.jstree={version:"3.3.10",defaults:{plugins:[]},plugins:{},path:h&&-1!==h.indexOf("/")?h.replace(/\/[^\/]+$/,""):"",idregex:/[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%?`]/g,root:"#"},a.jstree.create=function(b,d){var e=new a.jstree.core(++c),f=d;return d=a.extend(!0,{},a.jstree.defaults,d),f&&f.plugins&&(d.plugins=f.plugins),a.each(d.plugins,function(a,b){"core"!==a&&(e=e.plugin(b,d[b]))}),a(b).data("jstree",e),e.init(b,d),e},a.jstree.destroy=function(){a(".jstree:jstree").jstree("destroy"),a(i).off(".jstree")},a.jstree.core=function(a){this._id=a,this._cnt=0,this._wrk=null,this._data={core:{themes:{name:!1,dots:!1,icons:!1,ellipsis:!1},selected:[],last_error:{},working:!1,worker_queue:[],focused:null}}},a.jstree.reference=function(b){var c=null,d=null;if(!b||!b.id||b.tagName&&b.nodeType||(b=b.id),!d||!d.length)try{d=a(b)}catch(e){}if(!d||!d.length)try{d=a("#"+b.replace(a.jstree.idregex,"\\$&"))}catch(e){}return d&&d.length&&(d=d.closest(".jstree")).length&&(d=d.data("jstree"))?c=d:a(".jstree").each(function(){var d=a(this).data("jstree");return d&&d._model.data[b]?(c=d,!1):void 0}),c},a.fn.jstree=function(c){var d="string"==typeof c,e=Array.prototype.slice.call(arguments,1),f=null;return c!==!0||this.length?(this.each(function(){var g=a.jstree.reference(this),h=d&&g?g[c]:null;return f=d&&h?h.apply(g,e):null,g||d||c!==b&&!a.isPlainObject(c)||a.jstree.create(this,c),(g&&!d||c===!0)&&(f=g||!1),null!==f&&f!==b?!1:void 0}),null!==f&&f!==b?f:this):!1},a.expr.pseudos.jstree=a.expr.createPseudo(function(c){return function(c){return a(c).hasClass("jstree")&&a(c).data("jstree")!==b}}),a.jstree.defaults.core={data:!1,strings:!1,check_callback:!1,error:a.noop,animation:200,multiple:!0,themes:{name:!1,url:!1,dir:!1,dots:!0,icons:!0,ellipsis:!1,stripes:!1,variant:!1,responsive:!1},expand_selected_onload:!0,worker:!0,force_text:!1,dblclick_toggle:!0,loaded_state:!1,restore_focus:!0,keyboard:{"ctrl-space":function(b){b.type="click",a(b.currentTarget).trigger(b)},enter:function(b){b.type="click",a(b.currentTarget).trigger(b)},left:function(b){if(b.preventDefault(),this.is_open(b.currentTarget))this.close_node(b.currentTarget);else{var c=this.get_parent(b.currentTarget);c&&c.id!==a.jstree.root&&this.get_node(c,!0).children(".jstree-anchor").focus()}},up:function(a){a.preventDefault();var b=this.get_prev_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},right:function(b){if(b.preventDefault(),this.is_closed(b.currentTarget))this.open_node(b.currentTarget,function(a){this.get_node(a,!0).children(".jstree-anchor").focus()});else if(this.is_open(b.currentTarget)){var c=this.get_node(b.currentTarget,!0).children(".jstree-children")[0];c&&a(this._firstChild(c)).children(".jstree-anchor").focus()}},down:function(a){a.preventDefault();var b=this.get_next_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},"*":function(a){this.open_all()},home:function(b){b.preventDefault();var c=this._firstChild(this.get_container_ul()[0]);c&&a(c).children(".jstree-anchor").filter(":visible").focus()},end:function(a){a.preventDefault(),this.element.find(".jstree-anchor").filter(":visible").last().focus()},f2:function(a){a.preventDefault(),this.edit(a.currentTarget)}}},a.jstree.core.prototype={plugin:function(b,c){var d=a.jstree.plugins[b];return d?(this._data[b]={},d.prototype=this,new d(c,this)):this},init:function(b,c){this._model={data:{},changed:[],force_full_redraw:!1,redraw_timeout:!1,default_state:{loaded:!0,opened:!1,selected:!1,disabled:!1}},this._model.data[a.jstree.root]={id:a.jstree.root,parent:null,parents:[],children:[],children_d:[],state:{loaded:!1}},this.element=a(b).addClass("jstree jstree-"+this._id),this.settings=c,this._data.core.ready=!1,this._data.core.loaded=!1,this._data.core.rtl="rtl"===this.element.css("direction"),this.element[this._data.core.rtl?"addClass":"removeClass"]("jstree-rtl"),this.element.attr("role","tree"),this.settings.core.multiple&&this.element.attr("aria-multiselectable",!0),this.element.attr("tabindex")||this.element.attr("tabindex","0"),this.bind(),this.trigger("init"),this._data.core.original_container_html=this.element.find(" > ul > li").clone(!0),this._data.core.original_container_html.find("li").addBack().contents().filter(function(){return 3===this.nodeType&&(!this.nodeValue||/^\s+$/.test(this.nodeValue))}).remove(),this.element.html("<ul class='jstree-container-ul jstree-children' role='group'><li id='j"+this._id+"_loading' class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='presentation'><i class='jstree-icon jstree-ocl'></i><a class='jstree-anchor' role='treeitem' hLine truncated
|
||||
if(a&&"object"==typeof a.state)for(f in a.state)a.state.hasOwnProperty(f)&&(l.state[f]=a.state[f]);if(a&&"object"==typeof a.li_attr)for(f in a.li_attr)a.li_attr.hasOwnProperty(f)&&(l.li_attr[f]=a.li_attr[f]);if(l.li_attr.id&&!l.id&&(l.id=l.li_attr.id.toString()),l.id||(l.id=e),l.li_attr.id||(l.li_attr.id=l.id),a&&"object"==typeof a.a_attr)for(f in a.a_attr)a.a_attr.hasOwnProperty(f)&&(l.a_attr[f]=a.a_attr[f]);if(a&&a.children&&a.children.length){for(f=0,g=a.children.length;g>f;f++)h=this._parse_model_from_json(a.children[f],l.id,d),i=j[h],l.children.push(h),i.children_d.length&&(l.children_d=l.children_d.concat(i.children_d));l.children_d=l.children.concat(l.children_d)}return a&&a.children&&a.children===!0&&(l.state.loaded=!1,l.children=[],l.children_d=[]),delete a.data,delete a.children,l.original=a,j[l.id]=l,l.state.selected&&this._data.core.selected.push(l.id),l.id},_redraw:function(){var b=this._model.force_full_redraw?this._model.data[a.jstree.root].children.concat([]):this._model.changed.concat([]),c=i.createElement("UL"),d,e,f,g=this._data.core.focused;for(e=0,f=b.length;f>e;e++)d=this.redraw_node(b[e],!0,this._model.force_full_redraw),d&&this._model.force_full_redraw&&c.appendChild(d);this._model.force_full_redraw&&(c.className=this.get_container_ul()[0].className,c.setAttribute("role","group"),this.element.empty().append(c)),null!==g&&this.settings.core.restore_focus&&(d=this.get_node(g,!0),d&&d.length&&d.children(".jstree-anchor")[0]!==i.activeElement?d.children(".jstree-anchor").focus():this._data.core.focused=null),this._model.force_full_redraw=!1,this._model.changed=[],this.trigger("redraw",{nodes:b})},redraw:function(a){a&&(this._model.force_full_redraw=!0),this._redraw()},draw_children:function(b){var c=this.get_node(b),d=!1,e=!1,f=!1,g=i;if(!c)return!1;if(c.id===a.jstree.root)return this.redraw(!0);if(b=this.get_node(b,!0),!b||!b.length)return!1;if(b.children(".jstree-children").remove(),b=b[0],c.children.length&&c.state.loaded){for(f=g.createElement("UL"),f.setAttribute("role","group"),f.className="jstree-children",d=0,e=c.children.length;e>d;d++)f.appendChild(this.redraw_node(c.children[d],!0,!0));b.appendChild(f)}},redraw_node:function(b,c,d,e){var f=this.get_node(b),g=!1,h=!1,j=!1,k=!1,l=!1,m=!1,n="",o=i,p=this._model.data,q=!1,r=!1,s=null,t=0,u=0,v=!1,w=!1;if(!f)return!1;if(f.id===a.jstree.root)return this.redraw(!0);if(c=c||0===f.children.length,b=i.querySelector?this.element[0].querySelector("#"+(-1!=="0123456789".indexOf(f.id[0])?"\\3"+f.id[0]+" "+f.id.substr(1).replace(a.jstree.idregex,"\\$&"):f.id.replace(a.jstree.idregex,"\\$&"))):i.getElementById(f.id))b=a(b),d||(g=b.parent().parent()[0],g===this.element[0]&&(g=null),h=b.index()),c||!f.children.length||b.children(".jstree-children").length||(c=!0),c||(j=b.children(".jstree-children")[0]),q=b.children(".jstree-anchor")[0]===i.activeElement,b.remove();else if(c=!0,!d){if(g=f.parent!==a.jstree.root?a("#"+f.parent.replace(a.jstree.idregex,"\\$&"),this.element)[0]:null,!(null===g||g&&p[f.parent].state.opened))return!1;h=a.inArray(f.id,null===g?p[a.jstree.root].children:p[f.parent].children)}b=this._data.core.node.cloneNode(!0),n="jstree-node ";for(k in f.li_attr)if(f.li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"!==k?b.setAttribute(k,f.li_attr[k]):n+=f.li_attr[k]}for(f.a_attr.id||(f.a_attr.id=f.id+"_anchor"),b.setAttribute("aria-selected",!!f.state.selected),b.childNodes[1].setAttribute("aria-selected",!!f.state.selected),b.setAttribute("aria-level",f.parents.length),b.childNodes[1].setAttribute("aria-level",f.parents.length),b.setAttribute("aria-labelledby",f.a_attr.id),f.state.disabled&&(b.setAttribute("aria-disabled",!0),b.childNodes[1].setAttribute("aria-disabled",!0)),k=0,l=f.children.length;l>k;k++)if(!p[f.children[k]].state.hidden){v=!0;break}if(null!==f.parent&&p[f.parent]&&!f.state.hidden&&(k=a.inArray(f.id,p[f.parent].children),w=f.id,-1!==k))for(k++,l=p[f.parent].children.length;l>k;k++)if(p[p[f.parent].children[k]].state.hidden||(w=p[f.parent].children[k]),w!==f.id)break;f.state.hidden&&(n+=" jstree-hidden"),f.state.loading&&(n+=" jstree-loading"),f.state.loaded&&!v?n+=" jstree-leaf":(n+=f.state.opened&&f.state.loaded?" jstree-open":" jstree-closed",b.setAttribute("aria-expanded",f.state.opened&&f.state.loaded),b.childNodes[1].setAttribute("aria-expanded",f.state.opened&&f.state.loaded)),w===f.id&&(n+=" jstree-last"),b.id=f.id,b.className=n,n=(f.state.selected?" jstree-clicked":"")+(f.state.disabled?" jstree-disabled":"");for(l in f.a_attr)if(f.a_attr.hasOwnProperty(l)){if("href"===l&&"#"===f.a_attr[l])continue;"class"!==l?b.childNodes[1].setAttribute(l,f.a_attr[l]):n+=" "+f.a_attr[l]}if(n.length&&(b.childNodes[1].className="jstree-anchor "+n),(f.icon&&f.icon!==!0||f.icon===!1)&&(f.icon===!1?b.childNodes[1].childNodes[0].className+=" jstree-themeicon-hidden":-1===f.icon.indexOf("/")&&-1===f.icon.indexOf(".")?b.childNodes[1].childNodes[0].className+=" "+f.icon+" jstree-themeicon-custom":(b.childNodes[1].childNodeLine truncated
|
||||
!p)return!1;for(m=this.get_node(p),c&&c.state&&c.state.loaded===!1&&(m.state.loaded=!1),l=[],l.push(p),l=l.concat(m.children_d),this.trigger("model",{nodes:l,parent:r.id}),n=0,o=r.parents.length;o>n;n++)this._model.data[r.parents[n]].children_d=this._model.data[r.parents[n]].children_d.concat(l);for(l=[],n=0,o=r.children.length;o>n;n++)l[n>=e?n+1:n]=r.children[n];return l[e]=m.id,r.children=l,r.children_d.push(m.id),r.children_d=r.children_d.concat(m.children_d),r.id===a.jstree.root&&(this._model.force_full_redraw=!0),this._model.force_full_redraw||this._node_changed(r.id),h||this.redraw(r.id===a.jstree.root),f&&f.call(this,m,r,e),this.trigger("copy_node",{node:m,original:c,parent:r.id,position:e,old_parent:q,old_position:s&&s._id&&q&&s._model.data[q]&&s._model.data[q].children?a.inArray(c.id,s._model.data[q].children):-1,is_multi:s&&s._id&&s._id!==this._id,is_foreign:!s||!s._id,old_instance:s,new_instance:this}),m.id},cut:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="move_node",void this.trigger("cut",{node:b})):!1},copy:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="copy_node",void this.trigger("copy",{node:b})):!1},get_buffer:function(){return{mode:e,node:d,inst:f}},can_paste:function(){return e!==!1&&d!==!1},paste:function(a,b){return a=this.get_node(a),a&&e&&e.match(/^(copy_node|move_node)$/)&&d?(this[e](d,a,b,!1,!1,!1,f)&&this.trigger("paste",{parent:a.id,node:d,mode:e}),d=!1,e=!1,void(f=!1)):!1},clear_buffer:function(){d=!1,e=!1,f=!1,this.trigger("clear_buffer")},edit:function(b,c,d){var e,f,g,h,j,k,l,m,n,o=!1;return(b=this.get_node(b))?this.check("edit",b,this.get_parent(b))?(n=b,c="string"==typeof c?c:b.text,this.set_text(b,""),b=this._open_to(b),n.text=c,e=this._data.core.rtl,f=this.element.width(),this._data.core.focused=n.id,g=b.children(".jstree-anchor").focus(),h=a("<span></span>"),j=c,k=a("<div></div>",{css:{position:"absolute",top:"-200px",left:e?"0px":"-1000px",visibility:"hidden"}}).appendTo(i.body),l=a("<input />",{value:j,"class":"jstree-rename-input",css:{padding:"0",border:"1px solid silver","box-sizing":"border-box",display:"inline-block",height:this._data.core.li_height+"px",lineHeight:this._data.core.li_height+"px",width:"150px"},blur:a.proxy(function(c){c.stopImmediatePropagation(),c.preventDefault();var e=h.children(".jstree-rename-input"),f=e.val(),i=this.settings.core.force_text,m;""===f&&(f=j),k.remove(),h.replaceWith(g),h.remove(),j=i?j:a("<div></div>").append(a.parseHTML(j)).html(),b=this.get_node(b),this.set_text(b,j),m=!!this.rename_node(b,i?a("<div></div>").text(f).text():a("<div></div>").append(a.parseHTML(f)).html()),m||this.set_text(b,j),this._data.core.focused=n.id,setTimeout(a.proxy(function(){var a=this.get_node(n.id,!0);a.length&&(this._data.core.focused=n.id,a.children(".jstree-anchor").focus())},this),0),d&&d.call(this,n,m,o),l=null},this),keydown:function(a){var b=a.which;27===b&&(o=!0,this.value=j),(27===b||13===b||37===b||38===b||39===b||40===b||32===b)&&a.stopImmediatePropagation(),(27===b||13===b)&&(a.preventDefault(),this.blur())},click:function(a){a.stopImmediatePropagation()},mousedown:function(a){a.stopImmediatePropagation()},keyup:function(a){l.width(Math.min(k.text("pW"+this.value).width(),f))},keypress:function(a){return 13===a.which?!1:void 0}}),m={fontFamily:g.css("fontFamily")||"",fontSize:g.css("fontSize")||"",fontWeight:g.css("fontWeight")||"",fontStyle:g.css("fontStyle")||"",fontStretch:g.css("fontStretch")||"",fontVariant:g.css("fontVariant")||"",letterSpacing:g.css("letterSpacing")||"",wordSpacing:g.css("wordSpacing")||""},h.attr("class",g.attr("class")).append(g.contents().clone()).append(l),g.replaceWith(h),k.css(m),l.css(m).width(Math.min(k.text("pW"+l[0].value).width(),f))[0].select(),void a(i).one("mousedown.jstree touchstart.jstree dnd_start.vakata",function(b){l&&b.target!==l&&a(l).blur()})):(this.settings.core.error.call(this,this._data.core.last_error),!1):!1},set_theme:function(b,c){if(!b)return!1;if(c===!0){var d=this.settings.core.themes.dir;d||(d=a.jstree.path+"/themes"),c=d+"/"+b+"/style.css"}c&&-1===a.inArray(c,g)&&(a("head").append('<link rel="stylesheet" href="'+c+'" type="text/css" />'),g.push(c)),this._data.core.themes.name&&this.element.removeClass("jstree-"+this._data.core.themes.name),this._data.core.themes.name=b,this.element.addClass("jstree-"+b),this.element[this.settings.core.themes.responsive?"addClass":"removeClass"]("jstree-"+b+"-responsive"),this.trigger("set_theme",{theme:b})},get_theme:function(){return this._data.core.themes.name},set_theme_variant:function(a){this._data.core.themes.variant&&this.element.removeClass("jstree-"+this._data.core.theLine truncated
|
||||
item:b,reference:c.reference,element:c.element}))&&b.action?b.action.call(null,{item:b,reference:c.reference,element:c.element,position:{x:c.position_x,y:c.position_y}}):!1},_parse:function(b,d){if(!b)return!1;d||(c.html="",c.items=[]);var e="",f=!1,g;return d&&(e+="<ul>"),a.each(b,function(b,d){return d?(c.items.push(d),!f&&d.separator_before&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+"> </a></li>"),f=!1,e+="<li class='"+(d._class||"")+(d._disabled===!0||a.isFunction(d._disabled)&&d._disabled({item:d,reference:c.reference,element:c.element})?" vakata-contextmenu-disabled ":"")+"' "+(d.shortcut?" data-shortcut='"+d.shortcut+"' ":"")+">",e+="<a href='#' rel='"+(c.items.length-1)+"' "+(d.title?"title='"+d.title+"'":"")+">",a.vakata.context.settings.icons&&(e+="<i ",d.icon&&(e+=-1!==d.icon.indexOf("/")||-1!==d.icon.indexOf(".")?" style='background:url(\""+d.icon+"\") center center no-repeat' ":" class='"+d.icon+"' "),e+="></i><span class='vakata-contextmenu-sep'> </span>"),e+=(a.isFunction(d.label)?d.label({item:b,reference:c.reference,element:c.element}):d.label)+(d.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+d.shortcut+'">'+(d.shortcut_label||"")+"</span>":"")+"</a>",d.submenu&&(g=a.vakata.context._parse(d.submenu,!0),g&&(e+=g)),e+="</li>",void(d.separator_after&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+"> </a></li>",f=!0))):!0}),e=e.replace(/<li class\='vakata-context-separator'\><\/li\>$/,""),d&&(e+="</ul>"),d||(c.html=e,a.vakata.context._trigger("parse")),e.length>10?e:!1},_show_submenu:function(c){if(c=a(c),c.length&&c.children("ul").length){var d=c.children("ul"),e=c.offset().left,f=e+c.outerWidth(),g=c.offset().top,h=d.width(),i=d.height(),j=a(window).width()+a(window).scrollLeft(),k=a(window).height()+a(window).scrollTop();b?c[f-(h+10+c.outerWidth())<0?"addClass":"removeClass"]("vakata-context-left"):c[f+h>j&&e>j-f?"addClass":"removeClass"]("vakata-context-right"),g+i+10>k&&d.css("bottom","-1px"),c.hasClass("vakata-context-right")?h>e&&d.css("margin-right",e-h):h>j-f&&d.css("margin-left",j-f-h),d.show()}},show:function(d,e,f){var g,h,j,k,l,m,n,o,p=!0;switch(c.element&&c.element.length&&c.element.width(""),p){case!e&&!d:return!1;case!!e&&!!d:c.reference=d,c.position_x=e.x,c.position_y=e.y;break;case!e&&!!d:c.reference=d,g=d.offset(),c.position_x=g.left+d.outerHeight(),c.position_y=g.top;break;case!!e&&!d:c.position_x=e.x,c.position_y=e.y}d&&!f&&a(d).data("vakata_contextmenu")&&(f=a(d).data("vakata_contextmenu")),a.vakata.context._parse(f)&&c.element.html(c.html),c.items.length&&(c.element.appendTo(i.body),h=c.element,j=c.position_x,k=c.position_y,l=h.width(),m=h.height(),n=a(window).width()+a(window).scrollLeft(),o=a(window).height()+a(window).scrollTop(),b&&(j-=h.outerWidth()-a(d).outerWidth(),j<a(window).scrollLeft()+20&&(j=a(window).scrollLeft()+20)),j+l+20>n&&(j=n-(l+20)),k+m+20>o&&(k=o-(m+20)),c.element.css({left:j,top:k}).show().find("a").first().focus().parent().addClass("vakata-context-hover"),c.is_visible=!0,a.vakata.context._trigger("show"))},hide:function(){c.is_visible&&(c.element.hide().find("ul").hide().end().find(":focus").blur().end().detach(),c.is_visible=!1,a.vakata.context._trigger("hide"))}},a(function(){b="rtl"===a(i.body).css("direction");var d=!1;c.element=a("<ul class='vakata-context'></ul>"),c.element.on("mouseenter","li",function(b){b.stopImmediatePropagation(),a.contains(this,b.relatedTarget)||(d&&clearTimeout(d),c.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end(),a(this).siblings().find("ul").hide().end().end().parentsUntil(".vakata-context","li").addBack().addClass("vakata-context-hover"),a.vakata.context._show_submenu(this))}).on("mouseleave","li",function(b){a.contains(this,b.relatedTarget)||a(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover")}).on("mouseleave",function(b){a(this).find(".vakata-context-hover").removeClass("vakata-context-hover"),a.vakata.context.settings.hide_onmouseleave&&(d=setTimeout(function(b){return function(){a.vakata.context.hide()}}(this),a.vakata.context.settings.hide_onmouseleave))}).on("click","a",function(b){b.preventDefault(),a(this).blur().parent().hasClass("vakata-context-disabled")||a.vakata.context._execute(a(this).attr("rel"))===!1||a.vakata.context.hide()}).on("keydown","a",function(b){var d=null;switch(b.which){case 13:case 32:b.type="click",b.preventDefault(),a(b.currentTarget).trigger(b);break;case 37:c.is_visible&&(c.element.find(".vakata-context-hover").last().closest("li").first().find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 38:c.is_visible&&(d=c.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClaLine truncated
|
||||
e[f[h]].type=j,e[f[h]].icon===!0&&g[j].icon!==b&&(e[f[h]].icon=g[j].icon),g[j].li_attr!==b&&"object"==typeof g[j].li_attr)for(k in g[j].li_attr)if(g[j].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].li_attr[k]===b?e[f[h]].li_attr[k]=g[j].li_attr[k]:"class"===k&&(e[f[h]].li_attr["class"]=g[j].li_attr["class"]+" "+e[f[h]].li_attr["class"])}if(g[j].a_attr!==b&&"object"==typeof g[j].a_attr)for(k in g[j].a_attr)if(g[j].a_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].a_attr[k]===b?e[f[h]].a_attr[k]=g[j].a_attr[k]:"href"===k&&"#"===e[f[h]].a_attr[k]?e[f[h]].a_attr.href=g[j].a_attr.href:"class"===k&&(e[f[h]].a_attr["class"]=g[j].a_attr["class"]+" "+e[f[h]].a_attr["class"])}}e[a.jstree.root].type=a.jstree.root},this)),d.bind.call(this)},this.get_json=function(b,c,e){var f,g,h=this._model.data,i=c?a.extend(!0,{},c,{no_id:!1}):{},j=d.get_json.call(this,b,i,e);if(j===!1)return!1;if(a.isArray(j))for(f=0,g=j.length;g>f;f++)j[f].type=j[f].id&&h[j[f].id]&&h[j[f].id].type?h[j[f].id].type:"default",c&&c.no_id&&(delete j[f].id,j[f].li_attr&&j[f].li_attr.id&&delete j[f].li_attr.id,j[f].a_attr&&j[f].a_attr.id&&delete j[f].a_attr.id);else j.type=j.id&&h[j.id]&&h[j.id].type?h[j.id].type:"default",c&&c.no_id&&(j=this._delete_ids(j));return j},this._delete_ids=function(b){if(a.isArray(b)){for(var c=0,d=b.length;d>c;c++)b[c]=this._delete_ids(b[c]);return b}return delete b.id,b.li_attr&&b.li_attr.id&&delete b.li_attr.id,b.a_attr&&b.a_attr.id&&delete b.a_attr.id,b.children&&a.isArray(b.children)&&(b.children=this._delete_ids(b.children)),b},this.check=function(c,e,f,g,h){if(d.check.call(this,c,e,f,g,h)===!1)return!1;e=e&&e.id?e:this.get_node(e),f=f&&f.id?f:this.get_node(f);var i=e&&e.id?h&&h.origin?h.origin:a.jstree.reference(e.id):null,j,k,l,m;switch(i=i&&i._model&&i._model.data?i._model.data:null,c){case"create_node":case"move_node":case"copy_node":if("move_node"!==c||-1===a.inArray(e.id,f.children)){if(j=this.get_rules(f),j.max_children!==b&&-1!==j.max_children&&j.max_children===f.children.length)return this._data.core.last_error={error:"check",plugin:"types",id:"types_01",reason:"max_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(j.valid_children!==b&&-1!==j.valid_children&&-1===a.inArray(e.type||"default",j.valid_children))return this._data.core.last_error={error:"check",plugin:"types",id:"types_02",reason:"valid_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(i&&e.children_d&&e.parents){for(k=0,l=0,m=e.children_d.length;m>l;l++)k=Math.max(k,i[e.children_d[l]].parents.length);k=k-e.parents.length+1}(0>=k||k===b)&&(k=1);do{if(j.max_depth!==b&&-1!==j.max_depth&&j.max_depth<k)return this._data.core.last_error={error:"check",plugin:"types",id:"types_03",reason:"max_depth prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;f=this.get_node(f.parent),j=this.get_rules(f),k++}while(f)}}return!0},this.get_rules=function(a){if(a=this.get_node(a),!a)return!1;var c=this.get_type(a,!0);return c.max_depth===b&&(c.max_depth=-1),c.max_children===b&&(c.max_children=-1),c.valid_children===b&&(c.valid_children=-1),c},this.get_type=function(b,c){return b=this.get_node(b),b?c?a.extend({type:b.type},this.settings.types[b.type]):b.type:!1},this.set_type=function(c,d){var e=this._model.data,f,g,h,i,j,k,l,m;if(a.isArray(c)){for(c=c.slice(),g=0,h=c.length;h>g;g++)this.set_type(c[g],d);return!0}if(f=this.settings.types,c=this.get_node(c),!f[d]||!c)return!1;if(l=this.get_node(c,!0),l&&l.length&&(m=l.children(".jstree-anchor")),i=c.type,j=this.get_icon(c),c.type=d,(j===!0||!f[i]||f[i].icon!==b&&j===f[i].icon)&&this.set_icon(c,f[d].icon!==b?f[d].icon:!0),f[i]&&f[i].li_attr!==b&&"object"==typeof f[i].li_attr)for(k in f[i].li_attr)if(f[i].li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].li_attr["class"]=(e[c.id].li_attr["class"]||"").replace(f[i].li_attr[k],""),l&&l.removeClass(f[i].li_attr[k])):e[c.id].li_attr[k]===f[i].li_attr[k]&&(e[c.id].li_attr[k]=null,l&&l.removeAttr(k))}if(f[i]&&f[i].a_attr!==b&&"object"==typeof f[i].a_attr)for(k in f[i].a_attr)if(f[i].a_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].a_attr["class"]=(e[c.id].a_attr["class"]||"").replace(f[i].a_attr[k],""),m&&m.removeClass(f[i].a_attr[k])):e[c.id].a_attr[k]===f[i].a_attr[k]&&("href"===k?(e[c.id].a_attr[k]="#",m&&m.attr("href","#")):(delete e[c.id].a_attr[k],m&&m.removeAttr(k)))}if(f[d].li_attr!==b&&"object"==typeof f[d].li_attr)for(k in f[d].li_attr)if(f[d].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[c.id].li_attr[k]===b?(e[c.id].li_attr[k]=f[d].li_attr[k],l&&("class"===k?l.addClass(f[d].li_attr[k]):l.attr(k,f[d].li_attr[k]))):"class"===k&&(e[c.id].li_attr["class"]=f[d].li_attr[k]+" "+e[c.id].li_attr["class"],l&&l.addClass(f[d].li_attr[k]))}if(f[d].a_attr!==b&&"object"==typeof f[d].a_attr)for(k in f[d].a_attr)if(f[d].a_attr.hasOwnProperty(k)){if("idLine truncated
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 6.4 KiB |
+1146
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 5.5 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
+1102
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
+8
-19
@@ -1,8 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
|
||||
<script src="/js/main.js?v=0.1.18" type="module"></script>
|
||||
<script src="dist/jstree.min.js"></script>
|
||||
<script src="/js/main.js?v=0.1.2" type="module"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Klippy Web API Test</h3>
|
||||
@@ -37,27 +39,13 @@
|
||||
</form>
|
||||
<br/>
|
||||
<div style="display: flex">
|
||||
<input type="file" style="display:none" id="upload-file" />
|
||||
<div style="width: 10em">
|
||||
<button id="btnupload" class="toggleable" style="width: 9em">Upload File</button><br/><br/>
|
||||
<button id="btndownload" class="toggleable" style="width: 9em">Download File</button><br/><br/>
|
||||
<button id="btndelete" class="toggleable" style="width: 9em">Delete File</button><br/><br/>
|
||||
<button id="btngetfiles" style="width: 9em">Refresh List</button>
|
||||
<a id="hidden_link" href="#" hidden>hidden</a>
|
||||
</div>
|
||||
<div style="width: 10em">
|
||||
<button id="btnstartprint" style="width: 9em">Start Print</button><br/><br/>
|
||||
<button id="btnpauseresume" style="width: 9em">Pause Print</button><br/><br/>
|
||||
<button id="btncancelprint" style="width: 9em">Cancel Print</button><br/><br/>
|
||||
<button id="btngetmetadata" style="width: 9em">Get Metadata</button>
|
||||
</div>
|
||||
<div>
|
||||
<select id="filelist" size="8"></select>
|
||||
</div>
|
||||
<div id=filetype>
|
||||
<input type="radio" name="file_type" value="gcodes" checked="true">GCodes<br/>
|
||||
<input type="radio" name="file_type" value="config">Config Files<br/>
|
||||
<input type="radio" name="file_type" value="config_examples">Config Examples
|
||||
<a id="hidden_link" href="#" hidden>hidden</a>
|
||||
<input type="file" style="display:none" id="upload-file" />
|
||||
<div id="filelist">
|
||||
</div>
|
||||
</div>
|
||||
<br/>
|
||||
@@ -65,9 +53,10 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
|
||||
<span id="upload_progress">0%</span><br/><br/>
|
||||
<button id="btnqueryendstops" style="width: 9em">Query Endstops</button>
|
||||
<button id="btnsubscribe" style="width: 9em">Post Subscription</button>
|
||||
<button id="btngetsub" style="width: 9em">Get Subscription</button>
|
||||
<button id="btngetfiles" style="width: 9em">Get File List</button>
|
||||
<button id="btngethelp" style="width: 9em">Get Gcode Help</button>
|
||||
<button id="btngetobjs" style="width: 9em">Get Object List</button>
|
||||
<button id="btntestmesh" style="width: 9em">Get Bed Mesh</button>
|
||||
<button id="btnsendbatch" class="reqws" style="width: 9em">Test GC Batch</button>
|
||||
<button id="btnsendmacro" class="reqws" style="width: 9em">Test GC Macro</button>
|
||||
<br/><br/>
|
||||
|
||||
+717
-351
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user