66 Commits
Author SHA1 Message Date
Arksine d59d1e5f7f docs: document new "notify_metadata_update" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 11:37:06 -04:00
Arksine 28977bd579 moonraker: Don't use a PeriodicCallback for the init routine
The init function blocks, making it reentrant.  Use "call_later" instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 08:49:52 -04:00
Arksine f9b1e2922d moonraker: speed up intialization procedure
Attempt to reconnect every 250ms when disconnected.  Once connected, attempt to initialize every 250ms.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-01 07:41:53 -04:00
Arksine 960334d087 moonraker: stop the background logger prior to exiting
This allows all records on the queue to be logged before exiting the program.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-31 15:30:30 -04:00
Arksine 005caba234 test_client: log metadata notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:40:56 -04:00
Arksine 2c5bb4710e websockets: Add metadata update notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:30:38 -04:00
Arksine bcb7e17105 extract_metadata: Set slicer type to "Unknown" if not able to detect
Signed-off-by:  Eric Callahan <akrsine.code@gmail.com>
2020-08-30 15:28:21 -04:00
Arksine 304e861a28 file_manager: refactor metadata extraction
Move logic for managine metadata to its own class.  Allow 3 retries if extraction fails, and send a printer event if metadata is updated due to an added file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-30 15:28:21 -04:00
Arksine 16269c1a49 temperature_store: correctly handle subscribed diffs
When processing a status update, default the temperature and target to the last received value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-29 14:12:23 -04:00
Arksine 9613bb01de extract_metadata: include "days" when calculating time for PrusaSlicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-28 14:26:08 -04:00
Arksine 5b87c43535 moonraker: send "client_info" after initial connection to Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-26 07:34:29 -04:00
Arksine d021eddb16 docs: Fix typo in readme
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-22 20:47:56 -04:00
Arksine 1aa12e4ff1 utils: Add support for a QueueLogger
Logging to a file has the potential to block a the main thread, a QueueLogger resolves this by forwarding logging request to a secondary thread.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-19 10:59:07 -04:00
Arksine 55919fc7d3 docs: update the PANELDUE_BEEP macro documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-18 08:59:32 -04:00
Arksine f338bccc3b paneldue: Add support for the piezo buzzer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-18 08:48:57 -04:00
Arksine 5a6f1ae062 websockets: don't handle ServerError in local callbacks
They can propogate back to the JSONRPC.execute_method() where they will be correctly handled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 20:16:03 -04:00
Arksine 8b02797ede test client: use 'gcode_move' in place of 'gcode'
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 19:56:42 -04:00
Arksine 2848b4e9c1 paneldue: 'gcode' status is now in 'gcode_move'
Also toolhead.status is no longer available, use idle_timeout.state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-17 19:55:53 -04:00
Arksine 88bbd66a3b docs: document latest API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 19:58:15 -04:00
Arksine a17e1d4056 test client: support "disconnect" notification
The webhooks module may now be used to retreive "ready" and "shutdown" state

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 279d53afde moonraker: rework klippy state events
Emit specific events for each klippy state rather than one for all of them.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 56bd9a61ea moonraker: reorganize initialization
This optimized version should initialize faster as it doesn't rely on an additional Periodic Callback when Klippy is detected as ready.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 76493215c5 moonraker: move klippy connection logic to its own class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine a3c0f06c5f docs: Update API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine f9f70ce989 test client: Update for compatibility with Klippy API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 8840434c7c paneldue: use klippy_apis module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-16 18:08:41 -04:00
Arksine 6fb4cdca62 termperature_store: use klippy_apis module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 4a57dba586 moonraker: update protocol for data received from klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 291f2b0e91 klippy_apis: new module replacing deprecated "gcode_apis"
Like gcode_apis, the klippy_apis module registers Web API aliases for particular gcodes.  In addition, this module presents an interface where moonraker can call Klippy APIs directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 14:19:19 -04:00
Arksine 43b057c40c moonraker: klippy requests no longer take a "request method"
Klippy rpc methods now accept either GET or POST, the method will be executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-15 08:38:06 -04:00
Arksine 5b6d4371c8 moonraker: convert missed legacy strings to f-strings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-13 19:23:17 -04:00
Arksine e9cd86f468 docs: add "confirmed_macros" option to paneldue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 17:53:17 -04:00
Arksine 7cae2f4aac paneldue: add confirmation box option to macros
This allows users to specify a "confirmed_macros" that wil pop up a message box requiring confirmation before proceeding.  Useful for restart and firmware_restart to prevent accidental execution.

Also do not raise an exception when Klippy disconnects after a restart or firmware_restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 17:25:54 -04:00
Arksine a7147a44ca moonraker: refactor "make_request"
The make_request() method is now awaitable and returns the result directly vs the previous behavior of returning a request that was awaited.

There is no longer a need to check the result to see if it is an error, exceptions are raised if an error is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-12 08:43:37 -04:00
Arksine d04a419a80 docs: Update documentation for 0.1 release
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 21:27:41 -04:00
Arksine e78a2e3e41 gcode_apis: handle restart exceptions
It is expected that the Klippy will disconnect when a restart request is sent.  Handle those exceptions so they return an acknowledgement.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 20:50:58 -04:00
Arksine 2c332a968f file_manager: require base paths be located within home directory
They however cannot be the home directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 20:34:20 -04:00
Arksine b3f02a73a4 extract_metadata: Improve error reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:59 -04:00
Arksine 1d520310ac utils: update git describe arguments
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:59 -04:00
Arksine 7cd22804dd moonraker: replace legacy string interpolation with f-strings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:28:41 -04:00
Arksine de1a79a7ca docs: update API documentation regarding file list notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:28 -04:00
Arksine 82fbee2bc0 test client: Update to handle new file list notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:27 -04:00
Arksine 7441da4b57 file_manager: refactor notify_filelist_changed()
This brings more consistency to the notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 14:21:27 -04:00
Arksine 6dc43f7e12 moonraker: replace "check_available" with "check_available_objects"
There "check_available" endpoint no longer exists in Klippy, so use "objects/list" instead.  If Klippy is not properly configured Moonraker will log the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 0775f3d0c6 moonraker: Connect to Klippy as a client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine e1addb16fd utils: remove unused SocketLoggingHandler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 62e5f85473 moonraker: use tornado's iostream wrapper for klippy connection
This reduces the amount of code needed to handle the connection and adds more robust error handling.   This also prepares moonraker for the eventual transition of Klippy hosting the server socket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine b92000dd46 moonraker: Use file_manager to update mutable endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine a4638f6c21 moonraker: Improve connection error logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 0abfc76871 temperature_store: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 470cc13b0e shell_command: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 6b45c0c1d8 power: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine f114985dc6 paneldue: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 52907155d2 machine: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:28 -04:00
Arksine 5853f3f447 gcode_apis: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine 98b3c990e0 file_manager: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine e5cb27f5b7 authorization: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine de462b1d0f app: Add configparser support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine 7a94fb3a6b moonraker: Add configparser support
Rather than receive its configuration from Klippy, moonraker will receive its configuration from a config file.  By default this file is located at ~/moonraker.conf.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-11 08:38:27 -04:00
Arksine e2850ee77e paneldue: fix incorrect default baudrate
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 21:10:30 -04:00
Arksine 9c76875896 file_manager: use print_stats to determine if an operation is safe
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 14:02:06 -04:00
Arksine d19737f4c5 moonraker: don't timeout requests to Klippy
Klippy requests typically only timeout when the connection between Klippy and the Server is disconnected.  Rather returning a timeout, send an error if there are any pending requests when a disconnection is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine d235139e6b paneldue: use the new "print_stats" module to check printing state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 4f97ebb28d test_client: Update to use new "print_stats" module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine f082d4dd44 paneldue: Update to fetch status from Klipper's print_stats object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
Arksine 89fa9ba47e gcode_apis: update "print start" API to use SDCARD_PRINT_FILE gcode
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-08-05 11:20:26 -04:00
21 changed files with 1747 additions and 1196 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
# Moonraker - API Web Server for Klipper
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use interact with Klipper. Communcation between
client applications may use to interact with Klipper. Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket.
Moonraker depends on Tornado for its server functionality. Moonraker
+123
View File
@@ -0,0 +1,123 @@
This document keeps a record of all changes to Moonraker's remote
facing APIs.
### 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"}
```
+56
View File
@@ -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.
+174 -145
View File
@@ -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,7 +47,8 @@ cd ~
git clone https://github.com/Arksine/moonraker.git
```
If you have an older version of moonraker installed, it must be removed:
If you have an experimental verison of moonraker that pre-dates this repo,
it must be uninstalled:
```
cd ~/moonraker/scripts
./uninstall-moonraker.sh
@@ -56,184 +62,207 @@ cd ~/moonraker/scripts
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
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:
## Klipper configuration (printer.cfg)
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]
[pause_resume]
[display_status]
[virtual_sdcard]
path: ~/gcode_files
```
NOTE: While Klipper does not set any hard limits on the location of the
`path` option for the `virtual_sdcard`, Moonraker requires that the path
be located within the HOME directory, it cannot however be the HOME
directory. If you wish to host your files elsewhere, use a symlink.
## Moonraker configuration (moonraker.conf)
All other configuration is done via `moonraker.conf`. If you are
familiar with Klipper, the configuration is similar. A basic
configuration might look like the following:
```
[server]
host: 0.0.0.0
port: 7125
enable_debug_logging: True
config_path: ~/.klippy_config
[authorization]
enabled: True
trusted_clients:
192.168.1.0/24
```
Note that while all items in the `[server]` and `[authorization]`
sections have default values, the sections must be present for
moonraker to start. Aside from the `config_path` and `trusted_clients`
options it is recommended to use default values.
Below is a detailed explanation of all options currently available:
```
#[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.
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
# to all interfaces
port: 7125
# The port the HTTP server will listen on. Default is 7125
klippy_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
enable_debug_logging: True
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is True. In the future this will change.
config_path:
# An optional path where configuration files are located. If specified,
# Moonraker will serve this path allowing file and directory manipulation
# within it. This path must be located within the user's HOME directory,
# by may not be the home directory itself. The default is no path, which
# results in no configuration files being served.
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
# a valid API key or originate from a trusted client. Default is True.
api_key_path: ~/.moonraker_api_key
# Path of the file that stores Moonraker's API key. The default is
# ~/.moonraker_api_key
trusted_clients:
192.168.1.30
192.168.1.0/24
# A list of newline separated ip addresses and/or ip ranges that are
# trusted. Trusted clients are given full access to the API. Both IPv4
# and IPv6 addresses and ranges are supported. Ranges must be expressed
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
# of the ip address must be 0. The default is no clients or ranges are
# trusted.
```
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.
For the moment, you need to restart the moonraker service to load a new
configuration:
```
sudo service moonraker restart
```
## Plugin Configuration
### Plugin Configuration
The core plugins are configured via the primary configuration above. Optional
plugins each need their own configuration as outlined below.
### PanelDue Plugin
#### PanelDue Plugin
```
[moonraker_plugin paneldue]
serial: /dev/ttyAMA0
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
# must be provided.
baud: 57600
machine_name: Voron 2
# 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
PREHEAT_CHAMBER
TURN_OFF_MOTORS
TURN_OFF_HEATERS
PANELDUE_BEEP FREQUENCY=500 DURATION=1
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:
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```
[gcode_macro PANELDUE_BEEP]
variable_sequence: 0
variable_frequency: 0
variable_duration: 0
# Beep frequency
default_parameter_FREQUENCY: 300
# Beep duration in seconds
default_parameter_DURATION: 1.
gcode:
{ printer.moonraker.action_call_remote_method(
"paneldue_beep", frequency=FREQUENCY|int,
duration=DURATION|float) }
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=frequency VALUE={FREQUENCY|int}
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=duration VALUE={DURATION|float}
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=sequence VALUE={printer["gcode_macro PANELDUE_BEEP"].sequence|int + 1}
```
### Power Control Plugin
#### Power Control Plugin
Power Plugin Configuration. One may use this module to toggle the
state of a relay using a linux GPIO, enabling the ability to power
a printer on/off regardless of Klippy's state. GPIOs are toggled
using linux sysfs.
```
[moonraker_plugin power]
[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
# A comma separated list of devices you wish to control. Device names may not
# contain whitespace. This parameter must be provided.
#
# Each device specified in "devices" should define its own set of the below
# options:
{dev}_name: Friendly Name
# An optional alias for the device. The default is the name specifed in
# "devices".
{dev}_pin: 23
# 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.
# The sysfs GPIO pin number you wish to control. This parameter must be
# provided.
{dev}_active_low: False
# When set to true the pin signal is inverted. Default is False.
```
Define the devices you wish to control under _devices_ with a comma separated
+143 -87
View File
@@ -40,13 +40,21 @@ that uses promises to return responses and errors (see json-rcp.js).
`{jsonrpc: "2.0", method: "get_printer_info", id: <request id>}`
- Returns:\
An object containing the build version, cpu info, and if the Klippy
process is ready for operation. The latter is useful when a client connects
after the klippy state event has been broadcast.
An object containing the build version, cpu info, Klippy's current state.
`{version: "<version>", cpu: "<cpu_info>", is_ready: <boolean>,
hostname: "<hostname>", error_detected: <boolean>,
message: "<current state message>"}`
```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>",
}
```
### Emergency Stop
- HTTP command:\
@@ -88,41 +96,16 @@ that uses promises to return responses and errors (see json-rcp.js).
`{jsonrpc: "2.0", method: "get_printer_objects_list", id: <request id>}`
- Returns:\
An object containing key, value pairs, where the key is the name of the
Klippy module available for status query, and the value is an array of
strings containing that module's available attributes.
An a list of "printer objects" that are currently available for query
or subscription. This list will be passed in an "objects" parameter.
```json
{ gcode: ["busy", "gcode_position", ...],
toolhead: ["position", "status"...], ...}
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
```
### Request currently subscribed objects:
- HTTP command:
`GET /printer/objects/subscription`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_objects_subscription", id: <request id>}`
- Returns:\
An object of the similar that above, however the format of the `result`
value is changed to include poll times:
```json
{ objects: {
gcode: ["busy", "gcode_position", ...],
toolhead: ["position", "status"...],
...},
poll_times: {
gcode: .25,
toolhead: .25,
...}
}
```
### Request the a status update for an object, or group of objects:
### Query the a status for an object, or group of objects:
- HTTP command:\
`GET /printer/objects/status?gcode`
`GET /printer/objects/query?gcode`
The above will fetch a status update for all gcode attributes. The query
string can contain multiple items, and specify individual attributes:
@@ -130,40 +113,66 @@ that uses promises to return responses and errors (see json-rcp.js).
`?gcode=gcode_position,busy&toolhead&extruder=target`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_objects_status", params:
{gcode: [], toolhead: ["position", "status"]}, id: <request id>}`
`{jsonrpc: "2.0", method: "get_printer_objects_query", params:
{objects: {gcode: [], toolhead: ["position", "status"]}},
id: <request id>}`
Note that an empty array will fetch all available attributes for its key.
- Returns:\
An object where the top level keys are the requested Klippy objects, as shown
below:
An object where the top level items are "eventtime" and "status". The
"status" item contains data about the requested update.
```json
{ gcode: {
busy: true,
gcode_position: [0, 0, 0 ,0],
...},
toolhead: {
position: [0, 0, 0, 0],
status: "Ready",
...},
...}
{
eventtime: <klippy time of update>,
status: {
gcode: {
busy: true,
gcode_position: [0, 0, 0 ,0],
...},
toolhead: {
position: [0, 0, 0, 0],
status: "Ready",
...},
...}
}
```
### Subscribe to a status request or a batch of status requests:
- HTTP command:\
`POST /printer/objects/subscription?gcode=gcode_position,bus&extruder=target`
`POST /printer/objects/subscribe?gcode=gcode_position,bus&extruder=target`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_objects_subscription", params:
{gcode: [], toolhead: ["position", "status"]}, id: <request id>}`
`{jsonrpc: "2.0", method: "post_printer_objects_subscribe", params:
{objects: {gcode: [], toolhead: ["position", "status"]}},
id: <request id>}`
- Returns:\
An acknowledgement that the request has been received:
Status data for all currently subscribed objects, with the format matching that of
the `/printer/objects/query`:
`ok`
```json
{
eventtime: <klippy time of update>,
status: {
gcode: {
busy: true,
gcode_position: [0, 0, 0 ,0],
...},
toolhead: {
position: [0, 0, 0, 0],
status: "Ready",
...},
...}
}
```
Note that Moonraker's current behavior is maintain a superset of all client
subscriptions, thus you may received data for objects that you did not
request. This behavior is subject to change in the future (where each
client receives only the subscriptions it requested).
The actual status updates will be sent asynchronously over the websocket.
Future updates for subscribed objects are sent asynchronously over the
websocket. See the `notify_status_update` notification for details.
### Query Endstops
- HTTP command:\
@@ -662,11 +671,16 @@ Printer generated events are sent over the websocket as JSON-RPC 2.0
notifications. These notifications are sent to all connected clients
in the following format:
`{jsonrpc: "2.0", method: <event method name>, params: [<event state>]}`
`{jsonrpc: "2.0", method: <event method name>}`
It is important to keep in mind that the `params` value will always be
OR
`{jsonrpc: "2.0", method: <event method name>, params: [<event parameter>]}`
If a notification has parameters, the `params` value will always be
wrapped in an array as directed by the JSON-RPC standard. Currently
all notifications available are broadcast with a single parameter.
all notifications available are broadcast with either no parameters
or a single parameter.
### Gcode response:
All calls to gcode.respond() are forwarded over the websocket. They arrive
@@ -680,21 +694,12 @@ Status Subscriptions arrive as a "notify_status_update" notification:
`{jsonrpc: "2.0", method: "notify_status_update", params: [<status_data>]}`
The structure of the status data is identical to the structure that is
returned from a status request.
returned from an object query's "status" attribute.
### Klippy Process State Changed:
The following Klippy state changes are broadcast over the websocket:
- ready
- disconnect
- shutdown
### Klippy Disconnected:
Notify clients when Moonraker's connection to Klippy has terminated
Note that Klippy's "ready" is different from the Printer's "ready". The
Klippy "ready" state is broadcast upon startup after initialization is
complete. It should also be noted that the websocket will be disconnected
after the "disconnect" state, as that notification is broadcast prior to a
restart. Klippy State notifications are broadcast in the following format:
`{jsonrpc: "2.0", method: "notify_klippy_state_changed", params: [<state>]}`
`{jsonrpc: "2.0", method: "notify_klippy_disconnected"}`
### File List Changed
When a client makes a change to the virtual sdcard file list
@@ -704,21 +709,73 @@ clients of the change:
`{jsonrpc: "2.0", method: "notify_filelist_changed",
params: [<file changed info>]}`
The <file changed info> param is an object in the following format:
The <file changed info> param is an object in the following format, where
the "action" is the operation that prompted the change, and the "item"
contains information about the item that has changed:
```json
{action: "<action>", filename: "<file_name>", root: "<root_name>"}
{action: "<action>",
item: {
path: "<file or directory path>",
root: "<root_name>",
size: <file size>,
modified: "<date modified>"
}
```
Note that file move/copy actions also include the name and root of the
previous/source file:
Note that file move and copy actions also include a "source item" that
contains the path and root of the source file or directory.
```json
{action: "<action>", filename: "<file_name>", root: "<root_name>",
prev_file: "<previous file name>", prev_root: "<previous_root_name>"}
{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>"
}
}
```
The `action` is the operation that resulted in a file list change, the `filename`
is the name of the file the action was performed on, and the `filelist` is the current
file list, returned in the same format as `get_file_list`.
The following `actions` are currently available:
- `upload_file`
- `delete_file`
- `create_dir`
- `delete_dir`
- `move_item`
- `copy_item`
### Metadata Update
When a new file is uploaded via the API a websocket notification is broadcast
to all connected clients after parsing is complete:
`{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>
}, ...
]
}
```
# Appendix
@@ -753,15 +810,14 @@ the websocket:
status.
- If the response returns an error (such as 404), set a timeout for
2 seconds and try again.
- If the response returns success, check the result's `is_ready` attribute
to determine if Klipper is ready.
- If Klipper is ready you may proceed to request status of printer objects
- If the response returns success, check the result's `state` attribute
- If `state == "ready"` you may proceed to request status of printer objects
make subscriptions, get the file list, etc.
- If not ready check `error_detected` to see if Klippy has experienced an
error.
- If `state == "error"` then Klippy has experienced an error
- If an error is detected it might be wise to prompt the user. You can
get a description of the error from the `message` attribute
- If no error then re-request printer info in 2s.
get a description of the error from the `state_message` attribute
- If `state == "shutdown"` then Klippy is in a shutdown state.
- If `state == "startup"` then re-request printer info in 2s.
- Repeat step 2s until Klipper reports ready. T
- Client's should watch for the `notify_klippy_state_changed` event. If it reports
disconnected then Klippy has either been stopped or restarted. In this
+37 -42
View File
@@ -21,7 +21,7 @@ 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"
]
@@ -34,8 +34,10 @@ def _status_parser(request):
for v in vals:
if v:
parsed += v.decode().split(',')
if parsed == []:
parsed = None
args[key] = parsed
return args
return {'objects': args}
# Built-in Query String Parser
def _default_parser(request):
@@ -77,7 +79,7 @@ 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,
@@ -91,20 +93,23 @@ class APIDefinition:
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 = []
# 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)
enable_cors = config.getboolean('enable_cors', False)
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
app_handlers = [
@@ -112,18 +117,19 @@ class MoonrakerApp:
(r"/websocket", WebSocket,
{'wsm': self.wsm, 'auth': self.auth}),
(r"/api/version", EmulateOctoprintHandler,
{'server': server, 'auth': self.auth})]
{'server': self.server, 'auth': self.auth})]
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)
enable_cors=enable_cors)
self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers
self.register_static_file_handler("moonraker.log", args.logfile)
logfile = config['cmd_args'].get('logfile')
self.register_static_file_handler("moonraker.log", logfile)
self.auth.register_handlers(self)
def listen(self, host, port):
@@ -137,11 +143,6 @@ class MoonrakerApp:
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
@@ -150,13 +151,13 @@ class MoonrakerApp:
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))
logging.info(
f"Registering remote endpoint: "
f"({' '.join(api_def.request_methods)}) {api_def.uri}")
self.wsm.register_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(
@@ -169,8 +170,9 @@ class MoonrakerApp:
return
api_def = self._create_api_definition(
uri, ws_method, request_methods)
logging.info("Registering local endpoint: (%s) %s" % (
" ".join(request_methods), uri))
logging.info(
f"Registering local endpoint: "
f"({' '.join(request_methods)}) {uri}")
if not http_only:
self.wsm.register_handler(api_def, callback)
params = {}
@@ -193,8 +195,9 @@ class MoonrakerApp:
pattern += "/"
pattern += "(.*)"
else:
logging.info("Invalid file path: %s" % (file_path))
logging.info(f"Invalid file path: {file_path}")
return
logging.debug(f"Registering static file: ({pattern}) {file_path}")
methods = ['GET']
if can_delete:
methods.append('DELETE')
@@ -234,35 +237,27 @@ class MoonrakerApp:
# ***** Dynamic Handlers*****
class RemoteRequestHandler(AuthorizedRequestHandler):
def initialize(self, remote_callback, server, auth,
methods, arg_parser):
def initialize(self, remote_callback, server, auth, arg_parser):
super(RemoteRequestHandler, self).initialize(server, auth)
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):
async def _process_http_request(self):
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):
try:
result = await self.server.make_request(
self.remote_callback, args)
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):
@@ -299,7 +294,7 @@ class LocalRequestHandler(AuthorizedRequestHandler):
result = await self.callback(self.request.path, method, args)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e))
e.status_code, str(e)) from e
self.finish({'result': result})
@@ -317,7 +312,7 @@ class FileRequestHandler(AuthorizedFileHandler):
# 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:
@@ -342,7 +337,7 @@ class FileRequestHandler(AuthorizedFileHandler):
base = self.request.path.lstrip("/").split("/")[2]
filename = self.path.lstrip("/")
file_manager = self.server.lookup_plugin('file_manager')
file_manager.notify_filelist_changed(filename, 'removed', base)
file_manager.notify_filelist_changed('delete_file', filename, base)
self.finish({'result': filename})
class FileUploadHandler(AuthorizedRequestHandler):
+45 -54
View File
@@ -11,56 +11,57 @@ import ipaddress
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 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])
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\n"
f"Trusted Clients:\n{t_clients}")
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(
@@ -79,33 +80,23 @@ class Authorization:
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 +114,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 +136,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 +159,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
+87
View File
@@ -0,0 +1,87 @@
# 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 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, cmd_line_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
cmd_line_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['cmd_args'] = {'logfile': cmd_line_args.logfile}
return ConfigHelper(server, config, 'server')
+310 -298
View File
@@ -11,20 +11,21 @@ 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
from tornado import iostream
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',
'file_manager', 'klippy_apis', 'machine',
'temperature_store', 'shell_command']
class Sentinel:
@@ -33,74 +34,80 @@ 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.init_list = []
self.init_attempts = 0
self.klippy_state = "disconnected"
# XXX - currently moonraker maintains a superset of all
# subscriptions, the results of which are forwarded to all
# connected websockets. A better implementation would open a
# unique unix domain socket for each websocket client and
# allow Klipper to forward only those subscriptions back to
# correct client.
self.all_subscriptions = {}
# 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
for plugin in CORE_PLUGINS:
self.load_plugin(plugin)
self.ioloop = IOLoop.current()
# 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.register_remote_method(
'set_klippy_shutdown', self._set_klippy_shutdown)
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)
# Plugin initialization
self.plugins = {}
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
self._load_plugins(config)
def start(self):
logging.info(
"Starting Moonraker on (%s, %d)" %
(self.host, self.port))
f"Starting Moonraker on ({self.host}, {self.port})")
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(config.sections()) - \
set(['server', 'authorization', 'cmd_args'])
for section in opt_sections:
self.load_plugin(config[section], 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)
@@ -108,21 +115,21 @@ class Server:
module = importlib.import_module("plugins." + plugin_name)
try:
load_func = getattr(module, "load_plugin")
plugin = load_func(self)
plugin = load_func(config)
except Exception:
msg = "Unable to load plugin (%s)" % (plugin_name)
msg = f"Unable to load plugin ({plugin_name})"
logging.info(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,221 +138,209 @@ 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):
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
# ***** 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):
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()
return
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''
def process_command(self, cmd):
method = cmd.get('method', None)
if method is not None:
# This is a remote method called from klippy
cb = self.remote_methods.get(method, None)
if cb is not None:
params = cmd.get('params', {})
cb(**params)
else:
return
if data == b'':
# Socket Closed
self.close_client_sock()
logging.info(f"Unknown method received: {method}")
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()))
# 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)
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 = {}
logging.info("Klippy Connection Removed")
self.send_event("server:klippy_disconnect")
self.ioloop.call_later(.25, self._connect_klippy)
async def _initialize(self):
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:
# Moonraker is enabled in the Klippy module
# and Klippy is ready. We can stop the init
# procedure.
self.init_attempts = 0
else:
self.init_attempts += 1
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")
# Update filemanager fixed paths
fixed_paths = {k: result[k] for k in
['klipper_path', 'python_path',
'log_file', 'config_file']}
file_manager = self.lookup_plugin('file_manager')
file_manager.update_fixed_paths(fixed_paths)
is_ready = result.get('state', "") == "ready"
if is_ready:
await self._verify_klippy_requirements()
logging.info("Klippy ready")
self.klippy_state = "ready"
self.init_list.append('klippy_ready')
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, can_delete=True)
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):
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
self.send_event("server:status_update", status)
def make_request(self, path, method, args):
timeout = self.long_running_requests.get(path, self.request_timeout)
async def make_request(self, rpc_method, params):
# XXX - This adds the "response_template" to a subscription
# request and tracks all subscriptions so that each
# client gets what its requesting. In the future we should
# track subscriptions per client and send clients only
# the data they are asking for.
if rpc_method == "objects/subscribe":
for obj, items in params.get('objects', {}).items():
if obj in self.all_subscriptions:
pi = self.all_subscriptions[obj]
if items is None or pi is None:
self.all_subscriptions[obj] = None
else:
uitems = list(set(pi) | set(items))
self.all_subscriptions[obj] = uitems
else:
self.all_subscriptions[obj] = items
params['objects'] = dict(self.all_subscriptions)
params['response_template'] = {'method': "process_status_update"}
if path == "gcode/script":
script = args.get('script', "")
base_gc = script.strip().split()[0].upper()
timeout = self.long_running_gcodes.get(base_gc, timeout)
base_request = BaseRequest(path, method, args, timeout)
base_request = BaseRequest(rpc_method, params)
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)
result = await base_request.wait()
return result
async def _kill_server(self):
async def _stop_server(self):
# XXX - Currently this function is not used.
# Should I expose functionality to shutdown
# or restart the server, or simply remove this?
@@ -354,57 +349,92 @@ class Server:
for plugin in self.plugins:
if hasattr(plugin, "close"):
await plugin.close()
self.close_client_sock()
self.close_server_sock()
self.klippy_connection.close()
if self.server_running:
self.server_running = False
await self.moonraker_app.close()
self.io_loop.stop()
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")
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
def close_server_sock(self):
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,53 +442,33 @@ 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()
# 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)
ql = utils.setup_logging(log_file)
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
@@ -467,7 +477,8 @@ def main():
server = Server(cmd_line_args)
except Exception:
logging.exception("Moonraker Error")
return
ql.stop()
exit(1)
try:
server.start()
io_loop.start()
@@ -475,6 +486,7 @@ def main():
logging.exception("Server Running Error")
io_loop.close(True)
logging.info("Server Shutdown")
ql.stop()
if __name__ == '__main__':
+202 -147
View File
@@ -18,12 +18,14 @@ METADATA_SCRIPT = 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)
@@ -43,50 +45,66 @@ class FileManager:
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")
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
if config_path is not None:
ret = self.register_directory(
'config', config_path, can_delete=True)
if not ret:
raise config.error(
"Option 'config_path' is not a valid directory")
def update_fixed_paths(self, paths):
if paths == self.fixed_path_args:
# No change in fixed paths
return
self.fixed_path_args = dict(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)
self.register_directory("config_examples", example_cfg_path)
# Register log path
log_file = paths.get('log_file')
log_path = os.path.normpath(os.path.expanduser(log_file))
self.server.register_static_file_handler("klippy.log", log_path)
def register_directory(self, base, path, can_delete=False):
op_check_cb = None
if base == 'gcodes':
op_check_cb = self._handle_operation_check
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 ({base}) not valid. Please\n"
"check that the path exists and is a subfolder in the HOME\n"
"directory. Note that the path may not BE the home directory.")
return False
if path != self.file_paths.get(base, ""):
self.file_paths[base] = path
self.server.register_static_file_handler(
base, path, can_delete=can_delete, op_check_cb=op_check_cb)
try:
self._update_file_list(base='config_examples')
self._update_file_list(base=base)
except Exception:
logging.exception(
"Unable to initialize config_examples file list")
f"Unable to initialize file list: <{base}>")
return True
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
def get_fixed_path_args(self):
return dict(self.fixed_path_args)
async def _handle_filelist_request(self, path, method, args):
root = args.get('root', "gcodes")
return self.get_file_list(format_list=True, base=root)
@@ -96,7 +114,7 @@ class FileManager:
metadata = self.gcode_metadata.get(requested_file)
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
@@ -113,7 +131,7 @@ class FileManager:
os.mkdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed(url_path, "add_directory", base)
self.notify_filelist_changed("create_dir", url_path, base)
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == base:
@@ -121,7 +139,7 @@ class FileManager:
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
"Directory does not exist (%s)" % (directory))
f"Directory does not exist ({directory})")
force = args.get('force', False)
if isinstance(force, str):
force = force.lower() == "true"
@@ -135,38 +153,37 @@ class FileManager:
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", url_path, base)
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("/")
if not parts:
raise self.server.error("Invalid path: " % (url_path))
raise self.server.error(f"Invalid path: {url_path}")
base = parts[0]
if base not in self.file_paths:
raise self.server.error("Invalid base path (%s)" % (base))
raise self.server.error(f"Invalid base path ({base})")
root_path = local_path = self.file_paths[base]
url_path = ""
if len(parts) > 1:
@@ -186,112 +203,75 @@ class FileManager:
dest_base, dst_url_path, dest_path = self._convert_path(destination)
if dest_base not in FULL_ACCESS_ROOTS:
raise self.server.error(
"Destination path is read-only: %s" % (dest_base))
f"Destination path is read-only: {dest_base}")
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 = ""
action = op_result = ""
if path == "/server/files/move":
if source_base 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_base}")
# 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"
action = "move_item"
elif path == "/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_url_path = os.path.join(
dst_url_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_url_path, dest_base,
{'path': src_url_path, 'root': source_base})
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')
def _get_path_info(self, path):
modified = time.ctime(os.path.getmtime(path))
size = os.path.getsize(path)
path_info = {'modified': modified, 'size': size}
return path_info
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'):
def _update_file_list(self, base='gcodes', do_notify=False):
# Use os.walk find files in sd path and subdirs
path = self.file_paths.get(base, None)
if path is None:
msg = "No known path for root: %s" % (base)
msg = f"No known path for root: {base}"
logging.info(msg)
raise self.server.error(msg)
elif not os.path.isdir(path):
msg = "Cannot generate file list for root: %s" % (base)
msg = f"Cannot generate file list for root: {base}"
logging.info(msg)
raise self.server.error(msg)
logging.info("Updating File List <%s>..." % (base))
logging.info(f"Updating File List <{base}>...")
new_list = {}
for root, dirs, files in os.walk(path, followlinks=True):
for name in files:
@@ -300,13 +280,10 @@ class FileManager:
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}
new_list[r_path] = self._get_path_info(full_path)
self.file_lists[base] = new_list
if base == 'gcodes':
ioloop = IOLoop.current()
ioloop.spawn_callback(self._update_metadata)
self.gcode_metadata.refresh_metadata(new_list, path, do_notify)
return dict(new_list)
async def process_file_upload(self, request):
@@ -317,7 +294,7 @@ 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):
@@ -344,23 +321,23 @@ class FileManager:
self._write_file(upload)
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):
@@ -393,7 +370,7 @@ class FileManager:
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(base_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'],
@@ -446,7 +423,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 +431,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 = []
@@ -472,19 +449,97 @@ class FileManager:
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))
raise self.server.error(f"Invalid file path: {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))
raise self.server.error(f"Invalid file path: {path}")
os.remove(full_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)
def notify_filelist_changed(self, action, fname, base, source_item={}):
self._update_file_list(base, do_notify=True)
file_info = dict(self.file_lists[base].get(
fname, {'size': 0, 'modified': ""}))
file_info.update({'path': fname, 'root': base})
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)
class MetadataStorage:
def __init__(self, server):
self.server = server
self.lock = Lock()
self.metadata = {}
self.script_response = None
def get(self, key, default=None):
return self.metadata.get(key, default)
def __getitem__(self, key):
return 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 refresh_metadata(self, filelist, gc_path, do_notify=False):
IOLoop.current().spawn_callback(
self._do_metadata_update, filelist, gc_path, do_notify)
async def _do_metadata_update(self, filelist, gc_path, do_notify=False):
async with self.lock:
exisiting_data = {}
update_list = []
for fname, fdata in filelist.items():
mdata = self.metadata.get(fname, {})
if mdata.get('size', "") == fdata.get('size') \
and mdata.get('modified', "") == fdata.get('modified'):
# file metadata has already been extracted
exisiting_data[fname] = mdata
else:
update_list.append(fname)
self.metadata = exisiting_data
for fname in update_list:
retries = 3
while retries:
try:
await self._extract_metadata(fname, gc_path, do_notify)
except Exception:
logging.exception("Error running extract_metadata.py")
retries -= 1
else:
break
else:
logging.info(
f"Unable to extract medatadata from file: {fname}")
async def _extract_metadata(self, filename, path, do_notify=False):
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
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']
self.metadata[path] = dict(metadata)
metadata['filename'] = path
if do_notify:
self.server.send_event(
"file_manager:metadata_update", metadata)
def load_plugin(config):
return FileManager(config)
-67
View File
@@ -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)
+139
View File
@@ -0,0 +1,139 @@
# 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
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"
class Sentinel:
pass
class KlippyAPI:
def __init__(self, config):
self.server = config.get_server()
# Register GCode Aliases
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 _gcode_pause(self, path, method, args):
return await self.run_gcode("PAUSE")
async def _gcode_resume(self, path, method, args):
return await self.run_gcode("RESUME")
async def _gcode_cancel(self, path, method, args):
return await self.run_gcode("CANCEL_PRINT")
async def _gcode_start_print(self, path, method, args):
filename = args.get('filename')
return await self.start_print(filename)
async def _gcode_restart(self, path, method, args):
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, path, method, args):
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(self, method, params, default=Sentinel):
try:
result = await self.server.make_request(method, params)
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 = "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):
params = {'objects': objects}
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)
def load_plugin(config):
return KlippyAPI(config)
+5 -5
View File
@@ -6,8 +6,8 @@
import logging
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)
@@ -27,8 +27,8 @@ class Machine:
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception("Error running cmd '%s'" % (cmd))
logging.exception(f"Error running cmd '{cmd}'")
return "ok"
def load_plugin(server):
return Machine(server)
def load_plugin(config):
return Machine(config)
+173 -130
View File
@@ -9,9 +9,8 @@ import time
import json
import errno
import logging
import tempfile
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 +19,19 @@ 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 +49,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 +57,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,13 +126,14 @@ 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
@@ -152,26 +142,53 @@ class PanelDue:
# 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.beep_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)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
@@ -193,50 +210,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 +232,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 +257,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,18 +280,32 @@ 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
if "gcode_macro PANELDUE_BEEP" in status:
# This only processes a paneldue beep when the macro's
# variables have changed
params = self.printer_state["gcode_macro PANELDUE_BEEP"]
try:
self.handle_paneldue_beep(**params)
except Exception:
logging.exception("Unable to process PANELDUE_BEEP")
def handle_paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
{'beep_freq': frequency, 'beep_length': duration})
def handle_paneldue_beep(self, sequence, frequency, duration):
if sequence != self.beep_sequence:
self.beep_sequence = sequence
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, 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
@@ -323,7 +324,7 @@ class PanelDue:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
msg += f" Line Number: {line_no}"
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
@@ -335,7 +336,7 @@ class PanelDue:
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg = " Line Number: %d" % line_no
msg += f" Line Number: {line_no}"
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
@@ -355,7 +356,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 +370,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 +405,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 +413,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 +472,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 +502,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 +522,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 +556,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 +590,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 +618,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
@@ -630,12 +672,13 @@ class PanelDue:
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
@@ -681,5 +724,5 @@ class PanelDue:
async def close(self):
self.ser_conn.disconnect()
def load_plugin(server):
return PanelDue(server)
def load_plugin(config):
return PanelDue(config)
+31 -45
View File
@@ -10,8 +10,8 @@ from tornado.ioloop import IOLoop
from tornado import gen
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'],
self._handle_list_devices)
@@ -27,6 +27,22 @@ class PrinterPower:
self.current_dev = None
self.devices = {}
dev_names = config.get('devices')
dev_names = [d.strip() for d in dev_names.split(',') if d.strip()]
logging.info("Power plugin loading devices: " + str(dev_names))
devices = {}
for dev in dev_names:
pin = config.getint(dev + "_pin")
name = config.get(dev + "_name", dev)
active_low = config.getboolean(dev + "_active_low", False)
devices[dev] = {
"name": name,
"pin": pin,
"active_low": int(active_low),
"status": None
}
ioloop = IOLoop.current()
ioloop.spawn_callback(self.initialize_devices, devices)
async def _handle_list_devices(self, path, method, args):
output = {"devices": []}
@@ -65,47 +81,17 @@ class PrinterPower:
result[dev] = self.devices[dev]["status"]
return result
def load_config(self, config):
if "devices" not in config:
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)
async def initialize_devices(self, devices):
for name, device in devices.items():
try:
logging.debug(
"Attempting to configure pin GPIO%d"
% (device["pin"]))
f"Attempting to configure pin GPIO{device['pin']}")
await GPIO.setup_pin(device["pin"], device["active_low"])
device["status"] = GPIO.is_pin_on(device["pin"])
except Exception:
logging.exception(
"Power plugin: ERR Problem configuring the output pin for"
" device %s. Removing device" % (name))
self.devices.pop(name, None)
f"Power plugin: ERR Problem configuring the output pin for"
f" device {name}. Removing device")
continue
self.devices[name] = device
@@ -113,16 +99,16 @@ class GPIO:
gpio_root = "/sys/class/gpio"
@staticmethod
def _set_gpio_option(gpio, option, value):
def _set_gpio_option(pin, option, value):
GPIO._write(
os.path.join(GPIO.gpio_root, "gpio%d" % (gpio), option),
os.path.join(GPIO.gpio_root, f"gpio{pin}", option),
value
)
@staticmethod
def _get_gpio_option(pin, option):
return GPIO._read(
os.path.join(GPIO.gpio_root, "gpio%d" % (pin), option)
os.path.join(GPIO.gpio_root, f"gpio{pin}", option)
)
@staticmethod
@@ -139,9 +125,9 @@ class GPIO:
@staticmethod
async def verify_pin(pin, active_low=1):
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
if not os.path.exists(gpiopath):
logging.info("Re-intializing GPIO%d" % (pin))
logging.info(f"Re-intializing GPIO{pin}")
await GPIO.setup_pin(pin, active_low)
return
@@ -156,14 +142,14 @@ class GPIO:
pin = int(pin)
active_low = 1 if active_low == 1 else 0
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
if not os.path.exists(gpiopath):
GPIO._write(
os.path.join(GPIO.gpio_root, "export"),
pin)
logging.info("Waiting for GPIO%d to initialize" % (pin))
logging.info(f"Waiting for GPIO{pin} to initialize")
while os.stat(os.path.join(
GPIO.gpio_root, "gpio%d" % (pin),
GPIO.gpio_root, f"gpio{pin}",
"active_low")).st_gid == 0:
await gen.sleep(.1)
@@ -184,5 +170,5 @@ class GPIO:
GPIO._set_gpio_option(pin, "value", value)
def load_plugin(server):
return PrinterPower(server)
def load_plugin(config):
return PrinterPower(config)
+4 -4
View File
@@ -50,7 +50,7 @@ class ShellCommand:
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except Exception:
logging.exception(
"shell_command: Command {%s} failed" % (self.name))
f"shell_command: Command ({self.name}) failed")
return
if verbose:
fd = proc.stdout.fileno()
@@ -74,9 +74,9 @@ 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"
else:
msg = "Command {%s} timed out" % (self.name)
msg = f"Command ({self.name}) timed out"
logging.info(msg)
self.io_loop.remove_handler(fd)
@@ -84,5 +84,5 @@ class ShellCommandFactory:
def build_shell_command(self, cmd, callback):
return ShellCommand(cmd, callback)
def load_plugin(server):
def load_plugin(config):
return ShellCommandFactory()
+24 -24
View File
@@ -11,8 +11,8 @@ TEMPERATURE_UPDATE_MS = 1000
TEMPERATURE_STORE_SIZE = 20 * 60
class TemperatureStore:
def __init__(self, server):
self.server = server
def __init__(self, config):
self.server = config.get_server()
# Temperature Store Tracking
self.last_temps = {}
@@ -24,36 +24,32 @@ 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:klippy_ready", self._init_sensors)
# Register endpoint
self.server.register_endpoint(
"/server/temperature_store", "server_temperature_store", ['GET'],
self._handle_temp_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 +58,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 +77,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
@@ -98,5 +98,5 @@ class TemperatureStore:
async def close(self):
self.temp_update_cb.stop()
def load_plugin(server):
return TemperatureStore(server)
def load_plugin(config):
return TemperatureStore(config)
+31 -18
View File
@@ -4,30 +4,28 @@
#
# 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):
@@ -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):
root_logger = logging.getLogger()
queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
file_hdlr = MoonrakerLoggingHandler(
log_file, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(queue, file_hdlr)
listener.start()
return listener
+29 -26
View File
@@ -11,6 +11,9 @@ from tornado.ioloop import IOLoop
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from utils import ServerError
class Sentinel:
pass
class JsonRPC:
def __init__(self):
self.methods = {}
@@ -26,7 +29,7 @@ class JsonRPC:
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)
@@ -72,11 +75,12 @@ class JsonRPC:
result = await method(*args, **kwargs)
except TypeError as e:
return self.build_error(-32603, "Invalid params", 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)
@@ -104,16 +108,18 @@ class WebsocketManager:
# Register events
self.server.register_event_handler(
"server:klippy_state_changed", self._handle_klippy_state_changed)
"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)
async def _handle_klippy_state_changed(self, state):
await self.notify_websockets("klippy_state_changed", state)
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)
@@ -124,6 +130,9 @@ class WebsocketManager:
async def _handle_filelist_changed(self, flist):
await self.notify_websockets("filelist_changed", flist)
async def _handle_metadata_update(self, metadata):
await self.notify_websockets("metadata_update", metadata)
def register_handler(self, api_def, callback=None):
for r_method in api_def.request_methods:
cmd = r_method.lower() + '_' + api_def.ws_method
@@ -133,28 +142,22 @@ class WebsocketManager:
api_def.endpoint, r_method, callback)
else:
# Callback is a remote method
rpc_cb = self._generate_callback(api_def.endpoint, r_method)
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(cmd, rpc_cb)
def remove_handler(self, ws_method):
for prefix in ["get", "post", "delete"]:
self.rpc.remove_method(prefix + "_" + ws_method)
def _generate_callback(self, endpoint, request_method):
def _generate_callback(self, endpoint):
async def func(**kwargs):
request = self.server.make_request(
endpoint, request_method, kwargs)
result = await request.wait()
result = await self.server.make_request(endpoint, kwargs)
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
result = await callback(endpoint, request_method, kwargs)
return result
return func
@@ -164,29 +167,29 @@ class WebsocketManager:
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)
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]
notification = json.dumps(msg)
async with self.ws_lock:
for ws in list(self.websockets.values()):
try:
ws.write_message(notification)
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:
+46 -35
View File
@@ -10,6 +10,7 @@ import re
import os
import sys
import time
import traceback
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
@@ -94,7 +95,8 @@ class PrusaSlicer(BaseSlicer):
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)]
time_patterns = [(r"\d+d", 24*60*60), (r"\d+h", 60*60),
(r"\d+m", 60), (r"\d+s", 1)]
for pattern, multiplier in time_patterns:
t = _regex_find_ints(pattern, time_match)
if t:
@@ -113,13 +115,13 @@ 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],
@@ -291,43 +293,52 @@ SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails']
def extract_metadata(file_path, log):
metadata = {}
slicers = [s() for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = time.ctime(os.path.getmtime(file_path))
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
else:
metadata['slicer'] = "Unknown"
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()
+87 -68
View File
@@ -45,14 +45,14 @@ var api = {
method: "get_printer_objects_list"
},
object_status: {
url: "/printer/objects/status",
method: "get_printer_objects_status"
url: "/printer/objects/query",
method: "get_printer_objects_query"
},
object_subscription: {
url: "/printer/objects/subscription",
url: "/printer/objects/subscribe",
method: {
post: "post_printer_objects_subscription",
get: "get_printer_objects_subscription"
post: "post_printer_objects_subscribe",
get: "get_printer_objects_subscribe"
},
},
temperature_store: {
@@ -218,6 +218,28 @@ function update_error(cmd, msg) {
update_term("Command [" + cmd + "] resulted in an error: " + msg);
console.log("Error processing " + cmd +": " + msg);
}
function handle_klippy_state(state) {
// Klippy state can be "ready", "disconnect", and "shutdown". This
// differs from Printer State in that it represents the status of
// the Host software
switch(state) {
case "ready":
// It would be possible to use this event to notify the
// client that the printer has started, however the server
// may not start in time for clients to receive this event.
// It is being kept in case
if (!klippy_ready)
update_term("Klippy Ready");
break;
case "shutdown":
// Either M112 was entered or there was a printer error. We
// probably want to notify the user and disable certain controls.
klippy_ready = false;
update_term("Klipper has shutdown, check klippy.log for info");
break;
}
}
//***********End UI Update Functions****************/
//***********Websocket-Klipper API Functions (JSON-RPC)************/
@@ -243,11 +265,11 @@ function get_klippy_info() {
json_rpc.call_method(api.printer_info.method)
.then((result) => {
if (result.is_ready) {
if (result.state == "ready") {
if (!klippy_ready) {
update_term("Klippy Hostname: " + result.hostname +
" | CPU: " + result.cpu +
" | Build Version: " + result.version);
" | CPU: " + result.cpu_info +
" | Build Version: " + result.software_version);
klippy_ready = true;
// Klippy has transitioned from not ready to ready.
// It is now safe to fetch the file list.
@@ -257,22 +279,25 @@ function get_klippy_info() {
if ($("#cbxSub").is(":checked")) {
// If autosubscribe is check, request the subscription now
const sub = {
gcode: ["gcode_position", "speed", "speed_factor", "extrude_factor"],
idle_timeout: [],
pause_resume: [],
toolhead: [],
virtual_sdcard: [],
heater_bed: [],
extruder: ["temperature", "target"],
fan: []};
objects: {
gcode_move: ["gcode_position", "speed", "speed_factor", "extrude_factor"],
idle_timeout: null,
pause_resume: null,
toolhead: null,
virtual_sdcard: null,
heater_bed: null,
extruder: ["temperature", "target"],
fan: null,
print_stats: null}
};
add_subscription(sub);
} else {
get_status({idle_timeout: [], pause_resume: []});
get_status({idle_timeout: null, pause_resume: null});
}
}
} else {
if (result.error_detected) {
update_term(result.message);
if (result.state == "error") {
update_term(result.state_message);
} else {
update_term("Waiting for Klippy ready status...");
}
@@ -285,6 +310,9 @@ function get_klippy_info() {
})
.catch((error) => {
update_error(api.printer_info.method, error);
setTimeout(() => {
get_klippy_info();
}, 2000);
});
}
@@ -337,7 +365,7 @@ function get_status(printer_objects) {
});
}
function get_object_info() {
function get_object_list() {
json_rpc.call_method(api.object_list.method)
.then((result) => {
// result will be a dictionary containing all available printer
@@ -353,8 +381,8 @@ function add_subscription(printer_objects) {
json_rpc.call_method_with_kwargs(
api.object_subscription.method.post, printer_objects)
.then((result) => {
// result is simply an "ok" acknowledgement that subscriptions
// have been added for requested objects
// result is the the state from all fetched data
handle_status_update(result.status)
console.log(result);
})
.catch((error) => {
@@ -522,7 +550,7 @@ function handle_status_update(status) {
let full_name = name + "." + attr;
let val = obj[attr];
switch(full_name) {
case "virtual_sdcard.filename":
case "print_stats.filename":
$('#filename').prop("hidden", val == "");
$('#filename').text("Loaded File: " + val);
break;
@@ -547,6 +575,8 @@ function handle_status_update(status) {
update_streamdiv(name, attr, val);
}
break;
case "webhooks.state":
handle_klippy_state(val);
default:
update_streamdiv(name, attr, val);
@@ -556,50 +586,35 @@ function handle_status_update(status) {
}
json_rpc.register_method("notify_status_update", handle_status_update);
function handle_klippy_state(state) {
// Klippy state can be "ready", "disconnect", and "shutdown". This
// differs from Printer State in that it represents the status of
// the Host software
switch(state) {
case "ready":
// It would be possible to use this event to notify the
// client that the printer has started, however the server
// may not start in time for clients to receive this event.
// It is being kept in case
update_term("Klippy Ready");
break;
case "disconnect":
// Klippy has disconnected from the MCU and is prepping to
// restart. The client will receive this signal right before
// the websocket disconnects. If we need to do any kind of
// cleanup on the client to prepare for restart this would
// be a good place.
klippy_ready = false;
update_term("Klippy Disconnected");
setTimeout(() => {
get_klippy_info();
}, 2000);
break;
case "shutdown":
// Either M112 was entered or there was a printer error. We
// probably want to notify the user and disable certain controls.
klippy_ready = false;
update_term("Klipper has shutdown, check klippy.log for info");
break;
}
function handle_klippy_disconnected() {
// Klippy has disconnected from the MCU and is prepping to
// restart. The client will receive this signal right before
// the websocket disconnects. If we need to do any kind of
// cleanup on the client to prepare for restart this would
// be a good place.
klippy_ready = false;
update_term("Klippy Disconnected");
setTimeout(() => {
get_klippy_info();
}, 2000);
}
json_rpc.register_method("notify_klippy_state_changed", handle_klippy_state);
json_rpc.register_method("notify_klippy_disconnected", handle_klippy_disconnected);
function handle_file_list_changed(file_info) {
// This event fires when a client has either added or removed
// a gcode file.
if (file_list_type == file_info.root)
get_file_list(file_info.root);
if (file_list_type == file_info.item.root)
get_file_list(file_info.item.root);
console.log("Filelist Changed:");
console.log(file_info);
}
json_rpc.register_method("notify_filelist_changed", handle_file_list_changed);
function handle_metadata_update(metadata) {
console.log(metadata);
}
json_rpc.register_method("notify_metadata_update", handle_metadata_update);
//***********End Klipper Event Handlers (JSON-RPC)*****************/
// The function below is an example of one way to use JSON-RPC's batch send
@@ -1141,8 +1156,9 @@ window.onload = () => {
// Post Subscription Request
$('#btnsubscribe').click(() => {
if (api_type == 'http') {
let url = api.object_subscription.url + "?gcode=gcode_position,speed,speed_factor,extrude_factor" +
"&toolhead&virtual_sdcard&heater_bed&extruder=temperature,target&fan&idle_timeout&pause_resume";
let url = api.object_subscription.url + "?gcode_move=gcode_position,speed,speed_factor,extrude_factor" +
"&toolhead&virtual_sdcard&heater_bed&extruder=temperature,target&fan&idle_timeout&pause_resume" +
"&print_stats";
let settings = {url: url};
if (apikey != null)
settings.headers = {"X-Api-Key": apikey};
@@ -1151,14 +1167,17 @@ window.onload = () => {
});
} else {
const sub = {
gcode: ["gcode_position", "speed", "speed_factor", "extrude_factor"],
idle_timeout: [],
pause_resume: [],
toolhead: [],
virtual_sdcard: [],
heater_bed: [],
extruder: ["temperature", "target"],
fan: []};
objects: {
gcode_move: ["gcode_position", "speed", "speed_factor", "extrude_factor"],
idle_timeout: null,
pause_resume: null,
toolhead: null,
virtual_sdcard: null,
heater_bed: null,
extruder: ["temperature", "target"],
fan: null,
print_stats: null}
};
add_subscription(sub);
}
});
@@ -1201,7 +1220,7 @@ window.onload = () => {
return false;
});
} else {
get_object_info();
get_object_list();
}
});