Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
d59d1e5f7f | ||
|
|
28977bd579 | ||
|
|
f9b1e2922d | ||
|
|
960334d087 | ||
|
|
005caba234 | ||
|
|
2c5bb4710e | ||
|
|
bcb7e17105 | ||
|
|
304e861a28 | ||
|
|
16269c1a49 | ||
|
|
9613bb01de | ||
|
|
5b87c43535 | ||
|
|
d021eddb16 | ||
|
|
1aa12e4ff1 | ||
|
|
55919fc7d3 | ||
|
|
f338bccc3b | ||
|
|
5a6f1ae062 | ||
|
|
8b02797ede | ||
|
|
2848b4e9c1 | ||
|
|
88bbd66a3b | ||
|
|
a17e1d4056 | ||
|
|
279d53afde | ||
|
|
56bd9a61ea | ||
|
|
76493215c5 | ||
|
|
a3c0f06c5f | ||
|
|
f9f70ce989 | ||
|
|
8840434c7c | ||
|
|
6fb4cdca62 | ||
|
|
4a57dba586 | ||
|
|
291f2b0e91 | ||
|
|
43b057c40c | ||
|
|
5b6d4371c8 | ||
|
|
e9cd86f468 | ||
|
|
7cae2f4aac | ||
|
|
a7147a44ca | ||
|
|
d04a419a80 | ||
|
|
e78a2e3e41 | ||
|
|
2c332a968f | ||
|
|
b3f02a73a4 | ||
|
|
1d520310ac | ||
|
|
7cd22804dd | ||
|
|
de1a79a7ca | ||
|
|
82fbee2bc0 | ||
|
|
7441da4b57 | ||
|
|
6dc43f7e12 | ||
|
|
0775f3d0c6 | ||
|
|
e1addb16fd | ||
|
|
62e5f85473 | ||
|
|
b92000dd46 | ||
|
|
a4638f6c21 | ||
|
|
0abfc76871 | ||
|
|
470cc13b0e | ||
|
|
6b45c0c1d8 | ||
|
|
f114985dc6 | ||
|
|
52907155d2 | ||
|
|
5853f3f447 | ||
|
|
98b3c990e0 | ||
|
|
e5cb27f5b7 | ||
|
|
de462b1d0f | ||
|
|
7a94fb3a6b | ||
|
|
e2850ee77e | ||
|
|
9c76875896 | ||
|
|
d19737f4c5 | ||
|
|
d235139e6b | ||
|
|
4f97ebb28d | ||
|
|
f082d4dd44 | ||
|
|
89fa9ba47e |
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
|
||||
@@ -1,9 +1,23 @@
|
||||
# Moonraker - API Web Server for Klipper
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use interact with Klipper. Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket.
|
||||
client applications may use to interact with Klipper. Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
|
||||
is used to provide Moonraker's server functionality.
|
||||
|
||||
Moonraker depends on Tornado for its server functionality. Moonraker
|
||||
does not come bundled with a client, you will need to install one,
|
||||
such as [Mainsail](https://github.com/meteyou/mainsail).
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following web clients are currently available:
|
||||
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
|
||||
### 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) - November 19th 2020
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - November 28th 2020
|
||||
@@ -0,0 +1,278 @@
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
|
||||
### November 28th 2020
|
||||
- The following new endpoints are available when the `[update_manager]`
|
||||
section has been configured:
|
||||
- `GET /machine/update/status`
|
||||
- `POST /machine/update/moonraker`
|
||||
- `POST /machine/update/klipper`
|
||||
- `POST /machine/update/client`
|
||||
- `POST /machine/update/system`
|
||||
- The following endpoint has been added and is available as part of the
|
||||
core API:
|
||||
- `POST /machine/services/restart`
|
||||
|
||||
See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
|
||||
### November 23rd 2020
|
||||
- Moonraker now serves Klipper's "docs" directory. This can be access
|
||||
at `GET /server/files/docs/<filename>`.
|
||||
|
||||
### November 19th 2020
|
||||
- The path for the power APIs has changed from `gpio_power` to `device_power`:
|
||||
- `GET /machine/device_power/devices`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
|
||||
Returns an array of objects listing all detected devices.
|
||||
Each object in the array is guaranteed to have the following
|
||||
fields:
|
||||
- `device`: The device name
|
||||
- `status`: May be "init", "on", "off", or "error"
|
||||
- `type`: May be "gpio" or "tplink_smartplug"
|
||||
- `GET /machine/device_power/status?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
It is no longer possible to call this method with no arguments.
|
||||
Status will only be returned for the requested device, to get
|
||||
status of all devices use `/machine/device_power/devices`. As
|
||||
before, this returns an object in the format of
|
||||
`{device_name: status}`, where device_name is the name of the device
|
||||
and `status` is the devices current status.
|
||||
- `POST /machine/device_power/on?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device on. Returns the current status of the device.
|
||||
- `POST /machine/device_power/off?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device off. Returns the current status of the device.
|
||||
- The `notify_power_changed` notification now includes an object
|
||||
containing device info, matching that which would be recieved
|
||||
from a single item in `/machine/power/devices`.
|
||||
|
||||
### November 12th 2020
|
||||
- Two new fields have been added to the gcode metadata:
|
||||
- `gcode_start_byte`: Indicates the byte position in the
|
||||
file where the first "Gxx" or "Mxx" command is detected.
|
||||
- `gcode_end_byte`: Indicates the byte position in the
|
||||
file where the last "Gxx" or "Mxx" command is detected.
|
||||
These fields may be used to more accurately predict print
|
||||
progress based on the file size.
|
||||
|
||||
### November 11th 2020
|
||||
- The `server.websocket.id` API has been added. This returns a
|
||||
unique ID that Moonraker uses to track each client connection.
|
||||
As such, this API is only available over the websocket, there
|
||||
is no complementary HTTP request.
|
||||
- All HTTP API request may now include arguments in either the
|
||||
query string or in the request's body.
|
||||
- Subscriptions are now managed on a per connection basis. Each
|
||||
connection will only recieve updates for objects in which they
|
||||
are currently subscribed. If an "empty" request is sent, the
|
||||
subscription will be cancelled.
|
||||
- The `POST /printer/object/subscribe` now requires a
|
||||
`connection_id` argument. This is used to identify which
|
||||
connection's associated subscription should be updated.
|
||||
Currenlty subscriptions are only supported over the a
|
||||
websocket connection, one may use the id received from
|
||||
`server.websocket.id`.
|
||||
- The `notify_klippy_ready` websocket notification has been
|
||||
added.
|
||||
|
||||
### November 2nd 2020
|
||||
- The `GET /server/files/directory` endpoint now accepts a new
|
||||
optional argument, `extended`. If `extended=true`, then
|
||||
the data returned for gcode files will also include extracted
|
||||
metadata if it exists.
|
||||
|
||||
### October 25th 2020
|
||||
- The `modified` field reported for files and directories is no
|
||||
longer represented as a string. It is now a floating point
|
||||
value representing unix time (in seconds). This can be used
|
||||
to display the "last modified date" based on the client's
|
||||
timezone.
|
||||
|
||||
### October 21st 2020
|
||||
- The `/server/gcode_store` endpoint no longer returns a string
|
||||
in the result's `gcode_store` field. It now returns an
|
||||
Array of objects, each object containing `message` and `time`
|
||||
fields. The time refers to a timestamp in unix time (seconds),
|
||||
and may be used to determine when the gcode store received the
|
||||
accompanying `message`.
|
||||
|
||||
### September 30th 2020
|
||||
- Two new endpoints have been added:
|
||||
- `GET /server/info` (`server.info`)
|
||||
- `GET /server/gcode_store` (`server.gcode_store`)
|
||||
See web_api.md for details on their usage.
|
||||
|
||||
### September 7th 2020
|
||||
- A new websocket API has been added, `server.files.delete_file`:
|
||||
```
|
||||
{jsonrpc: "2.0", method: "server.files.delete_file", params:
|
||||
{path: "<root>/<file_name>"}, id: <request id>}
|
||||
```
|
||||
Where <root> is either "gcodes" or "config", and <file_name> is
|
||||
the relative path to the file for deletion. For example:
|
||||
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
|
||||
|
||||
|
||||
### September 3rd 2020
|
||||
- The Websocket APIs have changed for clarity. The APIs methods now
|
||||
use namespaces similar to those found in common programming languages.
|
||||
This change affects all websocket APIs, however websocket events have
|
||||
not changed. Below is a chart mapping the Previous API to the New API:
|
||||
| Previous Websocket Method | New Websocket Method |
|
||||
|---------------------------|----------------------|
|
||||
| get_printer_info | printer.info |
|
||||
| post_printer_emergency_stop | printer.emergency_stop |
|
||||
| post_printer_restart | printer.restart |
|
||||
| post_printer_firmware_restart | printer.firmware_restart |
|
||||
| get_printer_objects_list | printer.objects.list |
|
||||
| get_printer_objects_query | printer.objects.query |
|
||||
| post_printer_objects_subscribe | printer.objects.subscribe |
|
||||
| get_printer_query_endstops_status | printer.query_endstops.status |
|
||||
| post_printer_gcode_script | printer.gcode.script |
|
||||
| get_printer_gcode_help | printer.gcode.help |
|
||||
| post_printer_print_start | printer.print.start |
|
||||
| post_printer_print_pause | printer.print.pause |
|
||||
| post_printer_print_resume | printer.print.resume |
|
||||
| post_printer_print_cancel | printer.print.cancel |
|
||||
| post_machine_reboot | machine.reboot |
|
||||
| post_machine_shutdown | machine.shutdown |
|
||||
| get_server_temperature_store | server.temperature_store |
|
||||
| get_file_list | server.files.list |
|
||||
| get_file_metadata | server.files.metadata |
|
||||
| get_directory | server.files.get_directory |
|
||||
| post_directory | server.files.post_directory |
|
||||
| delete_directory | server.files.delete_directory |
|
||||
| post_file_move | server.files.move |
|
||||
| post_file_copy | server.files.copy |
|
||||
- The "power" plugin APIs have changed. This affects both HTTP and
|
||||
Websocket APIs. They were originally added to the "/printer" path,
|
||||
however this adds the possibility of a naming conflict. The new
|
||||
APIs are as follows:
|
||||
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
|
||||
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
|
||||
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
|
||||
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
|
||||
|
||||
### September 1st 2020
|
||||
- A new notification has been added: `notify_metdata_update`. This
|
||||
notification is sent when Moonraker parses metdata from a new upload.
|
||||
Note that the upload must be made via the API, files manually (using
|
||||
SAMBA, SCP, etc) do not trigger a notification. The notification is
|
||||
sent in the following format:
|
||||
```
|
||||
{jsonrpc: "2.0", method: "notify_metadata_update", params: [metadata]}
|
||||
```
|
||||
Where `metadata` is an object in the following format:
|
||||
|
||||
```json
|
||||
{
|
||||
filename: "file name",
|
||||
size: <file size>,
|
||||
modified: "last modified date",
|
||||
slicer: "Slicer Name",
|
||||
first_layer_height: <in mm>,
|
||||
layer_height: <in mm>,
|
||||
object_height: <in mm>,
|
||||
estimated_time: <time in seconds>,
|
||||
filament_total: <in mm>,
|
||||
thumbnails: [
|
||||
{
|
||||
width: <in pixels>,
|
||||
height: <in pixels>,
|
||||
size: <length of string>,
|
||||
data: <base64 string>
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### August 16th 2020
|
||||
- The structure of data returned from `/printer/info` (`get_printer_info`)
|
||||
has changed to the following format:
|
||||
```json
|
||||
{
|
||||
state: "<klippy state>",
|
||||
state_message: "<current state message>",
|
||||
hostname: "<hostname>",
|
||||
software_version: "<version>",
|
||||
cpu_info: "<cpu_info>",
|
||||
klipper_path: "<moonraker use only>",
|
||||
python_path: "<moonraker use only>",
|
||||
log_file: "<moonraker use only>",
|
||||
config_file: "<moonraker use only>",
|
||||
}
|
||||
```
|
||||
The "state" item can be one of the following:
|
||||
- "startup" - Klippy is in the process of starting up
|
||||
- "ready" - Klippy is ready
|
||||
- "shutdown" - Klippy has shutdown
|
||||
- "error" - Klippy has experienced an error during startup
|
||||
|
||||
The message from each state can be found in the `state_message`.
|
||||
- A `webhooks` printer object has been added, available for subscription or
|
||||
query. It includes the following items:
|
||||
- `state` - Printer state identical to that returned from `/printer/info`
|
||||
- `state_message` - identical to that returned from `/printer/info`
|
||||
- `/printer/objects/status` (`get_printer_objects_status`) has been renamed to
|
||||
`/printer/objects/query` (`get_printer_objects_query`). The format of the
|
||||
websocket request has changed, it should now look like the following:
|
||||
```json
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "get_printer_objects_query",
|
||||
params: {
|
||||
objects: {
|
||||
gcode: null,
|
||||
toolhead: ["position", "status"]
|
||||
}
|
||||
},
|
||||
id: <request id>
|
||||
}
|
||||
```
|
||||
As shown above, printer objects are now wrapped in an "objects" parameter.
|
||||
When a client wishes to subscribe to all items of a printer object, they
|
||||
should now be set to `null` rather than an empty array.
|
||||
The return value has also changed:
|
||||
```json
|
||||
{
|
||||
eventtime: <klippy time of update>,
|
||||
status: {
|
||||
gcode: {
|
||||
busy: true,
|
||||
gcode_position: [0, 0, 0 ,0],
|
||||
...},
|
||||
toolhead: {
|
||||
position: [0, 0, 0, 0],
|
||||
status: "Ready",
|
||||
...},
|
||||
...}
|
||||
}
|
||||
```
|
||||
The `status` item now contains the requested status.
|
||||
- `/printer/objects/subscription` (`post_printer_objects_subscription`) is now
|
||||
`printer/objects/subscribe` (`post_printer_objects_subscribe`). This
|
||||
request takes parameters in the same format as the `query`. It now returns
|
||||
state for all currently subscribed objects (in the same format as a `query`).
|
||||
This data can be used to initialize all local state after the request
|
||||
completes.
|
||||
- Subscriptions are now pushed as "diffs". Clients will only recieve updates
|
||||
for subscribed items when that data changes. This requires that clients
|
||||
initialize their local state with the data returned from the subscription
|
||||
request.
|
||||
- The structure of data returned from `/printer/objects/list` has changed. It
|
||||
now returns an array of available printer objects:
|
||||
```json
|
||||
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
|
||||
```
|
||||
- The `notify_klippy_state_changed` notification has been removed. Clients
|
||||
can subscribe to `webhooks` and use `webhooks.state` to be notified of
|
||||
transitions to the "ready" and "shutdown" states
|
||||
- A `notify_klippy_disconnected` event has been added to notify clients
|
||||
when the connection between Klippy and Moonraker has been terminated.
|
||||
This event is sent with no parameters:
|
||||
```json
|
||||
{jsonrpc: "2.0", method: "notify_klippy_disconnected"}
|
||||
```
|
||||
@@ -0,0 +1,225 @@
|
||||
This document describes Moonraker's full configuration.
|
||||
|
||||
# Primary Configuration
|
||||
The sections outlined here are required for Moonraker to function. A
|
||||
minimal functional 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
|
||||
```
|
||||
|
||||
## server
|
||||
|
||||
```
|
||||
[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:
|
||||
# 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
|
||||
|
||||
```
|
||||
[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.
|
||||
|
||||
```
|
||||
[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]
|
||||
# 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.
|
||||
|
||||
```
|
||||
[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
|
||||
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:
|
||||
```
|
||||
[power printer]
|
||||
type: gpio
|
||||
pin: gpio26
|
||||
|
||||
[power printer_led]
|
||||
type: gpio
|
||||
pin: !gpiochip0/gpio16
|
||||
|
||||
[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:
|
||||
```
|
||||
[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:
|
||||
```
|
||||
[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.
|
||||
|
||||
```
|
||||
[update_manager]
|
||||
client_repo:
|
||||
# This is the GitHub repo of the client, in the format of user/client.
|
||||
# For example, this could be set to cadriel/fluidd to update Fluidd or
|
||||
# meteyou/mainsail to update Mainsail. If this option is not set then
|
||||
# the update manager will not attempt to update a client.
|
||||
client_path:
|
||||
# The path to the client's files on disk. This cannot be a symbolic link,
|
||||
# it must be the real directory in which the client's files are located.
|
||||
# If `client_repo` is set, this parameter must be provided
|
||||
|
||||
```
|
||||
@@ -1,3 +1,59 @@
|
||||
### Moonraker Version 0.1 - August 11 2020
|
||||
- It is no longer possible to configure the subscription timer. All subscribed
|
||||
objects will update at an interval of 250ms.
|
||||
- Request timeout configuration has been removed. The server will no longer
|
||||
apply a timeout to requests. Any requests pending when Klippy disconnects
|
||||
will be aborted with an error. All pending requests are logged each minute.
|
||||
- The RESET_SD gcode is now SDCARD_RESET_FILE
|
||||
- The "virtual_sdcard" object has removed the following items:
|
||||
- "filename"
|
||||
- "total_duration"
|
||||
- "print_duration"
|
||||
- "filament_used"
|
||||
- A new object, "print_stats", has been added. It reports the following items:
|
||||
- "filename"
|
||||
- "total_duration"
|
||||
- "print_duration"
|
||||
- "filament_used"
|
||||
- "state" - can be one of the following:
|
||||
- "standby" - sd print not in progress
|
||||
- "printing" - print in progress
|
||||
- "paused" - print paused
|
||||
- "error" - print experienced an error
|
||||
- "complete" - print complete
|
||||
- "message" - contains error message when state is "error"
|
||||
- The behavior of print_stats is slightly different. When a print is finished the stats are
|
||||
not cleared. They will remain populated with the final data until the user issues a
|
||||
SDCARD_RESET_FILE gcode.
|
||||
- Moonraker Configuration has moved to moonraker.conf
|
||||
- Klippy now hosts the Unix Domain Socket. As a result, the order in which the
|
||||
Klipper and Moonraker services are started no longer matters.
|
||||
- The `notify_filelist_changed` event has been refactored for clarity. It now
|
||||
returns a result in the following format:
|
||||
```json
|
||||
{
|
||||
action: "<action>",
|
||||
item: {
|
||||
path: "<file or directory path>",
|
||||
root: "<root_name>",
|
||||
size: <file size>,
|
||||
modified: "<date modified>"
|
||||
},
|
||||
source_item: {
|
||||
path: "<file or directory path>",
|
||||
root: "<root_name>"
|
||||
}
|
||||
}
|
||||
```
|
||||
Note that the `source_item` is only present for `move_item` and `copy_item`
|
||||
actions. Below is a list of all available actions:
|
||||
- `upload_file`
|
||||
- `delete_file`
|
||||
- `create_dir`
|
||||
- `delete_dir`
|
||||
- `move_item`
|
||||
- `copy_item`
|
||||
|
||||
### Moonraker Version .08-alpha - 7/2/2020
|
||||
- Moonraker has moved to its own repo.
|
||||
- Python 3 support has been added.
|
||||
|
||||
@@ -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}}'
|
||||
+79
-191
@@ -10,31 +10,36 @@ 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.
|
||||
|
||||
Moonraker is still in alpha development, and thus some of its dependencies
|
||||
in Klipper have yet to be merged. Until this has been done it will be
|
||||
necessary to add a remote and work off a developmental branch of Klipper
|
||||
to correctly run Moonraker.
|
||||
|
||||
After Klipper is installed, you need to modify its "default" file. This file
|
||||
contains klipper's command line arguments, and you must add an argument that
|
||||
instructs Klippy to create a Unix Domain socket:
|
||||
```
|
||||
cd ~/klipper
|
||||
git remote add arksine https://github.com/Arksine/klipper.git
|
||||
sudo nano /etc/default/klipper
|
||||
```
|
||||
You should see a file that looks something like the following:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
|
||||
```
|
||||
|
||||
Now fetch and checkout:
|
||||
You need to add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
```
|
||||
git fetch arksine
|
||||
git checkout arksine/dev-moonraker-testing
|
||||
```
|
||||
Note that you are now in a detached head state and you cannot pull. Any
|
||||
time you want to update to the latest version of this branch you must
|
||||
repeat the two commands above.
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
For reference, if you want to switch back to the clone of the official repo:
|
||||
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"
|
||||
```
|
||||
git checkout master
|
||||
```
|
||||
Note that the above command is NOT part of the Moonraker install procedure.
|
||||
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).
|
||||
|
||||
You can now install the Moonraker application:
|
||||
```
|
||||
@@ -42,205 +47,88 @@ cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
If you have an older version of moonraker installed, it must be removed:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./uninstall-moonraker.sh
|
||||
```
|
||||
|
||||
Finally, run moonraker's install script:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
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:\
|
||||
`Moonraker: server connection detected`
|
||||
`webhooks: New connection established`
|
||||
|
||||
Currently Moonraker is responsible for creating the Unix Domain Socket,
|
||||
so so it must be started first for Klippy to connect. In any instance
|
||||
where Klipper was started first simply restart the klipper service.
|
||||
```
|
||||
sudo service klipper restart
|
||||
```
|
||||
After the connection is established Klippy will register API endpoints and
|
||||
send configuration to the server. Once the initial configuration is sent
|
||||
to Moonraker its configuration will be retained when Klippy disconnects
|
||||
(either through a restart or by stopping the service), and updated when
|
||||
Klippy reconnects.
|
||||
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.
|
||||
|
||||
# Configuration
|
||||
The host, port, log file location, socket file location and api key file
|
||||
are all specified via command arguments:
|
||||
## Command line Usage
|
||||
The configuration and log file paths may be specified via the command
|
||||
line.
|
||||
```
|
||||
usage: moonraker.py [-h] [-a <address>] [-p <port>] [-s <socketfile>]
|
||||
[-l <logfile>] [-k <apikeyfile>]
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
-a <address>, --address <address>
|
||||
host name or ip to bind to the Web Server
|
||||
-p <port>, --port <port>
|
||||
port the Web Server will listen on
|
||||
-s <socketfile>, --socketfile <socketfile>
|
||||
file name and location for the Unix Domain Socket
|
||||
-c <configfile>, --configfile <configfile>
|
||||
Location of moonraker configuration file
|
||||
-l <logfile>, --logfile <logfile>
|
||||
log file name and location
|
||||
-k <apikeyfile>, --apikey <apikeyfile>
|
||||
API Key file location
|
||||
```
|
||||
|
||||
The default configuration is:
|
||||
- address = 0.0.0.0 (Bind to all interfaces)
|
||||
- port = 7125
|
||||
- socketfile = /tmp/moonraker
|
||||
- logfile = /tmp/moonraker.log
|
||||
- apikeyfile = ~/.moonraker_api_key
|
||||
- config file - `~/moonraker.conf`
|
||||
- log file - `/tmp/moonraker.log`
|
||||
|
||||
It is recommended to use the defaults, however one may change these
|
||||
arguments by editing `/etc/default/moonraker`.
|
||||
|
||||
All other configuration is sent to the server via Klippy, thus it is done in
|
||||
printer.cfg. A basic configuration that authorizes clients on a range from
|
||||
192.168.1.1 - 192.168.1.254 is as follows:
|
||||
```
|
||||
[moonraker]
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
```
|
||||
## Prerequisites (Klipper Configuration)
|
||||
|
||||
Below is a detailed explanation of all options currently available:
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
- [virtual_sdcard]
|
||||
- [pause_resume]
|
||||
- [display_status]
|
||||
|
||||
If you have a `filament_switch_sensor` configured then `pause_resume` will
|
||||
automatically be loaded. Likewise, if you have a `display` configured then
|
||||
`display_status` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to printer.cfg:
|
||||
```
|
||||
#[moonraker]
|
||||
#require_auth: True
|
||||
# Enables Authorization. When set to true, only trusted clients and
|
||||
# requests with an API key are accepted.
|
||||
#enable_cors: False
|
||||
# Enables CORS support. If serving static files from a different http
|
||||
# server then CORS will need to be enabled.
|
||||
#trusted_clients:
|
||||
# A list of new line separated ip addresses and/or ip ranges that are trusted.
|
||||
# Trusted clients are given full access to the API. Both IPv4 and IPv6
|
||||
# addresses and ranges are supported. Ranges must be expressed in CIDR
|
||||
# notation (see http://ip.sb/cidr for more info). For example an entry of
|
||||
# 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
|
||||
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
|
||||
# of the ip address must be 0.
|
||||
# The default is no clients or ranges are trusted.
|
||||
#request_timeout: 5.
|
||||
# The amount of time (in seconds) a client request has to process before the
|
||||
# server returns an error. This timeout does NOT apply to gcode requests.
|
||||
# Default is 5 seconds.
|
||||
#long_running_gcodes:
|
||||
# BED_MESH_CALIBRATE, 120.
|
||||
# M104, 200.
|
||||
# A list of gcodes that will be assigned their own timeout. The list should
|
||||
# be in the format presented above, where the first item is the gcode name
|
||||
# and the second item is the timeout (in seconds). Each pair should be
|
||||
# separated by a newline. The default is an empty list where no gcodes have
|
||||
# a unique timeout.
|
||||
#long_running_requests:
|
||||
# gcode/script, 60.
|
||||
# pause_resume/pause, 60.
|
||||
# pause_resume/resume, 60.
|
||||
# pause_resume/cancel, 60.
|
||||
# A list of requests that will be assigned their own timeout. The list
|
||||
# should be formatted in the same manner as long_running_gcodes. The
|
||||
# default is matches the example shown above.
|
||||
#status_tier_1:
|
||||
# toolhead
|
||||
# gcode
|
||||
#status_tier_2:
|
||||
# fan
|
||||
#status_tier_3:
|
||||
# extruder
|
||||
# virtual_sdcard
|
||||
# Subscription Configuration. By default items in tier 1 are polled every
|
||||
# 250 ms, tier 2 every 500 ms, tier 3 every 1s, tier 4 every 2s, tier
|
||||
# 5 every 4s, tier 6 every 8s.
|
||||
#tick_time: .25
|
||||
# This is the base interval used for status tier 1. All other status tiers
|
||||
# are calculated using the value defined by tick_time (See below for more
|
||||
# information). Default is 250ms.
|
||||
#config_include_path: ~/klipper_config
|
||||
# The path of a directory in which "included" configuration files reside.
|
||||
# If specified, moonraker will serve this path allowing file and directory
|
||||
# manipuation within it. Note that this should not be the same directory
|
||||
# in which printer.cfg is located (the home directory for most installations).
|
||||
# The default is None, in which no included config files will be served.
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
```
|
||||
NOTES:
|
||||
- While Klipper does not set any hard limits on the location of the
|
||||
`path` option for the `virtual_sdcard`, Moonraker requires that the path
|
||||
be located within the HOME directory, it cannot however be the HOME
|
||||
directory. If you wish to host your files elsewhere, use a symlink.
|
||||
- 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.
|
||||
|
||||
The "status tiers" are used to determine how fast each klippy object is allowed
|
||||
to be polled. Each tier is calculated using the `tick_time` option. There are
|
||||
6 tiers, `tier_1 = tick_time` (.25s), `tier_2 = tick_time*2` (.5s),
|
||||
`tier_3 = tick_time*4` (1s), `tier_4 = tick_time*8` (2s),
|
||||
`tier_5 = tick_time*16` (4s), and `tier_6 = tick_time*16` (8s). This method
|
||||
was chosen to provide some flexibility for slower hosts while making it easy to
|
||||
batch subscription updates together.
|
||||
|
||||
## Plugin Configuration
|
||||
The core plugins are configured via the primary configuration above. Optional
|
||||
plugins each need their own configuration as outlined below.
|
||||
|
||||
### PanelDue Plugin
|
||||
|
||||
```
|
||||
[moonraker_plugin paneldue]
|
||||
serial: /dev/ttyAMA0
|
||||
baud: 57600
|
||||
machine_name: Voron 2
|
||||
macros:
|
||||
LOAD_FILAMENT
|
||||
UNLOAD_FILAMENT
|
||||
PREHEAT_CHAMBER
|
||||
TURN_OFF_MOTORS
|
||||
TURN_OFF_HEATERS
|
||||
PANELDUE_BEEP FREQUENCY=500 DURATION=1
|
||||
```
|
||||
|
||||
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:
|
||||
```
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
# Beep duration in seconds
|
||||
default_parameter_DURATION: 1.
|
||||
gcode:
|
||||
{ printer.moonraker.action_call_remote_method(
|
||||
"paneldue_beep", frequency=FREQUENCY|int,
|
||||
duration=DURATION|float) }
|
||||
```
|
||||
|
||||
### Power Control Plugin
|
||||
```
|
||||
[moonraker_plugin power]
|
||||
devices: printer, led
|
||||
# A comma separated list of devices you wish to control. Do not use spaces in
|
||||
# the device's name here
|
||||
#{dev}_name: Friendly Name
|
||||
# This is the friendly name for the device. {dev} must be swapped for the name
|
||||
# of the device used under devices, as an example:
|
||||
# printer_name: My Printer
|
||||
{dev}_pin: 23
|
||||
# This option is required.
|
||||
# The GPIO Pin number you wish to control
|
||||
#{dev}_active_low: False
|
||||
# If you have a device that needs a low or 0 signal to be turned on, set this
|
||||
# option to True.
|
||||
```
|
||||
|
||||
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,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,34 @@
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
|
||||
### 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.
|
||||
+700
-138
File diff suppressed because it is too large.
Load diff
+135
-142
@@ -9,42 +9,47 @@ 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", "moonraker/get_configuration"
|
||||
"list_endpoints", "gcode/subscribe_output",
|
||||
"register_remote_method"
|
||||
]
|
||||
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
|
||||
# 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(',')
|
||||
args[key] = parsed
|
||||
return args
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
val = request_handler.get_argument(key)
|
||||
if not val:
|
||||
args[key] = None
|
||||
else:
|
||||
args[key] = val.split(',')
|
||||
logging.debug(f"Parsed Arguments: {args}")
|
||||
return {'objects': args}
|
||||
|
||||
# Built-in Query String Parser
|
||||
def _default_parser(request):
|
||||
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):
|
||||
@@ -77,113 +82,118 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
try:
|
||||
self.rules.remove(rule)
|
||||
except Exception:
|
||||
logging.exception("Unable to remove rule: %s" % (pattern))
|
||||
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
|
||||
self.parser = parser
|
||||
|
||||
class MoonrakerApp:
|
||||
def __init__(self, server, args):
|
||||
self.server = server
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.tornado_server = None
|
||||
self.api_cache = {}
|
||||
self.registered_base_handlers = []
|
||||
self.max_upload_size = config.getint('max_upload_size', 200)
|
||||
self.max_upload_size *= 1024 * 1024
|
||||
|
||||
# Set Up Websocket and Authorization Managers
|
||||
self.wsm = WebsocketManager(server)
|
||||
self.auth = Authorization(args.apikey)
|
||||
self.wsm = WebsocketManager(self.server)
|
||||
self.auth = Authorization(config['authorization'])
|
||||
|
||||
mimetypes.add_type('text/plain', '.log')
|
||||
mimetypes.add_type('text/plain', '.gcode')
|
||||
mimetypes.add_type('text/plain', '.cfg')
|
||||
debug = config.getboolean('enable_debug_logging', True)
|
||||
|
||||
# Set up HTTP only requests
|
||||
self.mutable_router = MutableRouter(self)
|
||||
app_handlers = [
|
||||
(AnyMatches(), self.mutable_router),
|
||||
(r"/websocket", WebSocket,
|
||||
{'wsm': self.wsm, 'auth': self.auth}),
|
||||
(r"/api/version", EmulateOctoprintHandler,
|
||||
{'server': server, 'auth': self.auth})]
|
||||
(r"/websocket", WebSocket),
|
||||
(r"/api/version", EmulateOctoprintHandler)]
|
||||
|
||||
self.app = tornado.web.Application(
|
||||
app_handlers,
|
||||
serve_traceback=args.debug,
|
||||
serve_traceback=debug,
|
||||
websocket_ping_interval=10,
|
||||
websocket_ping_timeout=30,
|
||||
enable_cors=False)
|
||||
parent=self)
|
||||
self.get_handler_delegate = self.app.get_handler_delegate
|
||||
|
||||
# Register handlers
|
||||
self.register_static_file_handler("moonraker.log", args.logfile)
|
||||
logfile = config['system_args'].get('logfile')
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
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 load_config(self, config):
|
||||
if 'enable_cors' in config:
|
||||
self.app.settings['enable_cors'] = config['enable_cors']
|
||||
self.auth.load_config(config)
|
||||
|
||||
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("Registering remote endpoint: (%s) %s" % (
|
||||
" ".join(api_def.request_methods), api_def.uri))
|
||||
self.wsm.register_handler(api_def)
|
||||
logging.info(
|
||||
f"Registering remote endpoint - "
|
||||
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
|
||||
f"Websocket: {', '.join(api_def.ws_methods)}")
|
||||
self.wsm.register_remote_handler(api_def)
|
||||
params = {}
|
||||
params['server'] = self.server
|
||||
params['auth'] = self.auth
|
||||
params['methods'] = api_def.request_methods
|
||||
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("Registering local endpoint: (%s) %s" % (
|
||||
" ".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):
|
||||
@@ -193,19 +203,14 @@ class MoonrakerApp:
|
||||
pattern += "/"
|
||||
pattern += "(.*)"
|
||||
else:
|
||||
logging.info("Invalid file path: %s" % (file_path))
|
||||
logging.info(f"Invalid file path: {file_path}")
|
||||
return
|
||||
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}
|
||||
logging.debug(f"Registering static file: ({pattern}) {file_path}")
|
||||
params = {'path': file_path}
|
||||
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
|
||||
|
||||
def register_upload_handler(self, pattern):
|
||||
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)
|
||||
@@ -213,62 +218,72 @@ 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,
|
||||
methods, 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.methods = methods
|
||||
self.query_parser = arg_parser
|
||||
|
||||
async def get(self):
|
||||
if 'GET' in self.methods:
|
||||
await self._process_http_request('GET')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
await self._process_http_request()
|
||||
|
||||
async def post(self):
|
||||
if 'POST' in self.methods:
|
||||
await self._process_http_request('POST')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
await self._process_http_request()
|
||||
|
||||
async def _process_http_request(self, method):
|
||||
args = {}
|
||||
if self.request.query:
|
||||
args = self.query_parser(self.request)
|
||||
request = self.server.make_request(
|
||||
self.remote_callback, method, args)
|
||||
result = await request.wait()
|
||||
if isinstance(result, ServerError):
|
||||
async def _process_http_request(self):
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.server.make_request(
|
||||
WebRequest(self.remote_callback, args, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
result.status_code, str(result))
|
||||
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
|
||||
@@ -292,63 +307,41 @@ 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))
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
|
||||
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
|
||||
# a file
|
||||
basename = os.path.basename(self.absolute_path)
|
||||
self.set_header(
|
||||
"Content-Disposition", "attachment; filename=%s" % (basename))
|
||||
"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)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
file_manager.notify_filelist_changed(filename, 'removed', 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:
|
||||
|
||||
+128
-91
@@ -8,104 +8,104 @@ import uuid
|
||||
import os
|
||||
import time
|
||||
import ipaddress
|
||||
import re
|
||||
import logging
|
||||
import tornado
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from utils import ServerError
|
||||
|
||||
TOKEN_TIMEOUT = 5
|
||||
CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300 * 1000
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, api_key_file):
|
||||
self.api_key_loc = os.path.expanduser(api_key_file)
|
||||
def __init__(self, config):
|
||||
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
|
||||
self.api_key_file = os.path.expanduser(api_key_file)
|
||||
self.api_key = self._read_api_key()
|
||||
self.auth_enabled = True
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
self.auth_enabled = config.getboolean('enabled', True)
|
||||
self.trusted_connections = {}
|
||||
self.access_tokens = {}
|
||||
|
||||
# Get allowed cors domains
|
||||
cors_cfg = config.get('cors_domains', "").strip()
|
||||
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
|
||||
for d in cors_cfg.split('\n')if d.strip()]
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
trusted_clients = config.get('trusted_clients', "")
|
||||
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
|
||||
if c.strip()]
|
||||
for ip in trusted_clients:
|
||||
# Check IP address
|
||||
try:
|
||||
tc = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
tc = None
|
||||
if tc is None:
|
||||
# Check ip network
|
||||
try:
|
||||
tc = ipaddress.ip_network(ip)
|
||||
except ValueError:
|
||||
raise ServerError(
|
||||
f"Invalid option in trusted_clients: {ip}")
|
||||
self.trusted_ranges.append(tc)
|
||||
else:
|
||||
self.trusted_ips.append(tc)
|
||||
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges])
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Auth Enabled: {self.auth_enabled}\n"
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
self.prune_handler.start()
|
||||
|
||||
def load_config(self, config):
|
||||
self.auth_enabled = config.get("require_auth", self.auth_enabled)
|
||||
# reset trusted ips
|
||||
self.trusted_ips = []
|
||||
trusted_ips = config.get("trusted_ips", [])
|
||||
for ip in trusted_ips:
|
||||
try:
|
||||
ip_addr = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
logging.info("IP address <%s> invalid" % (ip))
|
||||
continue
|
||||
self.trusted_ips.append(ip_addr)
|
||||
# reset trusted ranges
|
||||
self.trusted_ranges = []
|
||||
trusted_ranges = config.get("trusted_ranges", [])
|
||||
for ip_range in trusted_ranges:
|
||||
try:
|
||||
ip_net = ipaddress.ip_network(ip_range)
|
||||
except ValueError:
|
||||
logging.info("IP range <%s> invalid" % (ip_range))
|
||||
continue
|
||||
self.trusted_ranges.append(ip_net)
|
||||
self._reset_trusted_connections()
|
||||
t_clients = [str(ip) for ip in self.trusted_ips] + \
|
||||
[str(rng) for rng in self.trusted_ranges]
|
||||
logging.info(
|
||||
"Authorization Configuration Loaded\n"
|
||||
"Auth Enabled: %s\n"
|
||||
"Trusted Clients:\n%s" %
|
||||
(self.auth_enabled, "\n".join(t_clients)))
|
||||
|
||||
def register_handlers(self, app):
|
||||
# Register Authorization Endpoints
|
||||
app.register_local_handler(
|
||||
"/access/api_key", None, ['GET', 'POST'],
|
||||
self._handle_apikey_request, http_only=True)
|
||||
"/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):
|
||||
if os.path.exists(self.api_key_loc):
|
||||
with open(self.api_key_loc, 'r') as f:
|
||||
if os.path.exists(self.api_key_file):
|
||||
with open(self.api_key_file, 'r') as f:
|
||||
api_key = f.read()
|
||||
return api_key
|
||||
# API Key file doesn't exist. Generate
|
||||
# a new api key and create the file.
|
||||
logging.info(
|
||||
"No API Key file found, creating new one at:\n%s"
|
||||
% (self.api_key_loc))
|
||||
f"No API Key file found, creating new one at:"
|
||||
f"\n{self.api_key_file}")
|
||||
return self._create_api_key()
|
||||
|
||||
def _create_api_key(self):
|
||||
api_key = uuid.uuid4().hex
|
||||
with open(self.api_key_loc, 'w') as f:
|
||||
with open(self.api_key_file, 'w') as f:
|
||||
f.write(api_key)
|
||||
return api_key
|
||||
|
||||
def _reset_trusted_connections(self):
|
||||
valid_conns = {}
|
||||
for ip, access_time in self.trusted_connections.items():
|
||||
if self._check_authorized_ip(ip):
|
||||
valid_conns[ip] = access_time
|
||||
else:
|
||||
logging.info(
|
||||
"Connection [%s] no longer trusted, removing" % (ip))
|
||||
self.trusted_connections = valid_conns
|
||||
|
||||
def _check_authorized_ip(self, ip):
|
||||
if ip in self.trusted_ips:
|
||||
return True
|
||||
@@ -123,7 +123,7 @@ class Authorization:
|
||||
for ip in expired_conns:
|
||||
self.trusted_connections.pop(ip, None)
|
||||
logging.info(
|
||||
"Trusted Connection Expired, IP: %s" % (ip))
|
||||
f"Trusted Connection Expired, IP: {ip}")
|
||||
|
||||
def _token_expire_handler(self, token):
|
||||
self.access_tokens.pop(token, None)
|
||||
@@ -145,7 +145,7 @@ class Authorization:
|
||||
return True
|
||||
elif self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
"Trusted Connection Detected, IP: %s" % (ip))
|
||||
f"Trusted Connection Detected, IP: {ip}")
|
||||
self.trusted_connections[ip] = time.time()
|
||||
return True
|
||||
return False
|
||||
@@ -168,7 +168,7 @@ class Authorization:
|
||||
ip = ipaddress.ip_address(request.remote_ip)
|
||||
except ValueError:
|
||||
logging.exception(
|
||||
"Unable to Create IP Address %s" % (request.remote_ip))
|
||||
f"Unable to Create IP Address {request.remote_ip}")
|
||||
ip = None
|
||||
if self._check_trusted_connection(ip):
|
||||
return True
|
||||
@@ -184,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:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# Configuration Helper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import configparser
|
||||
import os
|
||||
import logging
|
||||
|
||||
class ConfigError(Exception):
|
||||
pass
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class ConfigHelper:
|
||||
error = ConfigError
|
||||
def __init__(self, server, config, section):
|
||||
self.server = server
|
||||
self.config = config
|
||||
self.section = section
|
||||
self.sections = config.sections
|
||||
self.has_section = config.has_section
|
||||
|
||||
def get_server(self):
|
||||
return self.server
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.getsection(key)
|
||||
|
||||
def __contains__(self, key):
|
||||
return key in self.config
|
||||
|
||||
def get_name(self):
|
||||
return self.section
|
||||
|
||||
def get_prefix_sections(self, prefix):
|
||||
return [s for s in self.sections() if s.startswith(prefix)]
|
||||
|
||||
def getsection(self, section):
|
||||
if section not in self.config:
|
||||
raise ConfigError(f"No section [{section}] in config")
|
||||
return ConfigHelper(self.server, self.config, section)
|
||||
|
||||
def _get_option(self, func, option, default):
|
||||
try:
|
||||
val = func(option, default)
|
||||
except Exception:
|
||||
raise ConfigError(
|
||||
f"Error parsing option ({option}) from "
|
||||
f"section [{self.section}]")
|
||||
if val == Sentinel:
|
||||
raise ConfigError(
|
||||
f"No option found ({option}) in section [{self.section}]")
|
||||
return val
|
||||
|
||||
def get(self, option, default=Sentinel):
|
||||
return self._get_option(
|
||||
self.config[self.section].get, option, default)
|
||||
|
||||
def getint(self, option, default=Sentinel):
|
||||
return self._get_option(
|
||||
self.config[self.section].getint, option, default)
|
||||
|
||||
def getboolean(self, option, default=Sentinel):
|
||||
return self._get_option(
|
||||
self.config[self.section].getboolean, option, default)
|
||||
|
||||
def getfloat(self, option, default=Sentinel):
|
||||
return self._get_item(
|
||||
self.config[self.section].getfloat, option, default)
|
||||
|
||||
def get_configuration(server, system_args):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(
|
||||
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)
|
||||
try:
|
||||
config.read(cfg_file_path)
|
||||
except Exception:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from None
|
||||
|
||||
try:
|
||||
server_cfg = config['server']
|
||||
except KeyError:
|
||||
raise ConfigError("No section [server] in config")
|
||||
|
||||
if server_cfg.get('enable_debug_logging', True):
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
|
||||
config['system_args'] = {
|
||||
'logfile': system_args.logfile,
|
||||
'software_version': system_args.software_version}
|
||||
return ConfigHelper(server, config, 'server')
|
||||
+441
-325
@@ -11,21 +11,23 @@ import time
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
import errno
|
||||
import tornado
|
||||
import tornado.netutil
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
import confighelper
|
||||
import utils
|
||||
import asyncio
|
||||
from tornado import iostream, gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.util import TimeoutError
|
||||
from tornado.locks import Event
|
||||
from app import MoonrakerApp
|
||||
from utils import ServerError, MoonrakerLoggingHandler
|
||||
from utils import ServerError
|
||||
|
||||
INIT_MS = 1000
|
||||
INIT_TIME = .25
|
||||
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
|
||||
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
|
||||
CORE_PLUGINS = [
|
||||
'file_manager', 'gcode_apis', 'machine',
|
||||
'temperature_store', 'shell_command']
|
||||
'file_manager', 'klippy_apis', 'machine',
|
||||
'data_store', 'shell_command']
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
@@ -33,96 +35,112 @@ class Sentinel:
|
||||
class Server:
|
||||
error = ServerError
|
||||
def __init__(self, args):
|
||||
self.host = args.address
|
||||
self.port = args.port
|
||||
|
||||
# Options configurable by Klippy
|
||||
self.request_timeout = 5.
|
||||
self.long_running_gcodes = {}
|
||||
self.long_running_requests = {}
|
||||
config = confighelper.get_configuration(self, args)
|
||||
self.host = config.get('host', "0.0.0.0")
|
||||
self.port = config.getint('port', 7125)
|
||||
|
||||
# Event initialization
|
||||
self.events = {}
|
||||
|
||||
# Klippy Connection Handling
|
||||
socketfile = os.path.normpath(os.path.expanduser(args.socketfile))
|
||||
self.klippy_server_sock = tornado.netutil.bind_unix_socket(
|
||||
socketfile, backlog=1)
|
||||
self.remove_server_sock = tornado.netutil.add_accept_handler(
|
||||
self.klippy_server_sock, self._handle_klippy_connection)
|
||||
self.klippy_sock = None
|
||||
self.is_klippy_connected = False
|
||||
self.is_klippy_ready = False
|
||||
self.server_configured = False
|
||||
self.partial_data = b""
|
||||
self.klippy_address = config.get(
|
||||
'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"
|
||||
self.subscriptions = {}
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
self.moonraker_app = app = MoonrakerApp(self, args)
|
||||
self.io_loop = IOLoop.current()
|
||||
self.init_cb = PeriodicCallback(self._initialize, INIT_MS)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
self.moonraker_app = app = MoonrakerApp(config)
|
||||
self.register_endpoint = app.register_local_handler
|
||||
self.register_static_file_handler = app.register_static_file_handler
|
||||
self.register_upload_handler = app.register_upload_handler
|
||||
self.ioloop = IOLoop.current()
|
||||
|
||||
for plugin in CORE_PLUGINS:
|
||||
self.load_plugin(plugin)
|
||||
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(
|
||||
'set_klippy_shutdown', self._set_klippy_shutdown)
|
||||
'process_gcode_response', self._process_gcode_response,
|
||||
need_klippy_reg=False)
|
||||
self.register_remote_method(
|
||||
'response', self._handle_klippy_response)
|
||||
self.register_remote_method(
|
||||
'process_gcode_response', self._process_gcode_response)
|
||||
self.register_remote_method(
|
||||
'process_status_update', self._process_status_update)
|
||||
'process_status_update', self._process_status_update,
|
||||
need_klippy_reg=False)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
|
||||
self._load_plugins(config)
|
||||
|
||||
def start(self):
|
||||
hostname, hostport = self.get_host_info()
|
||||
logging.info(
|
||||
"Starting Moonraker on (%s, %d)" %
|
||||
(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)
|
||||
|
||||
# ***** Plugin Management *****
|
||||
def load_plugin(self, plugin_name, default=Sentinel):
|
||||
def _load_plugins(self, config):
|
||||
# load core plugins
|
||||
for plugin in CORE_PLUGINS:
|
||||
self.load_plugin(config, plugin)
|
||||
|
||||
# check for optional plugins
|
||||
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, None)
|
||||
|
||||
def load_plugin(self, config, plugin_name, default=Sentinel):
|
||||
if plugin_name in self.plugins:
|
||||
return self.plugins[plugin_name]
|
||||
# Make sure plugin exists
|
||||
mod_path = os.path.join(
|
||||
os.path.dirname(__file__), 'plugins', plugin_name + '.py')
|
||||
if not os.path.exists(mod_path):
|
||||
msg = "Plugin (%s) does not exist" % (plugin_name)
|
||||
msg = f"Plugin ({plugin_name}) does not exist"
|
||||
logging.info(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
module = importlib.import_module("plugins." + plugin_name)
|
||||
try:
|
||||
load_func = getattr(module, "load_plugin")
|
||||
plugin = load_func(self)
|
||||
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 = "Unable to load plugin (%s)" % (plugin_name)
|
||||
logging.info(msg)
|
||||
msg = f"Unable to load plugin ({plugin_name})"
|
||||
logging.exception(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
self.plugins[plugin_name] = plugin
|
||||
logging.info("Plugin (%s) loaded" % (plugin_name))
|
||||
logging.info(f"Plugin ({plugin_name}) loaded")
|
||||
return plugin
|
||||
|
||||
def lookup_plugin(self, plugin_name, default=Sentinel):
|
||||
plugin = self.plugins.get(plugin_name, default)
|
||||
if plugin == Sentinel:
|
||||
raise ServerError("Plugin (%s) not found" % (plugin_name))
|
||||
raise ServerError(f"Plugin ({plugin_name}) not found")
|
||||
return plugin
|
||||
|
||||
def register_event_handler(self, event, callback):
|
||||
@@ -131,280 +149,385 @@ class Server:
|
||||
def send_event(self, event, *args):
|
||||
events = self.events.get(event, [])
|
||||
for evt in events:
|
||||
self.io_loop.spawn_callback(evt, *args)
|
||||
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("Remote method (%s) already registered"
|
||||
% (method_name))
|
||||
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 *****
|
||||
def _handle_klippy_connection(self, conn, addr):
|
||||
if self.is_klippy_connected:
|
||||
logging.info("New Connection received while Klippy Connected")
|
||||
self.close_client_sock()
|
||||
logging.info("Klippy Connection Established")
|
||||
self.is_klippy_connected = True
|
||||
conn.setblocking(0)
|
||||
self.klippy_sock = conn
|
||||
self.io_loop.add_handler(
|
||||
self.klippy_sock.fileno(), self._handle_klippy_data,
|
||||
IOLoop.READ | IOLoop.ERROR)
|
||||
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)
|
||||
return
|
||||
# begin server iniialization
|
||||
self.init_cb.start()
|
||||
self.ioloop.spawn_callback(self._initialize)
|
||||
|
||||
def _handle_klippy_data(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
self.close_client_sock()
|
||||
def process_command(self, cmd):
|
||||
method = cmd.get('method', None)
|
||||
if method is not None:
|
||||
# This is a remote method called from klippy
|
||||
if method in self.remote_methods:
|
||||
params = cmd.get('params', {})
|
||||
self.ioloop.spawn_callback(
|
||||
self._execute_method, method, **params)
|
||||
else:
|
||||
logging.info(f"Unknown method received: {method}")
|
||||
return
|
||||
# This is a response to a request, process
|
||||
req_id = cmd.get('id', None)
|
||||
request = self.pending_requests.pop(req_id, None)
|
||||
if request is None:
|
||||
logging.info(
|
||||
f"No request matching request ID: {req_id}, "
|
||||
f"response: {cmd}")
|
||||
return
|
||||
if 'result' in cmd:
|
||||
result = cmd['result']
|
||||
if not result:
|
||||
result = "ok"
|
||||
else:
|
||||
err = cmd.get('error', "Malformed Klippy Response")
|
||||
result = ServerError(err, 400)
|
||||
request.notify(result)
|
||||
|
||||
async def _execute_method(self, method_name, **kwargs):
|
||||
try:
|
||||
data = self.klippy_sock.recv(4096)
|
||||
except socket.error as e:
|
||||
# If bad file descriptor allow connection to be
|
||||
# closed by the data check
|
||||
if e.errno == errno.EBADF:
|
||||
data = b''
|
||||
else:
|
||||
return
|
||||
if data == b'':
|
||||
# Socket Closed
|
||||
self.close_client_sock()
|
||||
return
|
||||
commands = data.split(b'\x03')
|
||||
commands[0] = self.partial_data + commands[0]
|
||||
self.partial_data = commands.pop()
|
||||
for cmd in commands:
|
||||
try:
|
||||
decoded_cmd = json.loads(cmd)
|
||||
method = decoded_cmd.get('method')
|
||||
params = decoded_cmd.get('params', {})
|
||||
cb = self.remote_methods.get(method)
|
||||
if cb is not None:
|
||||
cb(**params)
|
||||
else:
|
||||
logging.info("Unknown command received %s" % cmd.decode())
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Error processing Klippy Host Response: %s"
|
||||
% (cmd.decode()))
|
||||
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 klippy_send(self, data):
|
||||
# TODO: need a mutex or lock to make sure that multiple co-routines
|
||||
# do not attempt to send
|
||||
if not self.is_klippy_connected:
|
||||
return False
|
||||
retries = 10
|
||||
data = json.dumps(data).encode() + b"\x03"
|
||||
while data:
|
||||
try:
|
||||
sent = self.klippy_sock.send(data)
|
||||
except socket.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE \
|
||||
or not retries:
|
||||
sent = 0
|
||||
else:
|
||||
# XXX - Should pause for 1ms here
|
||||
retries -= 1
|
||||
continue
|
||||
retries = 10
|
||||
if sent > 0:
|
||||
data = data[sent:]
|
||||
else:
|
||||
logging.info("Error sending client data, closing socket")
|
||||
self.close_client_sock()
|
||||
return False
|
||||
return True
|
||||
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")
|
||||
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()
|
||||
if not self.server_configured:
|
||||
await self._request_config()
|
||||
if not self.is_klippy_ready:
|
||||
await self._request_ready()
|
||||
if self.is_klippy_ready and self.server_configured:
|
||||
# Make sure we have all registered endpoints
|
||||
await self._request_endpoints()
|
||||
self.init_cb.stop()
|
||||
# Subscribe to "webhooks"
|
||||
# Register "webhooks" subscription
|
||||
if "webhooks_sub" not in self.init_list:
|
||||
try:
|
||||
await self.klippy_apis.subscribe_objects({'webhooks': None})
|
||||
except ServerError as e:
|
||||
logging.info(f"{e}\nUnable to subscribe to webhooks object")
|
||||
else:
|
||||
logging.info("Webhooks Subscribed")
|
||||
self.init_list.append("webhooks_sub")
|
||||
# Subscribe to Gcode Output
|
||||
if "gcode_output_sub" not in self.init_list:
|
||||
try:
|
||||
await self.klippy_apis.subscribe_gcode_output()
|
||||
except ServerError as e:
|
||||
logging.info(
|
||||
f"{e}\nUnable to register gcode output subscription")
|
||||
else:
|
||||
logging.info("GCode Output Subscribed")
|
||||
self.init_list.append("gcode_output_sub")
|
||||
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.init_handle = self.ioloop.call_later(
|
||||
INIT_TIME, self._initialize)
|
||||
|
||||
async def _request_endpoints(self):
|
||||
request = self.make_request("list_endpoints", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
endpoints = result.get('hooks', {})
|
||||
static_paths = result.get('static_paths', {})
|
||||
for ep in endpoints:
|
||||
self.moonraker_app.register_remote_handler(ep)
|
||||
for sp in static_paths:
|
||||
self.moonraker_app.register_static_file_handler(
|
||||
sp['resource_id'], sp['file_path'])
|
||||
result = await self.klippy_apis.list_endpoints(default=None)
|
||||
if result is None:
|
||||
return
|
||||
endpoints = result.get('endpoints', {})
|
||||
for ep in endpoints:
|
||||
self.moonraker_app.register_remote_handler(ep)
|
||||
|
||||
async def _request_config(self):
|
||||
request = self.make_request(
|
||||
"moonraker/get_configuration", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
self._load_config(result)
|
||||
self.server_configured = True
|
||||
else:
|
||||
async def _check_ready(self):
|
||||
send_id = "identified" not in self.init_list
|
||||
try:
|
||||
result = await self.klippy_apis.get_klippy_info(send_id)
|
||||
except ServerError as e:
|
||||
if self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
|
||||
self.init_attempts <= MAX_LOG_ATTEMPTS:
|
||||
logging.info(
|
||||
f"{e}\nKlippy info request error. This indicates that\n"
|
||||
f"Klippy may have experienced an error during startup.\n"
|
||||
f"Please check klippy.log for more information")
|
||||
return
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
self.klippy_info = dict(result)
|
||||
self.klippy_state = result.get('state', "unknown")
|
||||
if self.klippy_state == "ready":
|
||||
await self._verify_klippy_requirements()
|
||||
logging.info("Klippy 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:
|
||||
msg = result.get('state_message', "Klippy Not Ready")
|
||||
logging.info("\n" + msg)
|
||||
|
||||
async def _verify_klippy_requirements(self):
|
||||
result = await self.klippy_apis.get_object_list(default=None)
|
||||
if result is None:
|
||||
logging.info(
|
||||
"Error receiving configuration. This indicates a "
|
||||
"potential configuration issue in printer.cfg. Please check "
|
||||
"klippy.log for more information")
|
||||
|
||||
async def _request_ready(self):
|
||||
request = self.make_request("info", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
is_ready = result.get("is_ready", False)
|
||||
if is_ready:
|
||||
self._set_klippy_ready()
|
||||
f"Unable to retreive Klipper Object List")
|
||||
return
|
||||
req_objs = set(["virtual_sdcard", "display_status", "pause_resume"])
|
||||
missing_objs = req_objs - set(result)
|
||||
if missing_objs:
|
||||
err_str = ", ".join([f"[{o}]" for o in missing_objs])
|
||||
logging.info(
|
||||
f"\nWarning, unable to detect the following printer "
|
||||
f"objects:\n{err_str}\nPlease add the the above sections "
|
||||
f"to printer.cfg for full Moonraker functionality.")
|
||||
if "virtual_sdcard" not in missing_objs:
|
||||
# Update the gcode path
|
||||
result = await self.klippy_apis.query_objects(
|
||||
{'configfile': None}, default=None)
|
||||
if result is None:
|
||||
logging.info(f"Unable to set SD Card path")
|
||||
else:
|
||||
msg = result.get("message", "Klippy Not Ready")
|
||||
logging.info(msg)
|
||||
else:
|
||||
logging.info(
|
||||
"Klippy Info request error. This indicates a that Klippy "
|
||||
"may have experienced an error during startup. Please check "
|
||||
"klippy.log for more information")
|
||||
|
||||
def _load_config(self, config):
|
||||
self.request_timeout = config.get(
|
||||
'request_timeout', self.request_timeout)
|
||||
self.long_running_gcodes = config.get(
|
||||
'long_running_gcodes', self.long_running_gcodes)
|
||||
self.long_running_requests = config.get(
|
||||
'long_running_requests', self.long_running_requests)
|
||||
self.moonraker_app.load_config(config)
|
||||
# load config for core plugins
|
||||
for plugin_name in CORE_PLUGINS:
|
||||
plugin = self.plugins[plugin_name]
|
||||
if hasattr(plugin, "load_config"):
|
||||
plugin.load_config(config)
|
||||
# Load and apply optional plugin Configuration
|
||||
plugin_cfgs = {name[7:]: cfg for name, cfg in config.items()
|
||||
if name.startswith("plugin_")}
|
||||
for name, cfg in plugin_cfgs.items():
|
||||
plugin = self.plugins.get(name)
|
||||
if plugin is None:
|
||||
plugin = self.load_plugin(name, None)
|
||||
if hasattr(plugin, "load_config"):
|
||||
plugin.load_config(cfg)
|
||||
# Remove plugins that are loaded but no longer configured
|
||||
valid_plugins = CORE_PLUGINS + list(plugin_cfgs.keys())
|
||||
self.io_loop.spawn_callback(self._prune_plugins, valid_plugins)
|
||||
|
||||
async def _prune_plugins(self, valid_plugins):
|
||||
for name, plugin in self.plugins.items():
|
||||
if name not in valid_plugins:
|
||||
if hasattr(plugin, "close"):
|
||||
await plugin.close()
|
||||
self.plugins.pop(name, None)
|
||||
|
||||
def _handle_klippy_response(self, request_id, response):
|
||||
req = self.pending_requests.pop(request_id, None)
|
||||
if req is not None:
|
||||
if isinstance(response, dict) and 'error' in response:
|
||||
response = ServerError(response['message'], 400)
|
||||
req.notify(response)
|
||||
else:
|
||||
logging.info("No request matching response: " + str(response))
|
||||
|
||||
def _set_klippy_ready(self):
|
||||
logging.info("Klippy ready")
|
||||
self.is_klippy_ready = True
|
||||
self.send_event("server:klippy_state_changed", "ready")
|
||||
|
||||
def _set_klippy_shutdown(self):
|
||||
logging.info("Klippy has shutdown")
|
||||
self.is_klippy_ready = False
|
||||
self.send_event("server:klippy_state_changed", "shutdown")
|
||||
config = result.get('configfile', {}).get('config', {})
|
||||
vsd_config = config.get('virtual_sdcard', {})
|
||||
vsd_path = vsd_config.get('path', None)
|
||||
if vsd_path is not None:
|
||||
file_manager = self.lookup_plugin('file_manager')
|
||||
file_manager.register_directory('gcodes', vsd_path)
|
||||
else:
|
||||
logging.info(
|
||||
"Configuration for [virtual_sdcard] not found,"
|
||||
" unable to set SD Card path")
|
||||
|
||||
def _process_gcode_response(self, response):
|
||||
self.send_event("server:gcode_response", response)
|
||||
|
||||
def _process_status_update(self, status):
|
||||
self.send_event("server:status_update", status)
|
||||
def _process_status_update(self, eventtime, status):
|
||||
if 'webhooks' in status:
|
||||
# XXX - process other states (startup, ready, error, etc)?
|
||||
state = status['webhooks'].get('state', None)
|
||||
if state is not None:
|
||||
if state == "shutdown":
|
||||
logging.info("Klippy has shutdown")
|
||||
self.send_event("server:klippy_shutdown")
|
||||
self.klippy_state = state
|
||||
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)
|
||||
|
||||
def make_request(self, path, method, args):
|
||||
timeout = self.long_running_requests.get(path, self.request_timeout)
|
||||
async def make_request(self, web_request):
|
||||
rpc_method = web_request.get_endpoint()
|
||||
if rpc_method == "objects/subscribe":
|
||||
return await self._request_subscripton(web_request)
|
||||
else:
|
||||
return await self._request_standard(web_request)
|
||||
|
||||
if path == "gcode/script":
|
||||
script = args.get('script', "")
|
||||
base_gc = script.strip().split()[0].upper()
|
||||
timeout = self.long_running_gcodes.get(base_gc, timeout)
|
||||
async def _request_subscripton(self, web_request):
|
||||
args = web_request.get_args()
|
||||
conn = web_request.get_connection()
|
||||
|
||||
base_request = BaseRequest(path, method, args, timeout)
|
||||
# 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:
|
||||
all_subs[obj] = None
|
||||
else:
|
||||
uitems = list(set(pi) | set(items))
|
||||
all_subs[obj] = uitems
|
||||
else:
|
||||
all_subs[obj] = items
|
||||
args['objects'] = all_subs
|
||||
args['response_template'] = {'method': "process_status_update"}
|
||||
|
||||
result = await self._request_standard(web_request)
|
||||
|
||||
# prune the status response
|
||||
pruned_status = {}
|
||||
all_status = result['status']
|
||||
sub = self.subscriptions.get(conn, {})
|
||||
for obj, fields in all_status.items():
|
||||
if obj in sub:
|
||||
valid_fields = sub[obj]
|
||||
if valid_fields is None:
|
||||
pruned_status[obj] = fields
|
||||
else:
|
||||
pruned_status[obj] = {k: v for k, v in fields.items()
|
||||
if k in valid_fields}
|
||||
result['status'] = pruned_status
|
||||
return result
|
||||
|
||||
async def _request_standard(self, web_request):
|
||||
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
|
||||
ret = self.klippy_send(base_request.to_dict())
|
||||
if not ret:
|
||||
self.pending_requests.pop(base_request.id, None)
|
||||
base_request.notify(
|
||||
ServerError("Klippy Host not connected", 503))
|
||||
return base_request
|
||||
self.ioloop.spawn_callback(
|
||||
self.klippy_connection.send_request, base_request)
|
||||
return await base_request.wait()
|
||||
|
||||
async def _kill_server(self):
|
||||
# XXX - Currently this function is not used.
|
||||
# Should I expose functionality to shutdown
|
||||
# or restart the server, or simply remove this?
|
||||
logging.info(
|
||||
"Shutting Down Webserver")
|
||||
for plugin in self.plugins:
|
||||
def remove_subscription(self, conn):
|
||||
self.subscriptions.pop(conn, None)
|
||||
|
||||
async def _stop_server(self):
|
||||
self.server_running = False
|
||||
for name, plugin in self.plugins.items():
|
||||
if hasattr(plugin, "close"):
|
||||
await plugin.close()
|
||||
self.close_client_sock()
|
||||
self.close_server_sock()
|
||||
if self.server_running:
|
||||
self.server_running = False
|
||||
await self.moonraker_app.close()
|
||||
self.io_loop.stop()
|
||||
ret = plugin.close()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.klippy_connection.close()
|
||||
while self.klippy_state != "disconnected":
|
||||
await gen.sleep(.1)
|
||||
await self.moonraker_app.close()
|
||||
self.ioloop.stop()
|
||||
|
||||
def close_client_sock(self):
|
||||
self.is_klippy_ready = False
|
||||
self.server_configured = False
|
||||
self.init_cb.stop()
|
||||
if self.is_klippy_connected:
|
||||
self.is_klippy_connected = False
|
||||
logging.info("Klippy Connection Removed")
|
||||
try:
|
||||
self.io_loop.remove_handler(self.klippy_sock.fileno())
|
||||
self.klippy_sock.close()
|
||||
except socket.error:
|
||||
logging.exception("Error Closing Client Socket")
|
||||
self.send_event("server:klippy_state_changed", "disconnect")
|
||||
async def _handle_server_restart(self, web_request):
|
||||
self.ioloop.spawn_callback(self._stop_server)
|
||||
return "ok"
|
||||
|
||||
def close_server_sock(self):
|
||||
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):
|
||||
self.ioloop = IOLoop.current()
|
||||
self.iostream = None
|
||||
self.on_recd = on_recd
|
||||
self.on_close = on_close
|
||||
|
||||
async def connect(self, address):
|
||||
ksock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
kstream = iostream.IOStream(ksock)
|
||||
try:
|
||||
self.remove_server_sock()
|
||||
self.klippy_server_sock.close()
|
||||
# XXX - remove server sock file (or use abstract?)
|
||||
except Exception:
|
||||
logging.exception("Error Closing Server Socket")
|
||||
await kstream.connect(address)
|
||||
except iostream.StreamClosedError:
|
||||
return False
|
||||
logging.info("Klippy Connection Established")
|
||||
self.iostream = kstream
|
||||
self.iostream.set_close_callback(self.on_close)
|
||||
self.ioloop.spawn_callback(self._read_stream, self.iostream)
|
||||
return True
|
||||
|
||||
async def _read_stream(self, stream):
|
||||
while not stream.closed():
|
||||
try:
|
||||
data = await stream.read_until(b'\x03')
|
||||
except iostream.StreamClosedError as e:
|
||||
return
|
||||
except Exception:
|
||||
logging.exception("Klippy Stream Read Error")
|
||||
continue
|
||||
try:
|
||||
decoded_cmd = json.loads(data[:-1])
|
||||
self.on_recd(decoded_cmd)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error processing Klippy Host Response: {data.decode()}")
|
||||
|
||||
async def send_request(self, request):
|
||||
if self.iostream is None:
|
||||
request.notify(ServerError("Klippy Host not connected", 503))
|
||||
return
|
||||
data = json.dumps(request.to_dict()).encode() + b"\x03"
|
||||
try:
|
||||
await self.iostream.write(data)
|
||||
except iostream.StreamClosedError:
|
||||
request.notify(ServerError("Klippy Host not connected", 503))
|
||||
|
||||
def is_connected(self):
|
||||
return self.iostream is not None and not self.iostream.closed()
|
||||
|
||||
def close(self):
|
||||
if self.iostream is not None and \
|
||||
not self.iostream.closed():
|
||||
self.iostream.close()
|
||||
|
||||
# Basic WebRequest class, easily converted to dict for json encoding
|
||||
class BaseRequest:
|
||||
def __init__(self, path, method, args, timeout=None):
|
||||
def __init__(self, rpc_method, params):
|
||||
self.id = id(self)
|
||||
self.path = path
|
||||
self.method = method
|
||||
self.args = args
|
||||
self._timeout = timeout
|
||||
self.rpc_method = rpc_method
|
||||
self.params = params
|
||||
self._event = Event()
|
||||
self.response = None
|
||||
if timeout is not None:
|
||||
self._timeout = time.time() + timeout
|
||||
|
||||
async def wait(self):
|
||||
# Wait for klippy to process the request or until the timeout
|
||||
# has been reached.
|
||||
try:
|
||||
await self._event.wait(timeout=self._timeout)
|
||||
except TimeoutError:
|
||||
logging.info("Request '%s' Timed Out" %
|
||||
(self.method + " " + self.path))
|
||||
return ServerError("Klippy Request Timed Out", 500)
|
||||
# Log pending requests every 60 seconds
|
||||
start_time = time.time()
|
||||
while True:
|
||||
timeout = time.time() + 60.
|
||||
try:
|
||||
await self._event.wait(timeout=timeout)
|
||||
except TimeoutError:
|
||||
pending_time = time.time() - start_time
|
||||
logging.info(
|
||||
f"Request '{self.rpc_method}' pending: "
|
||||
f"{pending_time:.2f} seconds")
|
||||
self._event.clear()
|
||||
continue
|
||||
break
|
||||
if isinstance(self.response, ServerError):
|
||||
raise self.response
|
||||
return self.response
|
||||
|
||||
def notify(self, response):
|
||||
@@ -412,69 +535,62 @@ class BaseRequest:
|
||||
self._event.set()
|
||||
|
||||
def to_dict(self):
|
||||
return {'id': self.id, 'path': self.path,
|
||||
'method': self.method, 'args': self.args}
|
||||
return {'id': self.id, 'method': self.rpc_method,
|
||||
'params': self.params}
|
||||
|
||||
def main():
|
||||
# Parse start arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Moonraker - Klipper API Server")
|
||||
parser.add_argument(
|
||||
"-a", "--address", default='0.0.0.0', metavar='<address>',
|
||||
help="host name or ip to bind to the Web Server")
|
||||
parser.add_argument(
|
||||
"-p", "--port", type=int, default=7125, metavar='<port>',
|
||||
help="port the Web Server will listen on")
|
||||
parser.add_argument(
|
||||
"-s", "--socketfile", default="/tmp/moonraker", metavar='<socketfile>',
|
||||
help="file name and location for the Unix Domain Socket")
|
||||
"-c", "--configfile", default="~/moonraker.conf",
|
||||
metavar='<configfile>',
|
||||
help="Location of moonraker configuration file")
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
parser.add_argument(
|
||||
"-k", "--apikey", default="~/.moonraker_api_key",
|
||||
metavar='<apikeyfile>', help="API Key file location")
|
||||
parser.add_argument(
|
||||
"-d", "--debug", action='store_true',
|
||||
help="Enable Debug Logging")
|
||||
cmd_line_args = parser.parse_args()
|
||||
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
|
||||
root_logger = logging.getLogger()
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
log_file, when='midnight', backupCount=2)
|
||||
root_logger.addHandler(file_hdlr)
|
||||
if cmd_line_args.debug:
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
root_logger.setLevel(logging.INFO)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
version = utils.get_software_version()
|
||||
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 = "Moonraker requires Python 3.7 or above. Detected Version: %s" \
|
||||
% (sys.version)
|
||||
msg = f"Moonraker requires Python 3.7 or above. " \
|
||||
f"Detected Version: {sys.version}"
|
||||
logging.info(msg)
|
||||
print(msg)
|
||||
ql.stop()
|
||||
exit(1)
|
||||
|
||||
# Start IOLoop and Server
|
||||
io_loop = IOLoop.current()
|
||||
try:
|
||||
server = Server(cmd_line_args)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
return
|
||||
try:
|
||||
server.start()
|
||||
io_loop.start()
|
||||
except Exception:
|
||||
logging.exception("Server Running Error")
|
||||
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:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
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)
|
||||
@@ -24,36 +28,37 @@ class TemperatureStore:
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_state_changed", self._init_sensors)
|
||||
"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, state):
|
||||
if state != "ready":
|
||||
return
|
||||
|
||||
async def _init_sensors(self):
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
# Fetch sensors
|
||||
request = self.server.make_request(
|
||||
"objects/status", 'GET', {'heaters': []})
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
logging.info("Error Configuring Sensors: %s" % (str(result)))
|
||||
try:
|
||||
result = await klippy_apis.query_objects({'heaters': None})
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error Configuring Sensors: {e}")
|
||||
return
|
||||
sensors = result.get("heaters", {}).get("available_sensors", [])
|
||||
|
||||
if sensors:
|
||||
# Add Subscription
|
||||
sub = {s: [] for s in sensors}
|
||||
request = self.server.make_request(
|
||||
"objects/subscription", 'POST', sub)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
logging.info("Error subscribing to sensors: %s" %(str(result)))
|
||||
sub = {s: None for s in sensors}
|
||||
try:
|
||||
status = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to sensors: {e}")
|
||||
return
|
||||
logging.info("Configuring available sensors: %s" % (str(sensors)))
|
||||
logging.info(f"Configuring available sensors: {sensors}")
|
||||
new_store = {}
|
||||
for sensor in sensors:
|
||||
if sensor in self.temperature_store:
|
||||
@@ -62,11 +67,15 @@ class TemperatureStore:
|
||||
new_store[sensor] = {
|
||||
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
|
||||
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
|
||||
if sensor not in self.last_temps:
|
||||
self.last_temps[sensor] = (0., 0.)
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
if sensor not in self.temperature_store:
|
||||
del self.last_temps[sensor]
|
||||
# Update initial temperatures
|
||||
self._set_current_temps(status)
|
||||
self.temp_update_cb.start()
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
@@ -77,10 +86,10 @@ class TemperatureStore:
|
||||
def _set_current_temps(self, data):
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
last_temp, last_target = self.last_temps[sensor]
|
||||
self.last_temps[sensor] = (
|
||||
round(data[sensor].get('temperature', 0.), 2),
|
||||
data[sensor].get('target', 0.))
|
||||
|
||||
round(data[sensor].get('temperature', last_temp), 2),
|
||||
data[sensor].get('target', last_target))
|
||||
|
||||
def _update_temperature_store(self):
|
||||
# XXX - If klippy is not connected, set values to zero
|
||||
@@ -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 load_plugin(server):
|
||||
return TemperatureStore(server)
|
||||
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 DataStore(config)
|
||||
+442
-255
@@ -6,308 +6,285 @@
|
||||
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, server):
|
||||
self.server = server
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.file_paths = {}
|
||||
self.file_lists = {}
|
||||
self.gcode_metadata = {}
|
||||
self.metadata_lock = Lock()
|
||||
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")
|
||||
|
||||
def load_config(self, config):
|
||||
# Gcode Files
|
||||
sd = config.get('sd_path', None)
|
||||
if sd is not None:
|
||||
sd = os.path.normpath(os.path.expanduser(sd))
|
||||
if sd != self.file_paths.get('gcodes', ""):
|
||||
self.file_paths['gcodes'] = sd
|
||||
self.server.register_static_file_handler(
|
||||
'/server/files/gcodes/', sd, can_delete=True,
|
||||
op_check_cb=self._handle_operation_check)
|
||||
try:
|
||||
self._update_file_list()
|
||||
except Exception:
|
||||
logging.exception("Unable to initialize gcode file list")
|
||||
# Configuration files in the optional config path
|
||||
cfg_path = config.get('printer_config_path', None)
|
||||
if cfg_path is not None:
|
||||
cfg_path = os.path.normpath(os.path.expanduser(cfg_path))
|
||||
if cfg_path != self.file_paths.get('config', ""):
|
||||
self.file_paths['config'] = cfg_path
|
||||
self.server.register_static_file_handler(
|
||||
"/server/files/config/", cfg_path,
|
||||
can_delete=True)
|
||||
try:
|
||||
self._update_file_list(base='config')
|
||||
except Exception:
|
||||
logging.exception("Unable to initialize config file list")
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", 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)
|
||||
if not ret:
|
||||
raise config.error(
|
||||
"Option 'config_path' is not a valid directory")
|
||||
|
||||
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 = paths
|
||||
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
|
||||
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
|
||||
|
||||
# Register path for example configs
|
||||
klipper_path = config.get('klipper_path', None)
|
||||
klipper_path = paths.get('klipper_path', None)
|
||||
if klipper_path is not None:
|
||||
example_cfg_path = os.path.join(klipper_path, "config")
|
||||
if example_cfg_path != self.file_paths.get("config_examples", ""):
|
||||
self.file_paths['config_examples'] = example_cfg_path
|
||||
self.server.register_static_file_handler(
|
||||
"/server/files/config_examples/", example_cfg_path)
|
||||
try:
|
||||
self._update_file_list(base='config_examples')
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Unable to initialize config_examples file list")
|
||||
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, 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:
|
||||
logging.info(
|
||||
f"\nSupplied path ({path}) for ({root}) not valid. Please\n"
|
||||
"check that the path exists and is a subfolder in the HOME\n"
|
||||
"directory. Note that the path may not BE the home directory.")
|
||||
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):
|
||||
return self.file_paths.get('gcodes', "")
|
||||
|
||||
async def _handle_filelist_request(self, path, method, args):
|
||||
root = args.get('root', "gcodes")
|
||||
return self.get_file_list(format_list=True, base=root)
|
||||
def get_fixed_path_args(self):
|
||||
return dict(self.fixed_path_args)
|
||||
|
||||
async def _handle_metadata_request(self, path, method, args):
|
||||
requested_file = args.get('filename')
|
||||
metadata = self.gcode_metadata.get(requested_file)
|
||||
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, 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(
|
||||
"Metadata not available for <%s>" % (requested_file), 404)
|
||||
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(url_path, "add_directory", 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(
|
||||
"Directory does not exist (%s)" % (directory))
|
||||
force = args.get('force', False)
|
||||
if isinstance(force, str):
|
||||
force = force.lower() == "true"
|
||||
f"Directory does not exist ({directory})")
|
||||
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(url_path, "delete_directory", base)
|
||||
self.notify_filelist_changed("delete_dir", rel_path, root)
|
||||
else:
|
||||
raise self.server.error("Operation Not Supported", 405)
|
||||
return "ok"
|
||||
|
||||
async def _handle_operation_check(self, requested_path):
|
||||
# Get virtual_sdcard status
|
||||
request = self.server.make_request(
|
||||
"objects/status", 'GET', {'virtual_sdcard': []})
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise result
|
||||
vsd = result.get('virtual_sdcard', {})
|
||||
loaded_file = vsd.get('filename', "")
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
result = await klippy_apis.query_objects({'print_stats': None})
|
||||
pstats = result.get('print_stats', {})
|
||||
loaded_file = pstats.get('filename', "")
|
||||
state = pstats.get('state', "")
|
||||
gc_path = self.file_paths.get('gcodes', "")
|
||||
full_path = os.path.join(gc_path, loaded_file)
|
||||
if os.path.isdir(requested_path):
|
||||
# Check to see of the loaded file is in the reques
|
||||
if full_path.startswith(requested_path):
|
||||
if loaded_file and state != "complete":
|
||||
if os.path.isdir(requested_path):
|
||||
# Check to see of the loaded file is in the request
|
||||
if full_path.startswith(requested_path):
|
||||
raise self.server.error("File currently in use", 403)
|
||||
elif full_path == requested_path:
|
||||
raise self.server.error("File currently in use", 403)
|
||||
elif full_path == requested_path:
|
||||
raise self.server.error("File currently in use", 403)
|
||||
ongoing = vsd.get('total_duration', 0.) > 0.
|
||||
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("Invalid path: " % (url_path))
|
||||
base = parts[0]
|
||||
if base not in self.file_paths:
|
||||
raise self.server.error("Invalid base path (%s)" % (base))
|
||||
root_path = local_path = self.file_paths[base]
|
||||
url_path = ""
|
||||
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(
|
||||
"Destination path is read-only: %s" % (dest_base))
|
||||
f"Destination path is read-only: {dest_root}")
|
||||
if not os.path.exists(source_path):
|
||||
raise self.server.error("File %s does not exist" % (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 = ""
|
||||
if path == "/server/files/move":
|
||||
if source_base not in FULL_ACCESS_ROOTS:
|
||||
action = op_result = ""
|
||||
if ep == "/server/files/move":
|
||||
if source_root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
"Source path is read-only, cannot move: %s"
|
||||
% (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:
|
||||
shutil.move(source_path, dest_path)
|
||||
op_result = shutil.move(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
action = "file_move"
|
||||
elif path == "/server/files/copy":
|
||||
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 ep == "/server/files/copy":
|
||||
try:
|
||||
if os.path.isdir(source_path):
|
||||
shutil.copytree(source_path, dest_path)
|
||||
op_result = shutil.copytree(source_path, dest_path)
|
||||
else:
|
||||
shutil.copy2(source_path, dest_path)
|
||||
op_result = shutil.copy2(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
action = "file_copy"
|
||||
action = "copy_item"
|
||||
if op_result != dest_path:
|
||||
dst_rel_path = os.path.join(
|
||||
dst_rel_path, os.path.basename(op_result))
|
||||
self.notify_filelist_changed(
|
||||
dst_url_path, action, dest_base,
|
||||
{'prev_file': src_url_path, 'prev_root': source_base})
|
||||
action, dst_rel_path, dest_root,
|
||||
{'path': src_rel_path, 'root': source_root})
|
||||
return "ok"
|
||||
|
||||
def _list_directory(self, path):
|
||||
if not os.path.isdir(path):
|
||||
raise self.server.error(
|
||||
"Directory does not exist (%s)" % (path))
|
||||
f"Directory does not exist ({path})")
|
||||
flist = {'dirs': [], 'files': []}
|
||||
for fname in os.listdir(path):
|
||||
full_path = os.path.join(path, fname)
|
||||
modified = time.ctime(os.path.getmtime(full_path))
|
||||
path_info = self._get_path_info(full_path)
|
||||
if os.path.isdir(full_path):
|
||||
flist['dirs'].append({
|
||||
'dirname': fname,
|
||||
'modified': modified
|
||||
})
|
||||
path_info['dirname'] = fname
|
||||
flist['dirs'].append(path_info)
|
||||
elif os.path.isfile(full_path):
|
||||
size = os.path.getsize(full_path)
|
||||
flist['files'].append(
|
||||
{'filename': fname,
|
||||
'modified': modified,
|
||||
'size': size})
|
||||
path_info['filename'] = fname
|
||||
flist['files'].append(path_info)
|
||||
return flist
|
||||
|
||||
def _shell_proc_callback(self, result):
|
||||
try:
|
||||
proc_resp = json.loads(result.strip())
|
||||
except Exception:
|
||||
logging.exception("file_manager: unable to load metadata")
|
||||
logging.debug(result)
|
||||
return
|
||||
proc_log = proc_resp.get('log', [])
|
||||
for log_msg in proc_log:
|
||||
logging.info(log_msg)
|
||||
file_path = proc_resp.pop('file', None)
|
||||
if file_path is not None:
|
||||
self.gcode_metadata[file_path] = proc_resp.get('metadata')
|
||||
|
||||
async def _update_metadata(self):
|
||||
async with self.metadata_lock:
|
||||
exisiting_data = {}
|
||||
update_list = []
|
||||
gc_files = dict(self.file_lists.get('gcodes', {}))
|
||||
gc_path = self.file_paths.get('gcodes', "")
|
||||
for fname, fdata in gc_files.items():
|
||||
mdata = self.gcode_metadata.get(fname, {})
|
||||
if mdata.get('size', "") == fdata.get('size') \
|
||||
and mdata.get('modified', "") == fdata.get('modified'):
|
||||
# file metadata has already been extracted
|
||||
exisiting_data[fname] = mdata
|
||||
else:
|
||||
update_list.append(fname)
|
||||
self.gcode_metadata = exisiting_data
|
||||
for fname in update_list:
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
gc_path, "-f", "'" + fname + "'"])
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(
|
||||
cmd, self._shell_proc_callback)
|
||||
try:
|
||||
await scmd.run(timeout=4.)
|
||||
except Exception:
|
||||
logging.exception("Error running extract_metadata.py")
|
||||
|
||||
def _update_file_list(self, base='gcodes'):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
path = self.file_paths.get(base, None)
|
||||
if path is None:
|
||||
msg = "No known path for root: %s" % (base)
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
elif not os.path.isdir(path):
|
||||
msg = "Cannot generate file list for root: %s" % (base)
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info("Updating File List <%s>..." % (base))
|
||||
new_list = {}
|
||||
for root, dirs, files in os.walk(path, followlinks=True):
|
||||
for name in files:
|
||||
ext = name[name.rfind('.')+1:]
|
||||
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root, name)
|
||||
r_path = full_path[len(path) + 1:]
|
||||
size = os.path.getsize(full_path)
|
||||
modified = time.ctime(os.path.getmtime(full_path))
|
||||
new_list[r_path] = {'size': size, 'modified': modified}
|
||||
self.file_lists[base] = new_list
|
||||
if base == 'gcodes':
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(self._update_metadata)
|
||||
return dict(new_list)
|
||||
def _get_path_info(self, path):
|
||||
modified = os.path.getmtime(path)
|
||||
size = os.path.getsize(path)
|
||||
path_info = {'modified': modified, 'size': size}
|
||||
return path_info
|
||||
|
||||
async def process_file_upload(self, request):
|
||||
# lookup root file path
|
||||
@@ -317,20 +294,25 @@ class FileManager:
|
||||
elif root in FULL_ACCESS_ROOTS:
|
||||
result = self._do_standard_upload(request, root)
|
||||
else:
|
||||
raise self.server.error("Invalid root request: %s" % (root))
|
||||
raise self.server.error(f"Invalid root request: {root}")
|
||||
return result
|
||||
|
||||
async def _do_gcode_upload(self, request):
|
||||
start_print = print_ongoing = False
|
||||
base_path = self.file_paths.get("gcodes", "")
|
||||
if not base_path:
|
||||
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(
|
||||
@@ -341,26 +323,31 @@ 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"
|
||||
gcode_apis = self.server.lookup_plugin('gcode_apis')
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
try:
|
||||
await gcode_apis.gcode_start_print(
|
||||
request.path, 'POST', {'filename': upload['filename']})
|
||||
await klippy_apis.start_print(upload['filename'])
|
||||
except self.server.error:
|
||||
# Attempt to start print failed
|
||||
start_print = False
|
||||
self.notify_filelist_changed(upload['filename'], 'added', "gcodes")
|
||||
self.notify_filelist_changed(
|
||||
'upload_file', upload['filename'], "gcodes")
|
||||
return {'result': upload['filename'], 'print_started': start_print}
|
||||
|
||||
def _do_standard_upload(self, request, root):
|
||||
path = self.file_paths.get(root, None)
|
||||
if path is None:
|
||||
raise self.server.error("Unknown root path: %s" % (root))
|
||||
raise self.server.error(f"Unknown root path: {root}")
|
||||
upload = self._get_upload_info(request, path)
|
||||
self._write_file(upload)
|
||||
self.notify_filelist_changed(upload['filename'], 'added', root)
|
||||
self.notify_filelist_changed('upload_file', upload['filename'], root)
|
||||
return {'result': upload['filename']}
|
||||
|
||||
def _get_argument(self, request, name, default=None):
|
||||
@@ -369,7 +356,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
|
||||
@@ -381,42 +368,99 @@ 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("/")
|
||||
parts = os.path.split(upload['filename'].strip().lstrip("/"))
|
||||
filename = os.path.join(parts[0], "_".join(parts[1].split()))
|
||||
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(
|
||||
"Cannot write to path: %s" % (full_path))
|
||||
f"Cannot write to path: {full_path}")
|
||||
return {
|
||||
'filename': filename,
|
||||
'body': upload['body'],
|
||||
'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}>...")
|
||||
for root_path, dirs, files in os.walk(path, followlinks=True):
|
||||
for name in files:
|
||||
ext = os.path.splitext(name)[-1].lower()
|
||||
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root_path, name)
|
||||
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}
|
||||
@@ -434,7 +478,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):
|
||||
@@ -446,7 +490,7 @@ class FileManager:
|
||||
root = parts[0]
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(
|
||||
"Invalid Directory Request: %s" % (directory))
|
||||
f"Invalid Directory Request: {directory}")
|
||||
path = self.file_paths[root]
|
||||
if len(parts) == 1:
|
||||
dir_path = path
|
||||
@@ -454,7 +498,7 @@ class FileManager:
|
||||
dir_path = os.path.join(path, parts[1])
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
"Directory does not exist (%s)" % (dir_path))
|
||||
f"Directory does not exist ({dir_path})")
|
||||
flist = self._list_directory(dir_path)
|
||||
if simple_format:
|
||||
simple_list = []
|
||||
@@ -462,29 +506,172 @@ 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)
|
||||
root = parts[0]
|
||||
if root not in self.file_paths or len(parts) != 2:
|
||||
raise self.server.error("Invalid file path: %s" % (path))
|
||||
root_path = self.file_paths[root]
|
||||
full_path = os.path.join(root_path, parts[1])
|
||||
if not os.path.isfile(full_path):
|
||||
raise self.server.error("Invalid file path: %s" % (path))
|
||||
os.remove(full_path)
|
||||
async def _handle_file_delete(self, web_request):
|
||||
file_path = web_request.get_str("path")
|
||||
return await self.delete_file(file_path)
|
||||
|
||||
def notify_filelist_changed(self, fname, action, base, params={}):
|
||||
self._update_file_list(base)
|
||||
result = {'filename': fname, 'action': action, 'root': base}
|
||||
if params:
|
||||
result.update(params)
|
||||
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]
|
||||
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, 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, 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 load_plugin(server):
|
||||
return FileManager(server)
|
||||
def close(self):
|
||||
self.gcode_metadata.close()
|
||||
|
||||
|
||||
METADATA_PRUNE_TIME = 600000
|
||||
|
||||
class MetadataStorage:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
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):
|
||||
if key not in self.metadata:
|
||||
return default
|
||||
return dict(self.metadata[key])
|
||||
|
||||
def __getitem__(self, key):
|
||||
return dict(self.metadata[key])
|
||||
|
||||
def _handle_script_response(self, result):
|
||||
try:
|
||||
proc_resp = json.loads(result.strip())
|
||||
except Exception:
|
||||
logging.exception("file_manager: unable to load metadata")
|
||||
logging.debug(result)
|
||||
return
|
||||
proc_log = proc_resp.get('log', [])
|
||||
for log_msg in proc_log:
|
||||
logging.info(log_msg)
|
||||
if 'file' in proc_resp:
|
||||
self.script_response = proc_resp
|
||||
|
||||
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
|
||||
|
||||
def _has_valid_data(self, fname, fsize, modified):
|
||||
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
|
||||
return mdata['size'] == fsize and mdata['modified'] == modified
|
||||
|
||||
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):
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
self.gc_path, "-f", "'" + filename + "'"])
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(
|
||||
cmd, self._handle_script_response)
|
||||
self.script_response = None
|
||||
await scmd.run(timeout=4.)
|
||||
if self.script_response is None:
|
||||
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 notify:
|
||||
self.server.send_event(
|
||||
"file_manager:metadata_update", metadata)
|
||||
|
||||
def load_plugin(config):
|
||||
return FileManager(config)
|
||||
@@ -1,67 +0,0 @@
|
||||
# Map HTTP/Websocket APIs for specific gcode tasks
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
GCODE_ENDPOINT = "gcode/script"
|
||||
|
||||
class GCodeAPIs:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
|
||||
# Register GCode Endpoints
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/pause", "printer_print_pause", ['POST'],
|
||||
self.gcode_pause)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", "printer_print_resume", ['POST'],
|
||||
self.gcode_resume)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", "printer_print_cancel", ['POST'],
|
||||
self.gcode_cancel)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", "printer_print_start", ['POST'],
|
||||
self.gcode_start_print)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", "printer_restart", ['POST'],
|
||||
self.gcode_restart)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
|
||||
self.gcode_firmware_restart)
|
||||
|
||||
async def _send_gcode(self, script):
|
||||
args = {'script': script}
|
||||
request = self.server.make_request(
|
||||
GCODE_ENDPOINT, 'POST', args)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise result
|
||||
return result
|
||||
|
||||
async def gcode_pause(self, path, method, args):
|
||||
return await self._send_gcode("PAUSE")
|
||||
|
||||
async def gcode_resume(self, path, method, args):
|
||||
return await self._send_gcode("RESUME")
|
||||
|
||||
async def gcode_cancel(self, path, method, args):
|
||||
return await self._send_gcode("CANCEL_PRINT")
|
||||
|
||||
async def gcode_start_print(self, path, method, args):
|
||||
filename = args.get('filename')
|
||||
# XXX - validate that file is on disk
|
||||
|
||||
if filename[0] != '/':
|
||||
filename = '/' + filename
|
||||
script = "M23 " + filename + "\nM24"
|
||||
return await self._send_gcode(script)
|
||||
|
||||
async def gcode_restart(self, path, method, args):
|
||||
return await self._send_gcode("RESTART")
|
||||
|
||||
async def gcode_firmware_restart(self, path, method, args):
|
||||
return await self._send_gcode("FIRMWARE_RESTART")
|
||||
|
||||
def load_plugin(server):
|
||||
return GCodeAPIs(server)
|
||||
@@ -0,0 +1,159 @@
|
||||
# Helper for Moonraker to Klippy API calls.
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import utils
|
||||
from websockets import WebRequest
|
||||
|
||||
INFO_ENDPOINT = "info"
|
||||
ESTOP_ENDPOINT = "emergency_stop"
|
||||
LIST_EPS_ENDPOINT = "list_endpoints"
|
||||
GC_OUTPUT_ENDPOINT = "gcode/subscribe_output"
|
||||
GCODE_ENDPOINT = "gcode/script"
|
||||
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
|
||||
STATUS_ENDPOINT = "objects/query"
|
||||
OBJ_LIST_ENDPOINT = "objects/list"
|
||||
REG_METHOD_ENDPOINT = "register_remote_method"
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
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", ['POST'], self._gcode_pause)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", ['POST'], self._gcode_resume)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", ['POST'], self._gcode_cancel)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", ['POST'], self._gcode_start_print)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", ['POST'], self._gcode_restart)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
|
||||
|
||||
async def _gcode_pause(self, web_request):
|
||||
return await self.run_gcode("PAUSE")
|
||||
|
||||
async def _gcode_resume(self, web_request):
|
||||
return await self.run_gcode("RESUME")
|
||||
|
||||
async def _gcode_cancel(self, web_request):
|
||||
return await self.run_gcode("CANCEL_PRINT")
|
||||
|
||||
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, web_request):
|
||||
return await self.do_restart("RESTART")
|
||||
|
||||
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(
|
||||
WebRequest(method, params, conn=self))
|
||||
except self.server.error as e:
|
||||
if default == Sentinel:
|
||||
raise
|
||||
result = default
|
||||
return result
|
||||
|
||||
async def run_gcode(self, script, default=Sentinel):
|
||||
params = {'script': script}
|
||||
result = await self._send_klippy_request(
|
||||
GCODE_ENDPOINT, params, default)
|
||||
return result
|
||||
|
||||
async def start_print(self, filename):
|
||||
# XXX - validate that file is on disk
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
|
||||
return await self.run_gcode(script)
|
||||
|
||||
async def do_restart(self, gc):
|
||||
try:
|
||||
result = await self.run_gcode(gc)
|
||||
except self.server.error as e:
|
||||
if str(e) == "Klippy Disconnected":
|
||||
result = "ok"
|
||||
else:
|
||||
raise
|
||||
return result
|
||||
|
||||
async def list_endpoints(self, default=Sentinel):
|
||||
return await self._send_klippy_request(
|
||||
LIST_EPS_ENDPOINT, {}, default)
|
||||
|
||||
async def emergency_stop(self, default=Sentinel):
|
||||
return await self._send_klippy_request(ESTOP_ENDPOINT, {}, default)
|
||||
|
||||
async def get_klippy_info(self, send_id=False, default=Sentinel):
|
||||
params = {}
|
||||
if send_id:
|
||||
ver = utils.get_software_version()
|
||||
params = {'client_info': {'program': "Moonraker", 'version': ver}}
|
||||
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
|
||||
|
||||
async def get_object_list(self, default=Sentinel):
|
||||
result = await self._send_klippy_request(
|
||||
OBJ_LIST_ENDPOINT, {}, default)
|
||||
if isinstance(result, dict) and 'objects' in result:
|
||||
return result['objects']
|
||||
return result
|
||||
|
||||
async def query_objects(self, objects, default=Sentinel):
|
||||
params = {'objects': objects}
|
||||
result = await self._send_klippy_request(
|
||||
STATUS_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and 'status' in result:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_objects(self, objects, default=Sentinel):
|
||||
for obj, items in objects.items():
|
||||
if obj in self.host_subscription:
|
||||
prev = self.host_subscription[obj]
|
||||
if items is None or prev is None:
|
||||
self.host_subscription[obj] = None
|
||||
else:
|
||||
uitems = list(set(prev) | set(items))
|
||||
self.host_subscription[obj] = uitems
|
||||
else:
|
||||
self.host_subscription[obj] = items
|
||||
params = {'objects': self.host_subscription}
|
||||
result = await self._send_klippy_request(
|
||||
SUBSCRIPTION_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and 'status' in result:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_gcode_output(self, default=Sentinel):
|
||||
template = {'response_template':
|
||||
{'method': "process_gcode_response"}}
|
||||
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, server):
|
||||
self.server = server
|
||||
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("Error running cmd '%s'" % (cmd))
|
||||
return "ok"
|
||||
logging.exception(f"Error running cmd '{cmd}'")
|
||||
raise
|
||||
|
||||
def load_plugin(server):
|
||||
return Machine(server)
|
||||
def load_plugin(config):
|
||||
return Machine(config)
|
||||
+202
-156
@@ -9,9 +9,9 @@ import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import tempfile
|
||||
from collections import deque
|
||||
from utils import ServerError
|
||||
from tornado import gen, netutil
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.locks import Lock
|
||||
|
||||
@@ -20,29 +20,20 @@ MIN_EST_TIME = 10.
|
||||
class PanelDueError(ServerError):
|
||||
pass
|
||||
|
||||
|
||||
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
|
||||
|
||||
class SerialConnection:
|
||||
def __init__(self, paneldue):
|
||||
def __init__(self, config, paneldue):
|
||||
self.ioloop = IOLoop.current()
|
||||
self.paneldue = paneldue
|
||||
self.port = ""
|
||||
self.baud = 57200
|
||||
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
|
||||
|
||||
def load_config(self, config):
|
||||
port = config.get('serial', None)
|
||||
baud = int(config.get('baud', 57200))
|
||||
if port is None:
|
||||
logging.info("No serial port specified, cannot connect")
|
||||
return
|
||||
if port != self.port or baud != self.baud or \
|
||||
not self.connected:
|
||||
self.disconnect()
|
||||
self.port = port
|
||||
self.baud = baud
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
|
||||
def disconnect(self):
|
||||
if self.connected:
|
||||
@@ -60,7 +51,7 @@ class SerialConnection:
|
||||
if connect_time > start_time + 30.:
|
||||
logging.info("Unable to connect, aborting")
|
||||
break
|
||||
logging.info("Attempting to connect to: %s" % (self.port))
|
||||
logging.info(f"Attempting to connect to: {self.port}")
|
||||
try:
|
||||
# XXX - sometimes the port cannot be exclusively locked, this
|
||||
# would likely be due to a restart where the serial port was
|
||||
@@ -68,7 +59,7 @@ class SerialConnection:
|
||||
self.ser = serial.Serial(
|
||||
self.port, self.baud, timeout=0, exclusive=True)
|
||||
except (OSError, IOError, serial.SerialException):
|
||||
logging.exception("Unable to open port: %s" % (self.port))
|
||||
logging.exception(f"Unable to open port: {self.port}")
|
||||
await gen.sleep(2.)
|
||||
connect_time += time.time()
|
||||
continue
|
||||
@@ -137,40 +128,72 @@ class SerialConnection:
|
||||
|
||||
|
||||
class PanelDue:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.ser_conn = SerialConnection(self)
|
||||
self.file_manager = self.server.load_plugin('file_manager')
|
||||
self.ser_conn = SerialConnection(config, self)
|
||||
self.file_manager = self.server.lookup_plugin('file_manager')
|
||||
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
self.kinematics = "none"
|
||||
self.machine_name = "Klipper"
|
||||
self.machine_name = config.get('machine_name', "Klipper")
|
||||
self.firmware_name = "Repetier | Klipper"
|
||||
self.last_message = None
|
||||
self.last_gcode_response = None
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
self.enable_checksum = config.getboolean('enable_checksum', True)
|
||||
self.debug_queue = deque(maxlen=100)
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state = {
|
||||
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'pause_resume': {}, 'fan': {}, 'display_status': {}}
|
||||
self.available_macros = {}
|
||||
self.non_trivial_keys = []
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
self.last_printer_state = 'C'
|
||||
|
||||
# Set up macros
|
||||
self.confirmed_gcode = ""
|
||||
self.mbox_sequence = 0
|
||||
self.available_macros = {}
|
||||
self.confirmed_macros = {
|
||||
"RESTART": "RESTART",
|
||||
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
|
||||
macros = config.get('macros', None)
|
||||
if macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
macros = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
conf_macros = config.get('confirmed_macros', None)
|
||||
if conf_macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
|
||||
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
|
||||
self.available_macros.update(self.confirmed_macros)
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
# Register server events
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_state_changed", self.handle_klippy_state)
|
||||
"server:klippy_ready", self._process_klippy_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._process_klippy_shutdown)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._process_klippy_disconnect)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self.handle_status_update)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self.handle_gcode_response)
|
||||
|
||||
self.server.register_remote_method(
|
||||
"paneldue_beep", self.handle_paneldue_beep)
|
||||
"paneldue_beep", self.paneldue_beep)
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# make a request to Klippy
|
||||
@@ -193,50 +216,20 @@ class PanelDue:
|
||||
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
|
||||
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
|
||||
'M290': self._prepare_M290,
|
||||
'M292': self._prepare_M292,
|
||||
'M999': lambda args: "FIRMWARE_RESTART"
|
||||
}
|
||||
|
||||
def load_config(self, config):
|
||||
self.ser_conn.load_config(config)
|
||||
self.machine_name = config.get('machine_name', self.machine_name)
|
||||
macros = config.get('macros', None)
|
||||
if macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
macros = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
else:
|
||||
self.available_macros = {}
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
|
||||
self.ioloop.spawn_callback(self.write_response, {'status': 'C'})
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
async def _klippy_request(self, command, method='GET', args={}):
|
||||
request = self.server.make_request(command, method, args)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise PanelDueError(str(result))
|
||||
return result
|
||||
|
||||
async def handle_klippy_state(self, state):
|
||||
if state == "ready":
|
||||
await self._process_klippy_ready()
|
||||
elif state == "shutdown":
|
||||
await self._process_klippy_shutdown()
|
||||
elif state == "disconnect":
|
||||
await self._process_klippy_disconnect()
|
||||
|
||||
async def _process_klippy_ready(self):
|
||||
# Request "info" and "configfile" status
|
||||
retries = 10
|
||||
printer_info = cfg_status = {}
|
||||
while retries:
|
||||
try:
|
||||
printer_info = await self._klippy_request("info")
|
||||
cfg_status = await self._klippy_request(
|
||||
"objects/status", args={'configfile': []})
|
||||
except PanelDueError:
|
||||
printer_info = await self.klippy_apis.get_klippy_info()
|
||||
cfg_status = await self.klippy_apis.query_objects(
|
||||
{'configfile': None})
|
||||
except self.server.error:
|
||||
logging.exception("PanelDue initialization request failed")
|
||||
retries -= 1
|
||||
if not retries:
|
||||
@@ -245,23 +238,24 @@ class PanelDue:
|
||||
continue
|
||||
break
|
||||
|
||||
self.firmware_name = "Repetier | Klipper " + printer_info['version']
|
||||
self.firmware_name = "Repetier | Klipper " + \
|
||||
printer_info['software_version']
|
||||
config = cfg_status.get('configfile', {}).get('config', {})
|
||||
printer_cfg = config.get('printer', {})
|
||||
self.kinematics = printer_cfg.get('kinematics', "none")
|
||||
|
||||
logging.info(
|
||||
"PanelDue Config Received:\n"
|
||||
"Firmware Name: %s\n"
|
||||
"Kinematics: %s\n"
|
||||
"Printer Config: %s\n"
|
||||
% (self.firmware_name, self.kinematics, str(config)))
|
||||
f"PanelDue Config Received:\n"
|
||||
f"Firmware Name: {self.firmware_name}\n"
|
||||
f"Kinematics: {self.kinematics}\n"
|
||||
f"Printer Config: {config}\n")
|
||||
|
||||
# Initalize printer state and make subscription request
|
||||
self.printer_state = {
|
||||
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'pause_resume': {}, 'fan': {}, 'display_status': {}}
|
||||
sub_args = {'gcode': [], 'toolhead': []}
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
sub_args = {k: None for k in self.printer_state.keys()}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
for cfg in config:
|
||||
@@ -269,18 +263,17 @@ class PanelDue:
|
||||
self.extruder_count += 1
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = []
|
||||
sub_args[cfg] = None
|
||||
elif cfg == "heater_bed":
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = []
|
||||
elif cfg in self.printer_state:
|
||||
sub_args[cfg] = []
|
||||
sub_args[cfg] = None
|
||||
try:
|
||||
await self._klippy_request(
|
||||
"objects/subscription", method='POST', args=sub_args)
|
||||
except PanelDueError:
|
||||
status = await self.klippy_apis.subscribe_objects(sub_args)
|
||||
except self.server.error:
|
||||
logging.exception("Unable to complete subscription request")
|
||||
else:
|
||||
self.printer_state.update(status)
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
@@ -293,53 +286,60 @@ class PanelDue:
|
||||
self.is_ready = False
|
||||
|
||||
async def handle_status_update(self, status):
|
||||
self.printer_state.update(status)
|
||||
for obj, items in status.items():
|
||||
if obj in self.printer_state:
|
||||
self.printer_state[obj].update(items)
|
||||
else:
|
||||
self.printer_state[obj] = items
|
||||
|
||||
def handle_paneldue_beep(self, frequency, duration):
|
||||
async def paneldue_beep(self, frequency, duration):
|
||||
duration = int(duration * 1000.)
|
||||
self.ioloop.spawn_callback(
|
||||
self.write_response,
|
||||
await self.write_response(
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
async 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_request("emergency_stop", method='POST')
|
||||
await 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 = " Line Number: %d" % 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 = " Line Number: %d" % 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])
|
||||
await self._run_gcode(line[line_index+1:cs_index])
|
||||
else:
|
||||
await self._run_gcode(line)
|
||||
|
||||
async def _run_gcode(self, script):
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
@@ -355,7 +355,7 @@ class PanelDue:
|
||||
try:
|
||||
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
|
||||
except Exception:
|
||||
msg = "paneldue: Error parsing direct gcode %s" % (script)
|
||||
msg = f"paneldue: Error parsing direct gcode {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
return
|
||||
@@ -369,12 +369,16 @@ class PanelDue:
|
||||
func = self.special_gcodes[cmd]
|
||||
script = func(parts[1:])
|
||||
|
||||
if not script:
|
||||
return
|
||||
elif script in RESTART_GCODES:
|
||||
await self.klippy_apis.do_restart(script)
|
||||
return
|
||||
|
||||
try:
|
||||
args = {'script': script}
|
||||
await self._klippy_request(
|
||||
"gcode/script", method='POST', args=args)
|
||||
except PanelDueError:
|
||||
msg = "Error executing script %s" % script
|
||||
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)
|
||||
|
||||
@@ -400,7 +404,7 @@ class PanelDue:
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "M23 " + filename + "\n" + "M24"
|
||||
return "SDCARD_PRINT_FILE FILENAME=" + filename
|
||||
|
||||
def _prepare_M98(self, args):
|
||||
macro = args[0][1:].strip()
|
||||
@@ -408,13 +412,39 @@ class PanelDue:
|
||||
macro = macro[name_start:]
|
||||
cmd = self.available_macros.get(macro)
|
||||
if cmd is None:
|
||||
raise PanelDueError("Macro %s invalid" % (macro))
|
||||
raise PanelDueError(f"Macro {macro} invalid")
|
||||
if macro in self.confirmed_macros:
|
||||
self._create_confirmation(macro, cmd)
|
||||
cmd = ""
|
||||
return cmd
|
||||
|
||||
def _prepare_M290(self, args):
|
||||
# args should in in the format Z0.02
|
||||
offset = args[0][1:].strip()
|
||||
return "SET_GCODE_OFFSET Z_ADJUST=%s MOVE=1" % (offset)
|
||||
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
|
||||
|
||||
def _prepare_M292(self, args):
|
||||
p_val = int(args[0][1])
|
||||
if p_val == 0:
|
||||
cmd = self.confirmed_gcode
|
||||
self.confirmed_gcode = ""
|
||||
return cmd
|
||||
return ""
|
||||
|
||||
def _create_confirmation(self, name, gcode):
|
||||
self.mbox_sequence += 1
|
||||
self.confirmed_gcode = gcode
|
||||
title = "Confirmation Dialog"
|
||||
msg = f"Please confirm your intent to run {name}." \
|
||||
" Press OK to continue, or CANCEL to abort."
|
||||
mbox = {}
|
||||
mbox['msgBox.mode'] = 3
|
||||
mbox['msgBox.msg'] = msg
|
||||
mbox['msgBox.seq'] = self.mbox_sequence
|
||||
mbox['msgBox.title'] = title
|
||||
mbox['msgBox.controls'] = 0
|
||||
mbox['msgBox.timeout'] = 0
|
||||
self.ioloop.spawn_callback(self.write_response, mbox)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
@@ -441,18 +471,25 @@ class PanelDue:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
is_active = printer_state['virtual_sdcard'].get('is_active', False)
|
||||
paused = printer_state['pause_resume'].get('is_paused', False)
|
||||
if paused:
|
||||
if is_active:
|
||||
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':
|
||||
# Resuming
|
||||
return 'R'
|
||||
# Printing
|
||||
return 'P'
|
||||
elif sd_state == "paused":
|
||||
if p_busy and self.last_printer_state != 'A':
|
||||
# Pausing
|
||||
return 'D'
|
||||
else:
|
||||
# Paused
|
||||
return 'A'
|
||||
|
||||
if is_active:
|
||||
return 'P'
|
||||
|
||||
if printer_state['gcode'].get('busy', False):
|
||||
if p_busy:
|
||||
# Printer is "busy"
|
||||
return 'B'
|
||||
|
||||
return 'I'
|
||||
@@ -464,7 +501,8 @@ class PanelDue:
|
||||
|
||||
if not self.is_ready:
|
||||
# Klipper is still starting up, do not query status
|
||||
response['status'] = 'S' if self.is_shutdown else 'C'
|
||||
self.last_printer_state = 'S' if self.is_shutdown else 'C'
|
||||
response['status'] = self.last_printer_state
|
||||
await self.write_response(response)
|
||||
return
|
||||
|
||||
@@ -483,28 +521,30 @@ class PanelDue:
|
||||
response['axes'] = 3
|
||||
|
||||
p_state = self.printer_state
|
||||
status = self._get_printer_status()
|
||||
response['status'] = status
|
||||
response['babystep'] = round(p_state['gcode'].get(
|
||||
'homing_zpos', 0.), 3)
|
||||
self.last_printer_state = self._get_printer_status()
|
||||
response['status'] = self.last_printer_state
|
||||
response['babystep'] = round(p_state['gcode_move'].get(
|
||||
'homing_origin', [0., 0., 0., 0.])[2], 3)
|
||||
|
||||
# Current position
|
||||
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
|
||||
response['pos'] = [round(p, 2) for p in pos[:3]]
|
||||
homed_pos = p_state['toolhead'].get('homed_axes', "")
|
||||
response['homed'] = [int(a in homed_pos) for a in "xyz"]
|
||||
sfactor = round(p_state['gcode'].get('speed_factor', 1.) * 100, 2)
|
||||
sfactor = round(p_state['gcode_move'].get('speed_factor', 1.) * 100, 2)
|
||||
response['sfactor'] = sfactor
|
||||
|
||||
# Print Progress Tracking
|
||||
sd_status = p_state['virtual_sdcard']
|
||||
fname = sd_status.get('filename', "")
|
||||
if fname:
|
||||
print_stats = p_state['print_stats']
|
||||
fname = print_stats.get('filename', "")
|
||||
sd_print_state = print_stats.get('state')
|
||||
if sd_print_state in ['printing', 'paused']:
|
||||
# We know a file has been loaded, initialize metadata
|
||||
if self.current_file != fname:
|
||||
self.current_file = fname
|
||||
self.file_metadata = self.file_manager.get_file_metadata(fname)
|
||||
progress = p_state['virtual_sdcard'].get('progress', 0)
|
||||
progress = sd_status.get('progress', 0)
|
||||
# progress and print tracking
|
||||
if progress:
|
||||
response['fraction_printed'] = round(progress, 3)
|
||||
@@ -515,19 +555,20 @@ class PanelDue:
|
||||
# filament estimate
|
||||
est_total_fil = self.file_metadata.get('filament_total')
|
||||
if est_total_fil:
|
||||
cur_filament = sd_status.get('filament_used', 0.)
|
||||
cur_filament = print_stats.get('filament_used', 0.)
|
||||
fpct = min(1., cur_filament / est_total_fil)
|
||||
times_left.append(int(est_time - est_time * fpct))
|
||||
# object height estimate
|
||||
obj_height = self.file_metadata.get('object_height')
|
||||
if obj_height:
|
||||
cur_height = p_state['gcode'].get('move_zpos', 0.)
|
||||
cur_height = p_state['gcode_move'].get(
|
||||
'gcode_position', [0., 0., 0., 0.])[2]
|
||||
hpct = min(1., cur_height / obj_height)
|
||||
times_left.append(int(est_time - est_time * hpct))
|
||||
else:
|
||||
# The estimated time is not in the metadata, however we
|
||||
# can still provide an estimate based on file progress
|
||||
duration = sd_status.get('print_duration', 0.)
|
||||
duration = print_stats.get('print_duration', 0.)
|
||||
times_left = [int(duration / progress - duration)]
|
||||
response['timesLeft'] = times_left
|
||||
else:
|
||||
@@ -548,7 +589,8 @@ class PanelDue:
|
||||
response['tool'] = tool
|
||||
|
||||
# Report Heater Status
|
||||
efactor = round(p_state['gcode'].get('extrude_factor', 1.) * 100., 2)
|
||||
efactor = round(p_state['gcode_move'].get(
|
||||
'extrude_factor', 1.) * 100., 2)
|
||||
|
||||
for name in self.heaters:
|
||||
temp = round(p_state[name].get('temperature', 0.0), 1)
|
||||
@@ -575,8 +617,7 @@ class PanelDue:
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
"PanelDue: Cannot process response type %d in M20"
|
||||
% (response_type))
|
||||
f"Cannot process response type {response_type} in M20")
|
||||
return
|
||||
path = arg_p
|
||||
|
||||
@@ -624,18 +665,19 @@ 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):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
print_stats = self.printer_state.get('print_stats', {})
|
||||
if filename is None:
|
||||
# PanelDue is requesting file information on a
|
||||
# currently printed file
|
||||
active = False
|
||||
if sd_status:
|
||||
filename = sd_status['filename']
|
||||
if sd_status and print_stats:
|
||||
filename = print_stats['filename']
|
||||
active = sd_status['is_active']
|
||||
if not filename or not active:
|
||||
# Either no file printing or no virtual_sdcard
|
||||
@@ -658,7 +700,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
|
||||
@@ -680,6 +722,10 @@ class PanelDue:
|
||||
|
||||
async 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(server):
|
||||
return PanelDue(server)
|
||||
def load_plugin(config):
|
||||
return PanelDue(config)
|
||||
+369
-150
@@ -6,183 +6,402 @@
|
||||
|
||||
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, server):
|
||||
self.server = server
|
||||
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 = {}
|
||||
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
|
||||
|
||||
def load_config(self, config):
|
||||
if "devices" not in config:
|
||||
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']
|
||||
|
||||
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
|
||||
|
||||
devices = config["devices"].split(',')
|
||||
logging.info("Power plugin loading devices: " + str(devices))
|
||||
|
||||
parsed_devices = {}
|
||||
for dev in devices:
|
||||
dev = dev.strip()
|
||||
pin = config.get(dev + "_pin", "")
|
||||
if not pin.isdigit():
|
||||
logging.info(
|
||||
"Power plugin: ERR %s does not have a pin defined" % (dev))
|
||||
continue
|
||||
|
||||
name = config.get(dev + "_name", dev)
|
||||
active_low = int(config.get(
|
||||
dev + "_active_low", "false").lower() == "true")
|
||||
parsed_devices[dev] = {
|
||||
"name": name,
|
||||
"pin": int(pin),
|
||||
"active_low": active_low,
|
||||
"status": None
|
||||
}
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(self.initialize_devices, parsed_devices)
|
||||
ioloop.spawn_callback(
|
||||
self._process_request, self.devices[device], status)
|
||||
|
||||
async def initialize_devices(self, devices):
|
||||
for name, device in devices.items():
|
||||
try:
|
||||
logging.debug(
|
||||
"Attempting to configure pin GPIO%d"
|
||||
% (device["pin"]))
|
||||
await GPIO.setup_pin(device["pin"], device["active_low"])
|
||||
device["status"] = GPIO.is_pin_on(device["pin"])
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Power plugin: ERR Problem configuring the output pin for"
|
||||
" device %s. Removing device" % (name))
|
||||
self.devices.pop(name, None)
|
||||
continue
|
||||
self.devices[name] = device
|
||||
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
|
||||
|
||||
class GPIO:
|
||||
gpio_root = "/sys/class/gpio"
|
||||
|
||||
@staticmethod
|
||||
def _set_gpio_option(gpio, option, value):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, "gpio%d" % (gpio), option),
|
||||
value
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_gpio_option(pin, option):
|
||||
return GPIO._read(
|
||||
os.path.join(GPIO.gpio_root, "gpio%d" % (pin), option)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _write(file, data):
|
||||
with open(file, 'w') as f:
|
||||
f.write(str(data))
|
||||
f.flush()
|
||||
|
||||
@staticmethod
|
||||
def _read(file):
|
||||
with open(file, 'r') as f:
|
||||
f.seek(0)
|
||||
return f.read().strip()
|
||||
|
||||
@staticmethod
|
||||
async def verify_pin(pin, active_low=1):
|
||||
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
|
||||
if not os.path.exists(gpiopath):
|
||||
logging.info("Re-intializing GPIO%d" % (pin))
|
||||
await GPIO.setup_pin(pin, active_low)
|
||||
return
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
|
||||
@staticmethod
|
||||
async def setup_pin(pin, active_low=1):
|
||||
pin = int(pin)
|
||||
active_low = 1 if active_low == 1 else 0
|
||||
|
||||
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
|
||||
if not os.path.exists(gpiopath):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, "export"),
|
||||
pin)
|
||||
logging.info("Waiting for GPIO%d to initialize" % (pin))
|
||||
while os.stat(os.path.join(
|
||||
GPIO.gpio_root, "gpio%d" % (pin),
|
||||
"active_low")).st_gid == 0:
|
||||
await gen.sleep(.1)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
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")
|
||||
self.set_power("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(server):
|
||||
return PrinterPower(server)
|
||||
# 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 = "Power{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid tasmota command: {command}")
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
|
||||
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,14 @@ 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
|
||||
|
||||
def _process_output(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
@@ -28,19 +29,22 @@ 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
|
||||
|
||||
async def run(self, timeout=2., verbose=True):
|
||||
fd = None
|
||||
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
|
||||
@@ -50,15 +54,15 @@ class ShellCommand:
|
||||
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"shell_command: Command {%s} failed" % (self.name))
|
||||
return
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
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,6 +71,8 @@ class ShellCommand:
|
||||
if proc.poll() is not None:
|
||||
complete = True
|
||||
break
|
||||
if self.cancelled:
|
||||
break
|
||||
if not complete:
|
||||
proc.terminate()
|
||||
if verbose:
|
||||
@@ -74,15 +80,32 @@ class ShellCommand:
|
||||
self.output_cb(self.partial_output)
|
||||
self.partial_output = b""
|
||||
if complete:
|
||||
msg = "Command {%s} finished" % (self.name)
|
||||
msg = f"Command ({self.name}) finished"
|
||||
elif self.cancelled:
|
||||
msg = f"Command ({self.name}) cancelled"
|
||||
else:
|
||||
msg = "Command {%s} timed out" % (self.name)
|
||||
msg = f"Command ({self.name}) timed out"
|
||||
logging.info(msg)
|
||||
self.io_loop.remove_handler(fd)
|
||||
return complete
|
||||
|
||||
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(server):
|
||||
def load_plugin(config):
|
||||
return ShellCommandFactory()
|
||||
@@ -0,0 +1,482 @@
|
||||
# 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 tornado.gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
|
||||
|
||||
MOONRAKER_PATH = os.path.normpath(os.path.join(
|
||||
os.path.dirname(__file__), "../.."))
|
||||
|
||||
# TODO: May want to attempt to look up the disto for the correct
|
||||
# klippy install script or have the user configure it
|
||||
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
|
||||
REPO_PREFIX = "https://api.github.com/repos"
|
||||
REPO_DATA = {
|
||||
'moonraker': {
|
||||
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
|
||||
'origin': "https://github.com/Arksine/moonraker.git",
|
||||
'install_script': "scripts/install-moonraker.sh",
|
||||
'requirements': "scripts/moonraker-requirements.txt",
|
||||
'venv_args': "-p python3 --system-site-packages"
|
||||
},
|
||||
'klipper': {
|
||||
'repo_url': f"{REPO_PREFIX}/kevinoconnor/klipper/branches/master",
|
||||
'origin': "https://github.com/KevinOConnor/klipper.git",
|
||||
'install_script': "scripts/install-octopi.sh",
|
||||
'requirements': "scripts/klippy-requirements.txt",
|
||||
'venv_args': "-p python2"
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
|
||||
self.http_client = AsyncHTTPClient()
|
||||
sw_version = config['system_args'].get('software_version')
|
||||
self.updaters = {
|
||||
"system": PackageUpdater(self),
|
||||
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH,
|
||||
sw_version, sys.executable)
|
||||
}
|
||||
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)
|
||||
|
||||
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_ready", self._set_klipper_repo)
|
||||
|
||||
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']
|
||||
kversion = kinfo['software_version']
|
||||
env = kinfo['python_path']
|
||||
self.updaters['klipper'] = GitUpdater(
|
||||
self, "klipper", kpath, kversion, env)
|
||||
|
||||
async def _check_versions(self):
|
||||
for updater in self.updaters.values():
|
||||
await updater.check_remote_version()
|
||||
|
||||
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):
|
||||
if web_request.get_boolean('refresh', False):
|
||||
await self._check_versions()
|
||||
vinfo = {}
|
||||
for name, updater in self.updaters.items():
|
||||
if hasattr(updater, "get_update_status"):
|
||||
vinfo[name] = updater.get_update_status()
|
||||
return {
|
||||
'version_info': vinfo,
|
||||
'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 github_request(self, url, is_download=False):
|
||||
cto = rto = 5.
|
||||
content_type = "application/vnd.github.v3+json"
|
||||
if is_download:
|
||||
content_type = "application/zip"
|
||||
rto = 120.
|
||||
timeout = cto + rto + 2.
|
||||
request = HTTPRequest(url, headers={"Accept": content_type},
|
||||
connect_timeout=cto, request_timeout=rto)
|
||||
retries = 5
|
||||
while True:
|
||||
to = IOLoop.current().time() + timeout
|
||||
try:
|
||||
fut = self.http_client.fetch(request)
|
||||
resp = await tornado.gen.with_timeout(to, fut)
|
||||
except Exception as e:
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise
|
||||
logging.info(f"Github request error, retrying: {e}")
|
||||
continue
|
||||
if is_download:
|
||||
return resp.body
|
||||
decoded = json.loads(resp.body)
|
||||
return decoded
|
||||
|
||||
def notify_update_response(self, resp):
|
||||
resp = resp.strip()
|
||||
if isinstance(resp, bytes):
|
||||
resp = resp.decode()
|
||||
notification = {
|
||||
'message': resp,
|
||||
'application': None,
|
||||
'proc_id': None}
|
||||
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, ver, 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
|
||||
self.github_request = umgr.github_request
|
||||
self.name = name
|
||||
self.repo_path = path
|
||||
self.env = env
|
||||
self.version = self.cur_hash = self.remote_hash = "?"
|
||||
self.is_valid = False
|
||||
self.is_dirty = ver.endswith("dirty")
|
||||
tag_version = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
self.version = tag_version
|
||||
IOLoop.current().spawn_callback(self._init_repo)
|
||||
|
||||
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):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.debug(log_msg)
|
||||
self.notify_update_response(log_msg)
|
||||
|
||||
async def _init_repo(self):
|
||||
self.is_valid = False
|
||||
self.cur_hash = "?"
|
||||
try:
|
||||
branch = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse --abbrev-ref HEAD")
|
||||
origin = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} remote get-url origin")
|
||||
hash = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse HEAD")
|
||||
except Exception:
|
||||
self._log_exc("Error retreiving git info")
|
||||
return
|
||||
|
||||
if not branch.startswith("fatal:"):
|
||||
self.cur_hash = hash
|
||||
if branch == "master":
|
||||
if origin == REPO_DATA[self.name]['origin']:
|
||||
self.is_valid = True
|
||||
self._log_info("Validity check for git repo passed")
|
||||
else:
|
||||
self._log_info(f"Invalid git origin '{origin}''")
|
||||
else:
|
||||
self._log_info("Git repo not on master branch")
|
||||
else:
|
||||
self._log_info(f"Invalid git repo at path '{self.repo_path}''")
|
||||
try:
|
||||
await self.check_remote_version()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def check_remote_version(self):
|
||||
repo_url = REPO_DATA[self.name]['repo_url']
|
||||
try:
|
||||
branch_info = await self.github_request(repo_url)
|
||||
except Exception:
|
||||
raise self._log_exc(f"Error retreiving github info")
|
||||
commit_hash = branch_info.get('commit', {}).get('sha', None)
|
||||
if commit_hash is None:
|
||||
self.is_valid = False
|
||||
self.upstream_version = "?"
|
||||
raise self._log_exc(f"Invalid github response", False)
|
||||
self._log_info(f"Received latest commit hash: {commit_hash}")
|
||||
self.remote_hash = commit_hash
|
||||
|
||||
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 == "?":
|
||||
await self.check_remote_version()
|
||||
if self.remote_hash == self.cur_hash:
|
||||
# No need to update
|
||||
return
|
||||
self._notify_status("Updating Repo...")
|
||||
try:
|
||||
await self.execute_cmd(f"git -C {self.repo_path} pull -q")
|
||||
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)
|
||||
if self.name == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
IOLoop.current().spawn_callback(self.restart_service)
|
||||
else:
|
||||
await self.restart_service()
|
||||
|
||||
async def _install_packages(self):
|
||||
# Open install file file and read
|
||||
inst_script = REPO_DATA[self.name]['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)
|
||||
if rebuild_env:
|
||||
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
|
||||
env_args = REPO_DATA[self.name]['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}")
|
||||
except Exception:
|
||||
self._log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
await tornado.gen.sleep(.5)
|
||||
if not os.path.expanduser(self.env):
|
||||
raise self._log_exc("Failed to create new virtualenv", False)
|
||||
reqs = os.path.join(
|
||||
self.repo_path, REPO_DATA[self.name]['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")
|
||||
|
||||
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 {
|
||||
'version': self.version,
|
||||
'current_hash': self.cur_hash,
|
||||
'remote_hash': self.remote_hash,
|
||||
'is_dirty': self.is_dirty,
|
||||
'is_valid': self.is_valid}
|
||||
|
||||
|
||||
class PackageUpdater:
|
||||
def __init__(self, umgr):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
|
||||
async def check_remote_version(self):
|
||||
pass
|
||||
|
||||
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")
|
||||
|
||||
class ClientUpdater:
|
||||
def __init__(self, umgr, repo, path):
|
||||
self.server = umgr.server
|
||||
self.github_request = umgr.github_request
|
||||
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 = "?"
|
||||
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()
|
||||
logging.info(f"\nInitializing repo '{self.name}',"
|
||||
f"\nversion: {self.version}"
|
||||
f"\npath: {self.path}")
|
||||
IOLoop.current().spawn_callback(self.check_remote_version)
|
||||
|
||||
async def check_remote_version(self):
|
||||
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
|
||||
try:
|
||||
result = await self.github_request(url)
|
||||
except Exception:
|
||||
logging.exception(f"Client {self.repo}: Github Request Error")
|
||||
result = {}
|
||||
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: {self.name}, "
|
||||
f"version: {self.remote_version} "
|
||||
f"url: {self.dl_url}")
|
||||
|
||||
async def update(self, *args):
|
||||
if self.remote_version == "?":
|
||||
await self.check_remote_version()
|
||||
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.github_request(self.dl_url, is_download=True)
|
||||
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 Updated: {self.name}")
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'version': self.version,
|
||||
'remote_version': self.remote_version
|
||||
}
|
||||
|
||||
def load_plugin(config):
|
||||
return UpdateManager(config)
|
||||
+33
-20
@@ -4,36 +4,34 @@
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import subprocess
|
||||
import asyncio
|
||||
from queue import SimpleQueue as Queue
|
||||
|
||||
class ServerError(Exception):
|
||||
def __init__(self, message, status_code=400):
|
||||
Exception.__init__(self, message)
|
||||
self.status_code = status_code
|
||||
|
||||
# XXX - Currently logging over the socket is not implemented.
|
||||
# I don't think it would be wise to log everything over the
|
||||
# socket, however it may be useful to log some specific items.
|
||||
# Decide what to do, then either finish the implementation or
|
||||
# remove this code
|
||||
class SocketLoggingHandler(logging.Handler):
|
||||
def __init__(self, server_manager):
|
||||
super(SocketLoggingHandler, self).__init__()
|
||||
self.server_manager = server_manager
|
||||
|
||||
def emit(self, record):
|
||||
record.msg = "[MOONRAKER]: " + record.msg
|
||||
# XXX - Convert log record to dict before sending,
|
||||
# the klippy_send function will handle serialization
|
||||
|
||||
self.server_manager.klippy_send(record)
|
||||
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
|
||||
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
|
||||
class LocalQueueHandler(logging.handlers.QueueHandler):
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
# Removed the call to self.prepare(), handle task cancellation
|
||||
try:
|
||||
self.enqueue(record)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
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)
|
||||
@@ -51,7 +49,7 @@ def get_software_version():
|
||||
|
||||
# Obtain version info from "git" program
|
||||
prog = ('git', '-C', moonraker_path, 'describe', '--always',
|
||||
'--tags', '--long', '--dirty', "--all")
|
||||
'--tags', '--long', '--dirty')
|
||||
try:
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
@@ -63,8 +61,23 @@ def get_software_version():
|
||||
version = version.decode()
|
||||
return version
|
||||
else:
|
||||
logging.debug("Error getting git version: %s", err)
|
||||
logging.debug(f"Error getting git version: {err}")
|
||||
except OSError:
|
||||
logging.exception("Error runing git describe")
|
||||
|
||||
return "?"
|
||||
|
||||
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(
|
||||
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)
|
||||
listener.start()
|
||||
return listener
|
||||
+162
-66
@@ -11,6 +11,68 @@ from tornado.ioloop import IOLoop
|
||||
from tornado.websocket import WebSocketHandler, WebSocketClosedError
|
||||
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 = {}
|
||||
@@ -21,12 +83,12 @@ 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)
|
||||
except Exception:
|
||||
msg = "Websocket data not json: %s" % (str(data))
|
||||
msg = f"Websocket data not json: {data}"
|
||||
logging.exception(msg)
|
||||
response = self.build_error(-32700, "Parse error")
|
||||
return json.dumps(response)
|
||||
@@ -34,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)
|
||||
@@ -58,25 +120,28 @@ 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:
|
||||
return self.build_error(-31000, str(e), req_id)
|
||||
if isinstance(result, ServerError):
|
||||
return self.build_error(result.status_code, str(result), req_id)
|
||||
elif req_id is None:
|
||||
|
||||
if req_id is None:
|
||||
return None
|
||||
else:
|
||||
return self.build_result(result, req_id)
|
||||
@@ -102,91 +167,109 @@ 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_state_changed", self._handle_klippy_state_changed)
|
||||
"server:klippy_ready", self._handle_klippy_ready)
|
||||
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_state_changed(self, state):
|
||||
await self.notify_websockets("klippy_state_changed", state)
|
||||
async def _handle_klippy_ready(self):
|
||||
await self.notify_websockets("klippy_ready")
|
||||
|
||||
async def _handle_klippy_disconnect(self):
|
||||
await self.notify_websockets("klippy_disconnected")
|
||||
|
||||
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)
|
||||
|
||||
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, r_method)
|
||||
self.rpc.register_method(cmd, rpc_cb)
|
||||
async def _handle_metadata_update(self, metadata):
|
||||
await self.notify_websockets("metadata_update", metadata)
|
||||
|
||||
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, request_method):
|
||||
async def func(**kwargs):
|
||||
request = self.server.make_request(
|
||||
endpoint, request_method, kwargs)
|
||||
result = await request.wait()
|
||||
def _generate_callback(self, endpoint):
|
||||
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):
|
||||
try:
|
||||
result = await callback(
|
||||
endpoint, request_method, kwargs)
|
||||
except ServerError as e:
|
||||
result = e
|
||||
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
|
||||
logging.info("New Websocket Added: %d" % ws.uid)
|
||||
logging.info(f"New Websocket Added: {ws.uid}")
|
||||
|
||||
async def remove_websocket(self, ws):
|
||||
async with self.ws_lock:
|
||||
old_ws = self.websockets.pop(ws.uid, None)
|
||||
if old_ws is not None:
|
||||
logging.info("Websocket Removed: %d" % ws.uid)
|
||||
self.server.remove_subscription(old_ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
|
||||
async def notify_websockets(self, name, data):
|
||||
notification = json.dumps({
|
||||
'jsonrpc': "2.0",
|
||||
'method': "notify_" + name,
|
||||
'params': [data]})
|
||||
async def notify_websockets(self, name, data=Sentinel):
|
||||
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
|
||||
if data != Sentinel:
|
||||
msg['params'] = [data]
|
||||
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("Websocket Removed: %d" % ws.uid)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Error sending data over websocket: %d" % (ws.uid))
|
||||
f"Error sending data over websocket: {ws.uid}")
|
||||
|
||||
async def close(self):
|
||||
async with self.ws_lock:
|
||||
@@ -195,9 +278,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)
|
||||
|
||||
@@ -210,23 +294,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:
|
||||
self.websockets.pop(self.uid, None)
|
||||
logging.info(f"Websocket Removed: {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):
|
||||
|
||||
+370
-116
@@ -9,7 +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):
|
||||
@@ -37,68 +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+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):
|
||||
@@ -113,59 +198,90 @@ class PrusaSlicer(BaseSlicer):
|
||||
data = "".join(lines[1:-1])
|
||||
if len(info) != 3:
|
||||
self.log.append(
|
||||
{'MetadataError': "Error parsing thumbnail header: %s"
|
||||
% (lines[0])})
|
||||
f"MetadataError: Error parsing thumbnail"
|
||||
f" header: {lines[0]}")
|
||||
continue
|
||||
if len(data) != info[2]:
|
||||
self.log.append(
|
||||
{'MetadataError': "Thumbnail Size Mismatch: detected %d, "
|
||||
"actual %d" % (info[2], len(data))})
|
||||
f"MetadataError: Thumbnail Size Mismatch: "
|
||||
f"detected {info[2]}, actual {len(data)}")
|
||||
continue
|
||||
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
|
||||
@@ -173,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(
|
||||
@@ -235,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(
|
||||
@@ -264,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
|
||||
@@ -277,57 +484,104 @@ 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(file_path) for s in SUPPORTED_SLICERS]
|
||||
header_data = footer_data = slicer = None
|
||||
size = os.path.getsize(file_path)
|
||||
metadata['size'] = size
|
||||
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:
|
||||
ident = s.check_identity(header_data)
|
||||
if ident is not None:
|
||||
slicer = s
|
||||
metadata.update(ident)
|
||||
break
|
||||
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):
|
||||
file_path = os.path.join(path, filename)
|
||||
slicers = [s() for s in SUPPORTED_SLICERS]
|
||||
log = []
|
||||
metadata = {}
|
||||
if not os.path.isfile(file_path):
|
||||
log.append("File Not Found: %s" % (file_path))
|
||||
log.append(f"File Not Found: {file_path}")
|
||||
else:
|
||||
header_data = footer_data = slicer = None
|
||||
size = os.path.getsize(file_path)
|
||||
metadata['size'] = size
|
||||
metadata['modified'] = time.ctime(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:
|
||||
slicer = s
|
||||
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
|
||||
try:
|
||||
metadata = extract_metadata(file_path, log)
|
||||
except Exception:
|
||||
log.append(traceback.format_exc())
|
||||
fd = sys.stdout.fileno()
|
||||
data = json.dumps(
|
||||
{'file': filename, 'log': log, 'metadata': metadata}).encode()
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
# Raspbian/Raspberry Pi OS based distributions.
|
||||
|
||||
PYTHONDIR="${HOME}/moonraker-env"
|
||||
REBUILD_ENV="n"
|
||||
FORCE_DEFAULTS="n"
|
||||
CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
|
||||
# Step 1: Verify Klipper has been installed
|
||||
check_klipper()
|
||||
@@ -19,7 +22,7 @@ check_klipper()
|
||||
# Step 2: 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..."
|
||||
@@ -33,10 +36,15 @@ install_packages()
|
||||
# Step 3: 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
|
||||
|
||||
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
|
||||
|
||||
# Install/update dependencies
|
||||
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
|
||||
@@ -54,7 +62,7 @@ install_script()
|
||||
install_config()
|
||||
{
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
[ -f $DEFAULTS_FILE ] && return
|
||||
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
|
||||
report_status "Installing system start configuration..."
|
||||
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
|
||||
@@ -64,18 +72,18 @@ MOONRAKER_USER=$USER
|
||||
|
||||
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
|
||||
|
||||
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py"
|
||||
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
|
||||
|
||||
EOF
|
||||
}
|
||||
|
||||
# Step 4: Start server
|
||||
# Step 6: Start server
|
||||
start_software()
|
||||
{
|
||||
report_status "Launching Moonraker API Server..."
|
||||
sudo /etc/init.d/klipper stop
|
||||
sudo systemctl stop klipper
|
||||
sudo /etc/init.d/moonraker restart
|
||||
sudo /etc/init.d/klipper start
|
||||
sudo systemctl start klipper
|
||||
}
|
||||
|
||||
# Helper functions
|
||||
@@ -98,6 +106,15 @@ 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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Python dependencies for Moonraker
|
||||
tornado==6.0.4
|
||||
tornado==6.1.0
|
||||
pyserial==3.4
|
||||
pillow==8.0.1
|
||||
@@ -0,0 +1,2 @@
|
||||
env_version=0.2.1
|
||||
deps_version=0.2.1
|
||||
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/>
|
||||
|
||||
+790
-409
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user