144 Commits
Author SHA1 Message Date
Arksine 6a13260e67 scripts: add version.txt
Moonraker's update_manager plugin will check this file to see if dependencies or the python enviroment need an update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-28 07:29:25 -05:00
Arksine 6403eaa0db docs: document "update_manager" plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-28 07:22:09 -05:00
Arksine 4edad1b7a4 test_client: add support for "update_response" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine 21a7a4e530 websockets: Add "update_response" notification
This will send output from "update" commands over the websocket to clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine d9af161a18 update_manager: initial implementation
This manager can perform updates on moonraker and klipper, assuming that the source is located in a valid git repo, the origin points to the official repo, and the currently selected branch is "master".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-27 16:59:29 -05:00
Arksine 83381446a0 machine: add "/machine/services/restart" endpoint
This makes it possible for clients to hard restart an service in the event it becomes unresponsive.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 093b8c14d6 shell_command: refactor output parsing
Separate output by line, and execute the output callback once per line.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 116c1e9f29 shell_command: add run_with_response() method
This method collects the entire response and returns it with the call.  Suitable for commands that produce little output.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 706d86dd21 file_manager: update paths in "ready" event handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine df81854f89 moonraker: Store info received from initial "info" request to klippy
This allows moonraker plugins to look up the stored info without needing to make an addition "info" request to Klippy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine b0469da462 moonraker: add software version to system_args
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine 2e9c6de5d0 moonraker: refactor references to cmd_line_args
They are now named "system_args", as they represent system wide arguments.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:56 -05:00
Arksine f96fb997da docs: document API for retreiving Klipper "docs"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:22:45 -05:00
Arksine b0f781ec16 file_manager: serve Klipper's "docs" directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-23 06:17:23 -05:00
Matthias Neumayr 93fd850b63 Added Tasmota SetOption26 to power/Tasmota setup description
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr a2327a093b Fixed error when reading Tasmota status response
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr 4415a3c858 Updated documentation with Tasmota power configuration settings and sample
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Matthias Neumayr 6ba54d9cb1 Added Tasmota power plugin
Signed-off-by: Matthias Neumayr <matt.neumayr@gmail.com>
2020-11-21 13:59:29 -05:00
Arksine 8d3e185894 docs: fix typo in user_changes.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-20 14:36:13 -05:00
Arksine 01a48e530f docs: update documentation for changes to "power" plugin
The power APIs were never properly documented, so this adds them to web_api.md.  In addition, a new "user_changes.md" document has been added to help users transition to the new plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 15:43:24 -05:00
Arksine 675fe750f6 test client: log objects received via the "power changed" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:42:55 -05:00
Arksine 8ead49504b power: add support for tplink smartplug (Kasa) devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 47c7cea5a5 power: add initial support for device types
This changes the API endpoints from "/machine/gpio_power" to "/machine/device_power".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine f6fa093369 power: refactor power requests
Do not allow on, off, or status requests without arguments.    Pass device objects to "power_device()" rather than device names.

Signed-off-by:  Eric Callahan <arkine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 6738aa8c68 power: Use libgpiod instead of sysfs for gpio management
This resolves issues inherent with sysfs gpio management.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-19 08:32:37 -05:00
Arksine 48266e0bd6 power: rework configuration
Devices are now configured using "prefix" sections.   The pin configuration now more closely mimics that of Klipper's configuration so as to reduce confusion.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 1975b875a5 confighelper: Add helper methods
Add "get_name()" and "get_prefix_section" methods

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 0a7b580799 moonraker: handle "prefix" section during inital load
Only load the plugin for each prefix section once.  Plugins themselves will be responsible for parsing the configuration from each prefix section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine d18fc889d5 docs: update installation.md with install script's command line options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine a5e8c290ef scripts: update tornado version in requirements file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine 8b5ed3c9da scripts: update install script
Add python3-libgpiod dependency.

As this dependency requiress a rebuild of the python3 environment, add some command line options to the install script:
- "-r" will rebuild the virtualenv
- "-f" will force overwite the defaults file.  By default an existing defaults file will not be modified.
- "-c <config_path>" will direct moonraker to use the supplied path for the config file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 15:39:13 -05:00
Arksine de34fee72a machine: register "reboot_machine" and "shutdown_machine" remote methods
This allows Klippy to command moonraker to reboot or shutdown the host machine.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 12:21:16 -05:00
Arksine 346fce177f app: close server connections when closing app
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 06:53:05 -05:00
Arksine 7ca910ec46 authorization: add additional CORS logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-17 06:52:47 -05:00
Arksine 5081810a96 file_manager: normalize the path for the metadata script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-16 19:55:37 -05:00
Arksine ac1d798a36 authorization: Add wildcards to cors_domians option
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-16 07:13:30 -05:00
Arksine 2d2f8bfbcd authorization: fix issue cors issue when an error is detected
Tornado clears the headers when an error is detected, "set_default_headers" must be overrridden so that errors are properly returned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-14 17:59:08 -05:00
Arksine 7414781b3a docs: update config documentation
The `enable_cors` option has been removed from the [server] config.  CORS is now configured in [authorization] via the `cors_domains` option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 08:57:10 -05:00
Arksine ea62bc9ed1 app: change enable_cors option to cors_domains
Rather than allow all origins as was the default with "enable_cors", users may not specify the domains allowed.  If "*" is specified, all domains are allowed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 07:27:17 -05:00
Arksine 2cfc5b9501 docs: update metadata documentation
Document the "gcode_start_byte" and "gcode_end_byte" fields.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:53:20 -05:00
Arksine 222dda50bc extract_metadata: parse "gcode_start_byte" and "gcode_end_byte"
Determine the byte location of the first and last gcode command (Either Mxxx or Gxxx commands).  This is useful for determining the portion of the file that consists of actual commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:45:21 -05:00
Arksine b021d10de5 klippy_apis: add quotes around filename in call to SDCARD_PRINT_FILE
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 06:03:19 -05:00
Arksine 6763ea6197 file_manager: correct issue with directories that contain spaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-13 05:25:37 -05:00
Arksine 697be6a822 file_manager: Immedately fetch metadata for file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-12 17:27:52 -05:00
Arksine a1de70ff89 docs: document "notify_klippy_ready" websocket notfication
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:59:08 -05:00
Arksine 6254586a65 test_client: support additional notifications
Add support for "notify_klippy_ready" and "notify_power_changed".

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:53:58 -05:00
Arksine 3d827d7513 websockets: Add "notify_klippy_ready" notification
GIven that subscriptions are reset,  connected clients no longer maintained and they cannot check "webhooks.state" to see if Klippy is ready.  This notifcation may be used to in its place.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 17:53:58 -05:00
Arksine 4b2f3a6f5f docs: update API documentation
Document the new server.websocket.id method and update the documentation for the subscription APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 11:58:28 -05:00
Arksine 2ba41701e1 test_client: Add connection ID to http requests if available
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 08:32:06 -05:00
Arksine 07c307f4ea moonraker: Only return subscribed items in response to "objects/subscribe"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 08:32:06 -05:00
Arksine daa93b0a2f app: include all arguments in parsers
Clients may provide arguments either in the query string or body.  Reserved arguments "token" and "connection_id" are excluded from the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 05:37:20 -05:00
Arksine 5836d60d88 app: allow http requests to specifiy a websocket id
Some requests, such "printer/objects/subscribe", require a websocket
for asynchronous updates.  Clients may now specify a "connection_id"
in the form data that identifies an associated websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 92d1715d88 app: Simplify request handlers
There is no need to pass the auth, server, or websocket manager objects to request handlers.  They can be retreived directly from the application reference.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 7abc86847e websockets: register server.websocket.id remote method
This allows clients to request the unique ID associated with each connected websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine a6913a982a moonraker: manage subscriptions independently for each connection
This allows clients to "unsubscribe"by sending an empty dict.  Each client will receive updates only for subscribed objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 8d1239c316 websockets: pass connection to WebRequest
This gives handlers direct access to a websocket client connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine de1575f757 power: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 6c8ef93f9f machine: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine a260356d78 klippy_apis: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 27a17ed5a6 file_manager: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 870cabfa05 data_store: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 7cd51fe1eb authorization: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine ac38899d1f moonraker: update request handlers to accept WebRequest objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine faa415a823 app: Wrap incoming requests in a WebRequest object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine 30c236f1a9 websockets: add WebRequest class
This class encapsulates all request data received from a client.  This simplifies callbacks and makes it easier to add additional parameters to a client request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:46:21 -05:00
Arksine b83211e98d paneldue: convert "paneldue_beep" into a coroutine
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:41:26 -05:00
Arksine 6dfab37ef8 moonraker: spawn remote methods on the event loop
This allows regsitered methods to be coroutines.  Execution is done on the event loop to prevent a coroutine from blocking the incoming command queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-11 04:39:53 -05:00
Pawel Zubrycki a0e23eb22a power: make the module more modular
Signed-off-by:  Pawel Zubrycki <paw.zubr@gmail.com>
2020-11-09 06:48:00 -05:00
Arksine 0fada7ffc2 moonraker: add .editorconfig file
Developers may use this to help conform to the repo's basic coding style.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 08:50:51 -05:00
Arksine 453745c1b6 file_manager: rename references from "url_path" to "rel_path"
This is a better description of the item parsed from _convert_path() is a path relative to the "root" directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 07:39:59 -05:00
Arksine 3b63205e70 websockets: Report exception when "TypeError" is caught
Signed-off-by:  Eric Callahan <arksine.coded@gmail.com>
2020-11-08 07:39:37 -05:00
Arksine ffdcfd527a file_manager: clear metadata on item delete or move
When a directory is deleted or moved go ahead and prune the storage.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-08 07:39:36 -05:00
Arksine 472c7c4b23 file_manager: rename all refrences of "base" to "root"
Previously different parts of the file manager referred to name identifying a "root directory" as either base or root.  This could lead to confusion, so all references are now "root".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine c415f9ee15 file_manager: Don't store file lists
Since we need to walk through a file list each time one is requested there is no gain from storing lists locally.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine e51dbb45c1 file_manager: refactor the MetadataStorage class
Storage is now updated by individual calls to "parse_metadata()" instead of passing a full list.  This will allow the manager to

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:36:08 -05:00
Arksine e5f3aeca78 docs: document remote method calls
This updates the "PANELDUE_BEEP" gcode macro to use the "paneldue_beep" remote method.  Also included is documentation on the "set_device_power" method added to the power plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 59d27e6829 power: register "set_device_power" remote method
This allows device power to be toggled from a klipper gcode macro.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 6464bbfc3c paneldue: register "paneldue_beep" remote method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine ba78a82a26 moonraker: add ability to register remote methods with Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine c6d629659b klippy_apis: Add API to register methods with Klippy
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-07 20:34:56 -05:00
Arksine 5ff87aa24e docs: Add home assistant example
Example provided courtesy of Github User Kruppes.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-11-06 07:00:01 -05:00
Arksine 8bd6e45303 file_manager: fix bug in _handle_metadata_request()
Don't modify the metadata directly.  Create a copy, then add the "filename" item.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-05 12:43:17 -05:00
Arksine 73cbcb7b7e docs: document "extended" argument for GET directory endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:07 -05:00
Arksine 624be50026 file_manager: add "extended" argument to directory endpoint
If extended==True is passed to GET directory then the result for each gcode file will include associate metadata, if present.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:07 -05:00
Arksine f14b1f3ff0 file_manager: use os.path.splitext to find file extensions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-02 20:18:03 -05:00
Arksine 0c7fa454e9 scripts: add "pillow" python requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Arksine aac11a9fb8 extract_metadata: Add support for extracting Cura thumbnails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Arksine 0d515e4938 file_manager: Add support for uploading and extracting ufp files
Credit to GitHub user cdkeito for creating a template from which this implementation was inspired.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-31 08:40:49 -04:00
Jordan Ruthe b63d192df7 power: add websocket notification
Signed-off-by: Jordan Ruthe <jordanruthe@gmail.com>
2020-10-27 18:08:56 -04:00
Arksine d582d76346 docs: Add clarification to printer object description
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 21:29:53 -04:00
Arksine 9394bf592c docs: Add documentation for Klipper Printer Objects
This documents the most useful printer objects available for query, providing the fields that a query returns and what the represent.

Also add a basic  "print state monitoring" example and  "bed_mesh" example to web_api.md.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 21:25:20 -04:00
Arksine 4919548ef5 test_client: Add button to retreive mesh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-26 20:29:02 -04:00
th33xitus 374d984ced fix: make installer not fail if klipper is installed as systemd service
If Klipper is installed as systemd service, the script would fail and exit at step 6 (corrected that typo) when trying to stop Klipper via init.d.
Changing the used command to systemctl will be compatible with both init.d and systemd services.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2020-10-26 14:46:44 -04:00
Arksine 413062f8e8 docs: Update API documentation
The "modified" field returned by all file manager endpoints and notifications now refers to unix time (in seconds).

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-25 19:50:24 -04:00
Arksine 7554a599b4 paneldue: Convert "modifed" attribute of metadata to a string
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:54:36 -04:00
Arksine dfb1e19948 extract_metadata: store file "modified" time as unix time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:53:45 -04:00
Arksine f2fb8d33d4 file_manager: store file "modified" time as unix time
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 17:53:08 -04:00
Arksine 2d77400a65 docs: update for latest API additions and changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-21 15:42:03 -04:00
Arksine 8a6503da8a datastore: Add timestamp (in unix time) field to each line in the gcode store
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-18 16:52:08 -04:00
Arksine ab35346f24 moonraker: Add method to retreive host info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-13 07:53:40 -04:00
Arksine 28844cb41d PanelDue: Dump recieved gcode queue on restart
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-11 09:09:17 -04:00
Arksine 8fcccfd46e moonraker: Add "/server/restart" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-11 09:09:17 -04:00
Arksine f220e1b2ee moonraker: remove stale objects from subscription tracking
This prevents moonraker from subscribing to unknown printer objects on startup.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-10 08:52:44 -04:00
Arksine 346c3ad2a0 PanelDue: Make checksums optional
Some displays which emulate PD firmware do not use checksums.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-08 14:28:15 -04:00
Arksine 7a013a42f7 machine: Use shutdown -r command to reboot
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 18:23:58 -04:00
Arksine 264e708c1d file_manager: fix typo in directory check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 18:16:10 -04:00
Arksine 620fb356cc file_manager: Update the internal file list when get_directory is called
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-10-05 17:57:18 -04:00
Arksine 43d8e181be readme: Add Fluidd to the list of supported clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-30 18:08:41 -04:00
Arksine ac648cefcf docs: Add new endpints to API documention
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-30 18:03:25 -04:00
Arksine 7e3f236393 data_store: add "/server/gcode_store" endpoint
Clients may use this API to fetch up to 1000 lines of cached gocde responses.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 14:57:44 -04:00
Arksine b8fc6f5130 plugins: rename "temperature_store" plugin to "data_store".
This is in preparation for additional storage functionality.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 14:08:40 -04:00
Eric Callahan a578199dab docs: fix incorrect option for API Key file location
Resolves #22.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-28 06:53:45 -04:00
Arksine 8440a10b9e extract_metadata: attempt to parse object height from PrusaSlicer comments
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 11:44:18 -04:00
Arksine 756492f349 moonraker: add "/server/info" endpoint
This method provides basic server information, such as loaded plugins and the state of the UDS connection to Klippy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 08:34:05 -04:00
Arksine 6905515f3d shell_command: add ability to cancel a running process
Also adds an indefinite timeout if the timeout is specified as "None".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 06:14:35 -04:00
Arksine 3d1faebf15 moonraker: load_plugin() fix
Make sure that the correct config section is loaded when "load_plugin" is called.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-26 06:09:08 -04:00
Arksine d1c0cdf65b docs: Fix incorrect option for klippy_uds_address
Resolves #20.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-16 11:27:20 -04:00
Arksine 36fb1da46d docs: add missing documentation
- Document "enable_cors".  Resolves #18.
- Add a note that Moonraker is not aware of the gcode file path  until Klippy successfully starts.  Resolves #16.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-12 07:48:54 -04:00
Arksine 8b08b03fbf app: add max_upload_size configuration option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-11 06:27:48 -04:00
Arksine 733cf0afac docs: Update metadata API documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-09 11:32:37 -04:00
Arksine 57fe71c800 extract_metadata: parse slicer version during identifcation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-09 08:29:22 -04:00
Arksine ec86c7bfda extract_metadata: optimize regex
Use calls to re.search() in place of re.findall() where appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 17:29:08 -04:00
Arksine ad8680be38 extract_metadata: Add support for IceSL slicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 12:49:42 -04:00
Arksine 805821c928 extract_metadata: extract first layer temperatures
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 11:33:10 -04:00
Arksine e38f63254f extract_metadata: extract basic metadata when slicer is unknown
It is possible to extract some metatdata, such as layer height, from bare gcode script.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-08 08:41:09 -04:00
Arksine 97cb072981 docs: Add documentation for "delete_file" websocket API.
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:51:39 -04:00
Arksine 4285ea7348 test client: Add jstree file management support
This allows for easier regression testing of the full file management API.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 36c82d0c7f file_manager: simplify directory registration
Now that the file_manager directly  handles DELETE file requests, it is not necessary have the HTTP file handler perform any checks.   Thus it is no longer required to pass a "can_delete" parameter.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 2a967303cb test client: add support for websocket file delete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine ae49dfe8f2 file_manager: add websocket method for file delete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 7078d5c980 file_manager: update delete_file method
This method is now the primary means of deleting files, as it includes checks to make sure that the delete is allowed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
Arksine 059f5d6a73 app: allow local handlers to select their supported protocol
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-07 12:38:15 -04:00
jruthe c523f35c5e Fixing paths on power plugin\
Signed off by: Jordan Ruthe
2020-09-05 14:17:45 -04:00
Arksine c122bd68e0 docs: document API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 15:26:46 -04:00
Arksine 59277f8b7a test_client: Update websocket APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:43:13 -04:00
Arksine 8eaef1e559 power: Refactor APIs
Register APIs in the "machine/gpio_power" namespace.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 5904c2daf5 temperature_store: Update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 33b965644b machine: Update API registration
Signed-off- by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 34008569dd klippy_apis: Update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 371c15aa33 file_manager: update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine b034485ce8 authorization: update API registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 14:01:34 -04:00
Arksine 76ea4d25a4 app: refactor websocket handler registration
Websocket APIs are now generated using traditional namespaces, for example "printer.gcode.script" rather than "post_printer_gcode_script".   Local endpoints that register multiple requests methods will have the method prefixed (ie:. "server.files.get_directory", "server.files.post_directory", "server.files.delete_directory")

Signed-off-by:  Eric Callahan
2020-09-03 14:01:34 -04:00
Arksine fdec6277eb moonraker: handle Klippy disconnects during initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-03 12:27:13 -04:00
Arksine 2a34986acb file_manager: check for unsuccessful attempt at metadata extraction
If the metadata script encoutners an error it will return an empty dict for the "metadata" item.  Do not update the metadata storage or send a notification if the dict is empty.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-09-02 17:13:25 -04:00
41 changed files with 15325 additions and 1420 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Editorconfig file for moonraker repo, courtesy of @trevjonez
root = true
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8
[*.py]
max_line_length = 80
+18 -4
View File
@@ -2,8 +2,22 @@
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with Klipper. Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket.
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
Moonraker depends on Tornado for its server functionality. Moonraker
does not come bundled with a client, you will need to install one,
such as [Mainsail](https://github.com/meteyou/mainsail).
Note that Moonraker does not come bundled with a client, you will need to
install one. The following web clients are currently available:
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
### Changes
This section contains changelogs that users and developers may reference
to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](/docs/user_changes.md) - November 19th 2020
Developers:\
[api_changes.md](/docs/api_changes.md) - November 28th 2020
+157 -2
View File
@@ -1,5 +1,160 @@
This document keeps a record of all changes to Moonraker's remote
facing APIs.
This document keeps a record of all changes to Moonraker's web APIs.
### November 28th 2020
- The following new endpoints are available when the `[update_manager]`
section has been configured:
- `GET /machine/update/status`
- `POST /machine/update/moonraker`
- `POST /machine/update/klipper`
- `POST /machine/update/client`
- `POST /machine/update/system`
- The following endpoint has been added and is available as part of the
core API:
- `POST /machine/services/restart`
See [web_api.md](web_api.md) for details on these new endpoints.
### November 23rd 2020
- Moonraker now serves Klipper's "docs" directory. This can be access
at `GET /server/files/docs/<filename>`.
### November 19th 2020
- The path for the power APIs has changed from `gpio_power` to `device_power`:
- `GET /machine/device_power/devices`\
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
Returns an array of objects listing all detected devices.
Each object in the array is guaranteed to have the following
fields:
- `device`: The device name
- `status`: May be "init", "on", "off", or "error"
- `type`: May be "gpio" or "tplink_smartplug"
- `GET /machine/device_power/status?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
"params":{"dev_name":null}}`\
It is no longer possible to call this method with no arguments.
Status will only be returned for the requested device, to get
status of all devices use `/machine/device_power/devices`. As
before, this returns an object in the format of
`{device_name: status}`, where device_name is the name of the device
and `status` is the devices current status.
- `POST /machine/device_power/on?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
"params":{"dev_name":null}}`\
Toggles device on. Returns the current status of the device.
- `POST /machine/device_power/off?dev_name`\
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
"params":{"dev_name":null}}`\
Toggles device off. Returns the current status of the device.
- The `notify_power_changed` notification now includes an object
containing device info, matching that which would be recieved
from a single item in `/machine/power/devices`.
### November 12th 2020
- Two new fields have been added to the gcode metadata:
- `gcode_start_byte`: Indicates the byte position in the
file where the first "Gxx" or "Mxx" command is detected.
- `gcode_end_byte`: Indicates the byte position in the
file where the last "Gxx" or "Mxx" command is detected.
These fields may be used to more accurately predict print
progress based on the file size.
### November 11th 2020
- The `server.websocket.id` API has been added. This returns a
unique ID that Moonraker uses to track each client connection.
As such, this API is only available over the websocket, there
is no complementary HTTP request.
- All HTTP API request may now include arguments in either the
query string or in the request's body.
- Subscriptions are now managed on a per connection basis. Each
connection will only recieve updates for objects in which they
are currently subscribed. If an "empty" request is sent, the
subscription will be cancelled.
- The `POST /printer/object/subscribe` now requires a
`connection_id` argument. This is used to identify which
connection's associated subscription should be updated.
Currenlty subscriptions are only supported over the a
websocket connection, one may use the id received from
`server.websocket.id`.
- The `notify_klippy_ready` websocket notification has been
added.
### November 2nd 2020
- The `GET /server/files/directory` endpoint now accepts a new
optional argument, `extended`. If `extended=true`, then
the data returned for gcode files will also include extracted
metadata if it exists.
### October 25th 2020
- The `modified` field reported for files and directories is no
longer represented as a string. It is now a floating point
value representing unix time (in seconds). This can be used
to display the "last modified date" based on the client's
timezone.
### October 21st 2020
- The `/server/gcode_store` endpoint no longer returns a string
in the result's `gcode_store` field. It now returns an
Array of objects, each object containing `message` and `time`
fields. The time refers to a timestamp in unix time (seconds),
and may be used to determine when the gcode store received the
accompanying `message`.
### September 30th 2020
- Two new endpoints have been added:
- `GET /server/info` (`server.info`)
- `GET /server/gcode_store` (`server.gcode_store`)
See web_api.md for details on their usage.
### September 7th 2020
- A new websocket API has been added, `server.files.delete_file`:
```
{jsonrpc: "2.0", method: "server.files.delete_file", params:
{path: "<root>/<file_name>"}, id: <request id>}
```
Where <root> is either "gcodes" or "config", and <file_name> is
the relative path to the file for deletion. For example:
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
### September 3rd 2020
- The Websocket APIs have changed for clarity. The APIs methods now
use namespaces similar to those found in common programming languages.
This change affects all websocket APIs, however websocket events have
not changed. Below is a chart mapping the Previous API to the New API:
| Previous Websocket Method | New Websocket Method |
|---------------------------|----------------------|
| get_printer_info | printer.info |
| post_printer_emergency_stop | printer.emergency_stop |
| post_printer_restart | printer.restart |
| post_printer_firmware_restart | printer.firmware_restart |
| get_printer_objects_list | printer.objects.list |
| get_printer_objects_query | printer.objects.query |
| post_printer_objects_subscribe | printer.objects.subscribe |
| get_printer_query_endstops_status | printer.query_endstops.status |
| post_printer_gcode_script | printer.gcode.script |
| get_printer_gcode_help | printer.gcode.help |
| post_printer_print_start | printer.print.start |
| post_printer_print_pause | printer.print.pause |
| post_printer_print_resume | printer.print.resume |
| post_printer_print_cancel | printer.print.cancel |
| post_machine_reboot | machine.reboot |
| post_machine_shutdown | machine.shutdown |
| get_server_temperature_store | server.temperature_store |
| get_file_list | server.files.list |
| get_file_metadata | server.files.metadata |
| get_directory | server.files.get_directory |
| post_directory | server.files.post_directory |
| delete_directory | server.files.delete_directory |
| post_file_move | server.files.move |
| post_file_copy | server.files.copy |
- The "power" plugin APIs have changed. This affects both HTTP and
Websocket APIs. They were originally added to the "/printer" path,
however this adds the possibility of a naming conflict. The new
APIs are as follows:
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
### September 1st 2020
- A new notification has been added: `notify_metdata_update`. This
+225
View File
@@ -0,0 +1,225 @@
This document describes Moonraker's full configuration.
# Primary Configuration
The sections outlined here are required for Moonraker to function. A
minimal functional configuration might look like the following:
```
[server]
host: 0.0.0.0
port: 7125
enable_debug_logging: True
config_path: ~/.klippy_config
[authorization]
enabled: True
trusted_clients:
192.168.1.0/24
```
## server
```
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
# to all interfaces
port: 7125
# The port the HTTP server will listen on. Default is 7125
klippy_uds_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
max_upload_size: 200
# The maximum size allowed for a file upload. Default is 200 MiB.
enable_debug_logging: True
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is True. In the future this will change.
config_path:
# An optional path where configuration files are located. If specified,
# Moonraker will serve this path allowing file and directory manipulation
# within it. This path must be located within the user's HOME directory,
# by may not be the home directory itself. The default is no path, which
# results in no configuration files being served.
```
## authorization
```
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
# a valid API key or originate from a trusted client. Default is True.
api_key_file: ~/.moonraker_api_key
# Path of the file that stores Moonraker's API key. The default is
# ~/.moonraker_api_key
trusted_clients:
192.168.1.30
192.168.1.0/24
# A list of newline separated ip addresses and/or ip ranges that are
# trusted. Trusted clients are given full access to the API. Both IPv4
# and IPv6 addresses and ranges are supported. Ranges must be expressed
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
# of the ip address must be 0. The default is no clients or ranges are
# trusted.
cors_domains:
http://klipper-printer.local
http://second-printer.local:7125
# Enables CORS for the specified domains. One may specify * if they wish
# to allow all domains.
```
# Plugin Configuration
The sections outlined here are optional and enable additional
functionality in moonraker.
## paneldue
Enables PanelDue display support. The PanelDue should be connected to the
host machine, either via the machine's UART GPIOs or through a USB-TTL
converter.
```
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
# must be provided.
baud: 57600
# The baud rate to connect at. The default is 57600 baud.
machine_name: Klipper
# An optional unique machine name which displays on the PanelDue's
# Header. The default is "Klipper".
macros:
LOAD_FILAMENT
UNLOAD_FILAMENT
PANELDUE_BEEP FREQUENCY=500 DURATION=1
# A list of newline separated "macros" that are displayed in the
# PanelDue's "macros" tab. These can be gcode macros or simple
# gcodes. A macro may contain parameters. The default is no
# macros will be displayed by the PanelDue.
confirmed_macros:
RESTART
FIRMWARE_RESTART
# Like the "macros" option, this list is added to the macros tab.
# When one of these macros is excuted the PanelDue will prompt
# the user with a confirmation dialog. The default is to include
# RESTART and FIRMWARE_RESTART.
```
Most options above are self explanatory. The "macros" option can be used
to specify commands (either built in or gcode_macros) that will show up
in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```
[gcode_macro PANELDUE_BEEP]
# Beep frequency
default_parameter_FREQUENCY: 300
# Beep duration in seconds
default_parameter_DURATION: 1.
gcode:
{action_call_remote_method("paneldue_beep",
frequency=FREQUENCY|int,
duration=DURATION|float)}
```
## power
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
and Tasmota (via http) devices are supported.
```
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
# This parameter must be provided.
pin: gpiochip0/gpio26
# The pin to use for GPIO devices. The chip is optional, if left out
# then the module will default to gpiochip0. If one wishes to invert
# the signal, a "!" may be prefixed to the pin. Valid examples:
# gpiochip0/gpio26
# gpio26
# !gpiochip0/gpio26
# !gpio26
# This parameter must be provided for "gpio" type devices
address:
port:
# The above options are used for "tplink_smartplug" devices. The
# address should be a valid ip or hostname for the tplink device.
# The port should be the port the device is configured to use. The
# address must be provided. The port defaults to 9999.
address:
password:
output_id:
# The above options are used for "tasmota" devices. The
# address should be a valid ip or hostname for the tasmota device.
# Provide a password if configured in Tasmota (default is empty).
# Provided an output_id (relay id) if the Tasmota device supports
# more than one (default is 1).
# If your single-relay Tasmota device switches on/off successfully,
# but fails to report its state, ensure that 'SetOption26' is set in
# Tasmota.
```
Below are some potential examples:
```
[power printer]
type: gpio
pin: gpio26
[power printer_led]
type: gpio
pin: !gpiochip0/gpio16
[power wifi_switch]
type: tplink_smartplug
address: 192.168.1.123
[power tasmota_plug]
type: tasmota
address: 192.168.1.124
password: password1
```
It is possible to toggle device power from the Klippy host, this can be done
with a gcode_macro, such as:
```
[gcode_macro POWER_OFF_PRINTER]
gcode:
{action_call_remote_method("set_device_power",
device="printer",
state="off")}
```
The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
This could be used in conjunction with Klipper's idle timeout to turn the
printer off when idle with a configuration similar to that of below:
```
[delayed_gcode delayed_printer_off]
initial_duration: 0.
gcode:
{% if printer.idle_timeout.state == "Idle" %}
POWER_OFF_PRINTER
{% endif %}
[idle_timeout]
gcode:
TURN_OFF_MOTORS
TURN_OFF_HEATERS
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
```
## update_manager
This enables moonraker's update manager. Note that updates can only be
performed on pristine git repos. Repos that have been modified on
disk or cloned from unofficial sources are not supported.
```
[update_manager]
client_repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
# meteyou/mainsail to update Mainsail. If this option is not set then
# the update manager will not attempt to update a client.
client_path:
# The path to the client's files on disk. This cannot be a symbolic link,
# it must be the real directory in which the client's files are located.
# If `client_repo` is set, this parameter must be provided
```
+52
View File
@@ -0,0 +1,52 @@
# Example Home Assistant configuration file for a Voron V0.
# Credit to GitHub user @Kruppes
#
sensor:
- platform: rest
name: Voron_V0_sensor
resource: "http://192.168.178.56:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
json_attributes_path: "$.result.status"
json_attributes:
- heater_bed
- extruder
- print_stats
- toolhead
- display_status
- virtual_sdcard
value_template: 'OK'
- platform: template
sensors:
vzero_hotend_target:
friendly_name: 'V0.126 Hotend Target'
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_hotend_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_bed_target:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_bed_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
vzero_state:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["state"]}}'
vzero_current_print:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["filename"]}}'
vzero_current_progress:
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
unit_of_measurement: '%'
vzero_print_time:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
vzero_time_remaining:
value_template: '{{ (((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
vzero_eta:
value_template: '{{ (as_timestamp(now())+2*60*60+((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
vzero_nozzletemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1)| string)]|join}}'
vzero_bedtemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1)| string)]|join}}'
+27 -168
View File
@@ -47,19 +47,25 @@ cd ~
git clone https://github.com/Arksine/moonraker.git
```
If you have an experimental verison of moonraker that pre-dates this repo,
it must be uninstalled:
```
cd ~/moonraker/scripts
./uninstall-moonraker.sh
```
Finally, run moonraker's install script:
```
cd ~/moonraker/scripts
./install-moonraker.sh
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- -r\
This will rebuild the virtual environment for existing installations.
Sometimes this is necessary when a dependency has been added.
- -f\
This will tell the script to overwrite Moonraker's "defaults" file.
By default the script will not modify the "defaults" file if it is
detected as present.
- -c /path/to/moonraker.conf\
This allows the user to specify the path to Moonraker's config file.
The default location is "/home/<user>/moonraker.conf".
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`webhooks: New connection established`
@@ -71,9 +77,7 @@ https://github.com/meteyou/mainsail).
developer some time to bring up Mainsail in line with the latest release
of Moonraker.
# Configuration
## Command line
## Command line Usage
The configuration and log file paths may be specified via the command
line.
```
@@ -96,7 +100,7 @@ The default configuration is:
It is recommended to use the defaults, however one may change these
arguments by editing `/etc/default/moonraker`.
## Klipper configuration (printer.cfg)
## Prerequisites (Klipper Configuration)
Moonraker depends on the following Klippy extras for full functionality:
- [virtual_sdcard]
@@ -115,161 +119,16 @@ missing one or both, you can simply add the bare sections to printer.cfg:
[virtual_sdcard]
path: ~/gcode_files
```
NOTE: While Klipper does not set any hard limits on the location of the
`path` option for the `virtual_sdcard`, Moonraker requires that the path
be located within the HOME directory, it cannot however be the HOME
directory. If you wish to host your files elsewhere, use a symlink.
NOTES:
- While Klipper does not set any hard limits on the location of the
`path` option for the `virtual_sdcard`, Moonraker requires that the path
be located within the HOME directory, it cannot however be the HOME
directory. If you wish to host your files elsewhere, use a symlink.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
Once Moonraker receives the path it will retain it regardless of Klippy's
state, and update it if the path is changed in printer.cfg.
## Moonraker configuration (moonraker.conf)
All other configuration is done via `moonraker.conf`. If you are
familiar with Klipper, the configuration is similar. A basic
configuration might look like the following:
```
[server]
host: 0.0.0.0
port: 7125
enable_debug_logging: True
config_path: ~/.klippy_config
[authorization]
enabled: True
trusted_clients:
192.168.1.0/24
```
Note that while all items in the `[server]` and `[authorization]`
sections have default values, the sections must be present for
moonraker to start. Aside from the `config_path` and `trusted_clients`
options it is recommended to use default values.
Below is a detailed explanation of all options currently available:
```
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
# to all interfaces
port: 7125
# The port the HTTP server will listen on. Default is 7125
klippy_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
enable_debug_logging: True
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is True. In the future this will change.
config_path:
# An optional path where configuration files are located. If specified,
# Moonraker will serve this path allowing file and directory manipulation
# within it. This path must be located within the user's HOME directory,
# by may not be the home directory itself. The default is no path, which
# results in no configuration files being served.
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
# a valid API key or originate from a trusted client. Default is True.
api_key_path: ~/.moonraker_api_key
# Path of the file that stores Moonraker's API key. The default is
# ~/.moonraker_api_key
trusted_clients:
192.168.1.30
192.168.1.0/24
# A list of newline separated ip addresses and/or ip ranges that are
# trusted. Trusted clients are given full access to the API. Both IPv4
# and IPv6 addresses and ranges are supported. Ranges must be expressed
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
# of the ip address must be 0. The default is no clients or ranges are
# trusted.
```
For the moment, you need to restart the moonraker service to load a new
configuration:
```
sudo service moonraker restart
```
### Plugin Configuration
The core plugins are configured via the primary configuration above. Optional
plugins each need their own configuration as outlined below.
#### PanelDue Plugin
```
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
# must be provided.
baud: 57600
# The baud rate to connect at. The default is 57600 baud.
machine_name: Klipper
# An optional unique machine name which displays on the PanelDue's
# Header. The default is "Klipper".
macros:
LOAD_FILAMENT
UNLOAD_FILAMENT
PANELDUE_BEEP FREQUENCY=500 DURATION=1
# A list of newline separated "macros" that are displayed in the
# PanelDue's "macros" tab. These can be gcode macros or simple
# gcodes. A macro may contain parameters. The default is no
# macros will be displayed by the PanelDue.
confirmed_macros:
RESTART
FIRMWARE_RESTART
# Like the "macros" option, this list is added to the macros tab.
# When one of these macros is excuted the PanelDue will prompt
# the user with a confirmation dialog. The default is to include
# RESTART and FIRMWARE_RESTART.
```
Most options above are self explanatory. The "macros" option can be used
to specify commands (either built in or gcode_macros) that will show up
in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```
[gcode_macro PANELDUE_BEEP]
variable_sequence: 0
variable_frequency: 0
variable_duration: 0
# Beep frequency
default_parameter_FREQUENCY: 300
# Beep duration in seconds
default_parameter_DURATION: 1.
gcode:
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=frequency VALUE={FREQUENCY|int}
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=duration VALUE={DURATION|float}
SET_GCODE_VARIABLE MACRO=PANELDUE_BEEP VARIABLE=sequence VALUE={printer["gcode_macro PANELDUE_BEEP"].sequence|int + 1}
```
#### Power Control Plugin
Power Plugin Configuration. One may use this module to toggle the
state of a relay using a linux GPIO, enabling the ability to power
a printer on/off regardless of Klippy's state. GPIOs are toggled
using linux sysfs.
```
[power]
devices: printer, led
# A comma separated list of devices you wish to control. Device names may not
# contain whitespace. This parameter must be provided.
#
# Each device specified in "devices" should define its own set of the below
# options:
{dev}_name: Friendly Name
# An optional alias for the device. The default is the name specifed in
# "devices".
{dev}_pin: 23
# The sysfs GPIO pin number you wish to control. This parameter must be
# provided.
{dev}_active_low: False
# When set to true the pin signal is inverted. Default is False.
```
Define the devices you wish to control under _devices_ with a comma separated
list. For device specific configrations, swap {dev} for the name of the device
that you listed under devices.
Each device can have a Friendly Name, pin, and activehigh set. Pin is the only
required option. For devices that should be active when the signal is 0 or low,
set {dev}_activehigh to False, otherwise don't put the option in the
configuration.
Please see [configuration.md](configuration.md) for details on how to
configure moonraker.conf.
+344
View File
@@ -0,0 +1,344 @@
As mentioned in the API documentation, it is possible to
[query](web_api.md#query-printer-object-status) or
[subscribe](web_api.md#subscribe-to-printer-object-status)
to "Klipper Printer Objects." There are numerous printer objects in
Klipper, many of which are optional and only report status if they are
enabled by Klipper's configuration. Client's may retreive a list of
available printer objects via the
[list objects endpoint](web_api.md#list-available-printer-objects). This
should be done after Klipper reports its state as "ready".
This section will provide an overview of the most useful printer objects.
If a developer is interested in retreiving state for an object not listed here,
look in Klipper's source code for module you wish to query. If the module
contains a "get_status()" method, its return value will contain a dictionary
that reports state which can be queried.
## webhooks
```json
{
state: "startup",
state_message: "message"
}
```
The `webhooks` object contains the current printer state and the current
state message. These fields match those returned via the `/printer/info`
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
so they are asynchonously notified of a change to printer state. The `state`
may be "startup", "ready", "shutdown", or "error". The `state_message`
contains a message specific to the current printers state.
## gcode_move
```json
{
speed_factor: 1.0,
speed: 100.0,
extrude_factor: 1.0,
absolute_coordinates: true,
absolute_extrude: false,
homing_origin: [0.0, 0.0, 0.0, 0.0],
position: [0.0, 0.0, 0.0, 0.0],
gcode_position: [0.0, 0.0, 0.0, 0.0]
}
```
The `gcode_move` object reports the current gcode state:
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
- `speed`: The current gcode speed in mm/s.
- `extrude_factor`: AKA "extrusion multiplier".
- `absolute_coorinates`: true if the machine axes are moved using
absolute coordinates, false if using relative coordinates.
- `absolute_extrude`: true if the extruder is moved using absolute
coordinates, false if using relative coordinates.
- `homing_origin`: [X, Y, Z, E] - returns the "gcode offset" applied to
each axis. For example, the "Z" axis can be checked to determine how
much offset has been applied via "babystepping".
- `position`: [X, Y, Z, E] - The internal gcode position, including
any offsets (gcode_offset, G92, etc) added to an axis.
- `gcode_position`: [X, Y, Z, E] - The current gcode position
sans any offsets applied. For X, Y, and Z, this should match
the most recent "G1" or "G0" processed assuming the machine is
using absolute coordinates.
Note: The printer's actual movement may lag behind the reported positional
coordinates due to lookahead.
## toolhead
```json
{
homed_axes: "xyz",
print_time: 0.0,
estimated_print_time: 0.0,
extruder: "extruder",
position: [0.0, 0.0, 0.0, 0.0],
max_velocity: 500.0,
max_accel: 3000.0,
max_accel_to_decel: 1500.0,
square_corner_velocity: 5.0
}
```
The `toolhead` object reports state of the current tool:
- `homed_axes`: a string containing the axes that are homed. If no axes
are homed, returns a null string.
- `print_time`: internal value, not generally useful for clients
- `estimated_print_time`: internal value, not generally useful for clients.
- `extruder`: the name of the currently selected extruder, ie "extruder"
or "extruder1".
- `position`: [X, Y, Z, E] - This the the last position toward which the tool
was commanded to move. It includes any offsets applied via gcode as well
as any transforms made by modules such as "bed_mesh", "bed_tilt", or
"skew_correction".
- `max_velocity`: The currently set maximum velocity of the tool (mm/s^2).
- `max_accel`: The currently set maximum acceleration of the tool (mm/s^2).
- `max_accel_to_decel`: The currently set maximum accel to decel of the tool.
This value is the maximum rate at which the tool can transition from
acceleration to deceleration (mm/s^2).
- `square_corner_velocity`: The currently set square corner velocity. This
is the maximum velocity at which the tool may travel a 90 degree corner.
Note: `max_velocity`, `max_accel`, `max_accel_to_decel`, and
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
`M204` can also change `max_accel`.
## configfile
```json
{
config: {},
save_config_pending: false
}
```
The `configfile` object reports printer configuration state:
- `config`: This is an object containing the configuration as read from
printer.cfg. Each config section will be an object containing the
configured options. Option values will ALWAYS be reported as
strings. Note that default values are not reported, only options
configured in printer.cfg are present.
- `save_config_pending`: True if the printer has taken an action which
has updated the internal configuration (ie: PID calibration, probe
calibration, bed mesh calibration). This allows clients to present
the user with the option to execute a SAVE_CONFIG gcode which will
save the configuration to printer.cfg and restart the Klippy Host.
## extruder
*Enabled when [extruder] is included in printer.cfg*
Note: If multiple extruders are configured, extruder 0 is available as
`extruder`, extruder 1 as `extruder1` and so on.
```json
{
temperature: 0.0,
target: 0.0
pressure_advance: 0.0,
smooth_time: 0.0
}
```
The `extruder` object reports state of an extruder:
- `temperature`: The extruder's current temperature (in C).
- `target`: The extruder's target temperature (in C).
- `pressure_advance`: The extruder's current pressure advance value.
- `smooth_time`: The currently set time range to use when calculating the
average extruder velocity for pressure advance.
## heater_bed
*Enabled when [heater_bed] is included in printer.cfg*
```json
{
temperature: 0.0,
target: 0.0
}
```
The `heater_bed` object reports state of the heated bed:
- `temperature`: The bed's current temperature
- `target`: The bed's target temperature
## fan
*Enabled when [fan] is included in printer.cfg*
```json
{
speed: 0.0
}
```
The `fan` object returns state of the part cooling fan:
- `speed`: The current fan speed. This is reported as a
percentage of maximum speed in the range of 0.0 - 1.0.
## idle_timeout
```json
{
state: "Idle",
printing_time: 0.0
}
```
The `idle_timeout` object reports the idle state of the printer:
- `state`: Can be "Idle", "Ready", or "Printing". The printer will
transition to the "Printing" state whenever a gcode is issued that
commands the tool, this includes manual commands. Thus this should
not be used to determine if a gcode file print is in progress. It can
however be used to determine if the printer is busy.
- `printing_time`: The amount of time the printer has been in the
"Printing" state. This is reset to 0 whenever the printer transitions
from "Printing" to "Ready".
## virtual_sdcard
*Enabled when [virtual_sdcard] is included in printer.cfg*
```json
{
progress: 0.0,
is_active: false,
file_position: 0
}
```
The `virtual_sdcard` object reports the state of the virtual sdcard:
- `progress`: The print progress reported as a percentage of the file
read, in the range of 0.0 - 1.0.
- `is_active`: Returns true if the virtual sdcard is currently processing
a file. Note that this will return false if a virtual sdcard print is
paused.
- `file_position`: The current file position in bytes. This will always
be an integer value
Note: `progress` and `file_position` will persist after a print has
paused, completed, or errored. They are cleared when the user issues
a SDCARD_RESET_FILE gcode or when a new print has started.
## print_stats
*Enabled when [virtual_sdcard] is included in printer.cfg*
```json
{
filename: "",
total_duration: 0.0,
print_duration: 0.0,
filament_used: 0.0,
state: "standby",
message: ""
}
```
The `print_stats` object reports "virtual_sdcard" print state:
- `filename`: The name of the current file loaded. This will be a null
string if no file is loaded. Note that name is a path relative to the
gcode folder, thus if the file is located in a subdirectory it would
be reported as "my_sub_dir/myprint.gcode".
- `total_duration`: The total time (in seconds) elapsed since a print
has started. This includes time spent paused.
- `print_duration`: The total time spent printing (in seconds). This is
equivalent to `total_duration` - time paused.
- `filament_used`: The amount of filament used during the current print
(in mm). Any extrusion during a pause is excluded.
- `state`: Current print state. Can be "standby", "printing", "paused",
"complete", or "error". If an error is detected the print will abort.
- `message`: If an error is detected, this field contains the error
message generated. Otherwise it will be a null string.
Note: After a print has started all of the values above will persist until
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
## display_status
*Enabled when [display] or [display_status] is included in printer.cfg*
```json
{
message: "",
progress: 0.0
}
```
The `display_status` object contains state typically used to update displays:
- `message`: The message set by a M117 gcode. If no message is set this will
be a null string.
- `progress`: The percentage of print progress, as reported by M73. This
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
will fallback to the eqivalent of `virtual_sdcard.progess`. Note that
progress updated via M73 has a timeout. If no M73 is received after 5
seconds, `progress` will be set to the fallback value.
## temperature_sensor sensor_name
*Enabled when [temperature_sensor sensor_name] is included in printer.cfg. It is*
*possible for multiple temperature sensors to be configured.*
```json
{
temperature: 0.0,
measured_min_temp: 0.0,
measured_max_temp: 0.0
}
```
A `temperature_sensor` reports the following state:
- `temperature`: Sensor's current reported temperature
- `measured_min_temp`: The mimimum temperature read from the sensor
- `measured_max_temp`: The maximum temperature read from the sensor
## temperature_fan fan_name
*Enabled when [temperature_fan fan_name] is included in printer.cfg. It is*
*possible for multiple temperature fans to be configured.*
```json
{
speed: 0.0,
temperature: 0.0,
target: 0.0
}
```
A `temperature_fan` reports the following state:
- `speed`: Current fan speed as a percentage of maximum speed, reported
in the range of 0.0 - 1.0
- `temperature`: Currently reported temperature of the sensor associated
with the fan
- `target`: The current target temperature for the `temperature_fan`.
## filament_switch_sensor sensor_name
*Enabled when [filament_switch_sensor sensor_name] is included in printer.cfg.*
*It is possible for multiple filament sensors to be configured.*
```json
{
filament_detected: false,
enabled: true
}
```
A `filament_switch_sensor` reports the following state:
- `filament_detected`: Set to true if the switch detects filament, otherwise
false
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
## output_pin pin_name
*Enabled when [output_pin pin_name] is included in printer.cfg.*
*It is possible for multiple output pins to be configured.*
```json
{
value: 0.0
}
```
An `output_pin` reports the following state:
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
across the entire range.
## bed_mesh
*Enabled when [bed_mesh] is included in printer.cfg.*
```json
{
profile_name: "",
mesh_min: [0.0, 0.0],
mesh_max: [0.0, 0.0],
probed_matrix: [[]],
mesh_matrix: [[]]
}
```
The `bed_mesh` printer object reports the following state:
- `profile_name`: The name of the currently loaded profile. If no profile is
loaded then this will report a null string. If the user is not using bed_mesh
profile management then this will report "default" after mesh calibration
completes.
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
values. If the matrix has not been probed the the result is `[[]]`.
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
no matrix has been generated the result is `[[]]`.
Note: See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
of how to use this information to generate (X,Y,Z) coordinates.
## gcode_macro macro_name
*Enabled when [gcode_macro macro_name] is included in printer.cfg.*
*It is possible for multiple gcode macros to be configured.*
Gcode macros will report the state of configured "variables".
While user defined macros likely won't report state that is useful
for a client, it is possible for client developers to recommend or
request a specific gcode_macro configuration, then have the client
take action based on the variables reported by the macro.
+34
View File
@@ -0,0 +1,34 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### November 19th 2020
- The install script (`install-moonraker.sh`) now has command-line
options:\
`-r` Rebuild the python virtual env\
`-f` Force an overwrite of `/etc/default/moonraker` during installation\
`-c /path/to/moonraker.conf` Allows user to specify the path to
moonraker.conf during configuration. Using this in conjunction with `-f`
will update the defaults file wih the new path.
- New dependencies have been added to Moonraker which require reinstallation.
Run the following command to reinstall and rebuild the virtualenv:
```
~/moonraker/scripts/install-moonraker.sh -r
```
- The power plugin configuration has changed. See the
[install guide](installation.md#power-control-plugin) for
details on the new configuration.
- Users transitioning from the previous version of the power plugin will need
to unexport any curently used pins. For example, the following command
may be used to unexport pin 19:
```
echo 19 > /sys/class/gpio/unexport
```
Alternatively one may reboot the machine after upgrading:
```
cd ~/moonraker/
git pull
~/moonraker/scripts/install-moonraker.sh -r
sudo reboot
```
Make sure that the power plugin configuration has been updated prior
to rebooting the machine.
+571 -65
View File
@@ -11,8 +11,9 @@ of:
`{result: <response data>}`
The command matches the original command request, the result is the return
value generated from the request.
Arguments sent via the HTTP APIs may either be included in the query string
or as part of the request's body. All of the examples in this document
use the query string for arguments.
Websocket requests are returned in JSON-RPC format:
`{jsonrpc: "2.0", "result": <response data>, id: <request id>}`
@@ -37,7 +38,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`GET /printer/info`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_info", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.info", id: <request id>}`
- Returns:\
An object containing the build version, cpu info, Klippy's current state.
@@ -61,7 +62,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/emergency_stop`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_emergency_stop", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.emergency_stop", id: <request id>}`
- Returns:\
`ok`
@@ -71,7 +72,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/restart`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_restart", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.restart", id: <request id>}`
- Returns:\
`ok`
@@ -81,19 +82,19 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/firmware_restart`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_firmware_restart", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.firmware_restart", id: <request id>}`
- Returns:\
`ok`
## Printer Status
### Request available printer objects and their attributes:
### List available printer objects:
- HTTP command:\
`GET /printer/objects/list`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_objects_list", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.objects.list", id: <request id>}`
- Returns:\
An a list of "printer objects" that are currently available for query
@@ -103,7 +104,7 @@ that uses promises to return responses and errors (see json-rcp.js).
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
```
### Query the a status for an object, or group of objects:
### Query printer object status:
- HTTP command:\
`GET /printer/objects/query?gcode`
@@ -113,8 +114,8 @@ that uses promises to return responses and errors (see json-rcp.js).
`?gcode=gcode_position,busy&toolhead&extruder=target`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_objects_query", params:
{objects: {gcode: [], toolhead: ["position", "status"]}},
`{jsonrpc: "2.0", method: "printer.objects.query", params:
{objects: {gcode: null, toolhead: ["position", "status"]}},
id: <request id>}`
Note that an empty array will fetch all available attributes for its key.
@@ -138,17 +139,30 @@ that uses promises to return responses and errors (see json-rcp.js).
...}
}
```
### Subscribe to a status request or a batch of status requests:
See [printer_objects.md](printer_objects.md) for details on the printer objects
available for query.
### Subscribe to printer object status:
- HTTP command:\
`POST /printer/objects/subscribe?gcode=gcode_position,bus&extruder=target`
`POST /printer/objects/subscribe?connection_id=123456789&
gcode=gcode_position,bus&extruder=target`
Note: The HTTP API requires that a `connection_id` is passed via the query
string or as part of the form. This should be the
[ID reported](#get-websocket-id) from a currently connected websocket. A
request that includes only the `connection_id` argument will cancel the
subscription on the specified websocket.
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_objects_subscribe", params:
{objects: {gcode: [], toolhead: ["position", "status"]}},
`{jsonrpc: "2.0", method: "printer.objects.subscribe", params:
{objects: {gcode: null, toolhead: ["position", "status"]}},
id: <request id>}`
Note that if `objects` is an empty object then the subscription will
be cancelled.
- Returns:\
Status data for all currently subscribed objects, with the format matching that of
Status data for objects in the request, with the format matching that of
the `/printer/objects/query`:
```json
@@ -166,20 +180,18 @@ that uses promises to return responses and errors (see json-rcp.js).
...}
}
```
Note that Moonraker's current behavior is maintain a superset of all client
subscriptions, thus you may received data for objects that you did not
request. This behavior is subject to change in the future (where each
client receives only the subscriptions it requested).
See [printer_objects.md](printer_objects.md) for details on the printer objects
available for subscription.
Future updates for subscribed objects are sent asynchronously over the
websocket. See the `notify_status_update` notification for details.
Status updates for subscribed objects are sent asynchronously over the
websocket. See the `notify_status_update` notification for details.
### Query Endstops
- HTTP command:\
`GET /printer/query_endstops/status`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_query_endstops_status", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.query_endstops.status", id: <request id>}`
- Returns:\
An object containing the current endstop state, with each attribute in the
@@ -192,12 +204,35 @@ that uses promises to return responses and errors (see json-rcp.js).
z: "open"}
```
### Query Server Info
- HTTP command:\
`GET /server/info`
- Websocket command:
`{jsonrpc: "2.0", method: "server.info", id: <request id>}`
- Returns:\
An object containing the server's state, structured as follows:
```json
{
klippy_connected: <bool>,
klippy_state: <string>,
plugins: [<strings>]
}
```
Note that `klippy_state` will match the `state` value received from
`/printer/info`. The `klippy_connected` item tracks the state of the
connection to Klippy. The `plugins` key will return a list of all
enabled plugins. This can be used by clients to check if an optional
plugin is available.
### Fetch stored temperature data
- HTTP command:\
`GET /server/temperature_store`
- Websocket command:
`{jsonrpc: "2.0", method: "get_temperature_store", id: <request id>}`
`{jsonrpc: "2.0", method: "server.temperature_store", id: <request id>}`
- Returns:\
An object where the keys are the available temperature sensor names, and with
@@ -206,6 +241,78 @@ that uses promises to return responses and errors (see json-rcp.js).
array is organized from oldest temperature to most recent (left to right).
Note that when the host starts each array is initialized to 0s.
### Fetch stored gcode info
- HTTP command:\
`GET /server/gcode_store`
Optionally, a `count` argument may be added to specify the number of
responses to fetch. If omitted, the entire gcode store will be sent
(up to 1000 responses).
`GET /server/gcode_store?count=100`
- Websocket command:
`{jsonrpc: "2.0", method: "server.gcode_store", id: <request id>}`
OR
`{jsonrpc: "2.0", method: "server.gcode_store",
params: {count: <integer>} id: <request id>}`
- Returns:\
An object with the field `gcode_store` that contains an array
of objects. Each object will contain a `message` field and a
`time` field:
```json
{
gcode_store: [
{
message: <string>,
time: unix_time_stamp
}, ...
]
}
```
Each `message` field contains a gcode response received at the time
indicated in the `time` field. Note that the time stamp refers to
unix time (in seconds). This can be used to create a JavaScript
`Date` object:
```javascript
for (let resp of result.gcode_store) {
let date = new Date(resp.time * 1000);
// Do something with date and resp.message ...
}
```
### Restart Server
- HTTP command:\
`POST /server/restart`
- Websocket command:
`{jsonrpc: "2.0", method: "server.restart", id: <request id>}`
- Returns:\
`"ok"` upon receipt of the restart request. After the request
is returns, the server will restart. Any existing connection
will be disconnected. A restart will result in the creation
of a new server instance where the configuration is reloaded.
## Get Websocket ID
- HTTP command:\
Not Available
- Websocket command:
`{jsonrpc: "2.0", method: "server.websocket.id", id: <request id>}`
- Returns:\
This connected websocket's unique identifer in the format shown below.
Note that this API call is only available over the websocket.
```json
{
websocket_id: <int>
}
```
## Gcode Controls
### Run a gcode:
@@ -217,7 +324,7 @@ that uses promises to return responses and errors (see json-rcp.js).
Will echo "Hello" to the terminal.
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_gcode_script",
`{jsonrpc: "2.0", method: "printer.gcode.script",
params: {script: <gc>}, id: <request id>}`
- Returns:\
@@ -230,7 +337,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`GET /printer/gcode/help`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_printer_gcode_help",
`{jsonrpc: "2.0", method: "printer.gcode.help",
params: {script: <gc>}, id: <request id>}`
- Returns:\
@@ -245,7 +352,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/print/start?filename=<file name>`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_print_start",
`{jsonrpc: "2.0", method: "printer.print.start",
params: {filename: <file name>, id:<request id>}`
- Returns:\
@@ -256,7 +363,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/print/pause`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_print_pause", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.print.pause", id: <request id>}`
- Returns:\
`ok`
@@ -266,7 +373,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/print/resume`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_print_resume", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.print.resume", id: <request id>}`
- Returns:\
`ok`
@@ -276,7 +383,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /printer/print/cancel`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_printer_print_cancel", id: <request id>}`
`{jsonrpc: "2.0", method: "printer.print.cancel", id: <request id>}`
- Returns:\
`ok`
@@ -288,7 +395,7 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /machine/shutdown`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_machine_shutdown", id: <request id>}`
`{jsonrpc: "2.0", method: "machine.shutdown", id: <request id>}`
- Returns:\
No return value as the server will shut down upon execution
@@ -298,11 +405,25 @@ that uses promises to return responses and errors (see json-rcp.js).
`POST /machine/reboot`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_machine_reboot", id: <request id>}`
`{jsonrpc: "2.0", method: "machine.reboot", id: <request id>}`
- Returns:\
No return value as the server will shut down upon execution
### Restart a system service
Restarts a system service via `sudo systemctl restart <name>`. Currently
only `moonraker` and `klipper` are allowed.
- HTTP command:\
`POST /machine/services/restart?service=<service_name>`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.services.restart",
params: {service: "service name"}, id: <request id>}`
- Returns:\
`ok` when complete. Note that if `moonraker` is chosen, the return
value will be sent prior to the restart.
## File Operations
@@ -315,6 +436,7 @@ as the "gcodes" root. The following roots are available:
- gcodes
- config
- config_examples (read-only)
- docs (read-only)
Write operations (upload, delete, make directory, remove directory) are
only available on the `gcodes` and config roots. Note that the `config` root
@@ -332,7 +454,7 @@ path relative to the specified "root". Note that if the query st
the "gcodes" file list by default.
- Websocket command:\
`{jsonrpc: "2.0", method: "get_file_list", params: {root: "gcodes"}
`{jsonrpc: "2.0", method: "server.files.list", params: {root: "gcodes"}
, id: <request id>}`
If `params` are are omitted then the command will return the "gcodes"
@@ -344,8 +466,8 @@ path relative to the specified "root". Note that if the query st
```json
[
{filename: "file name",
size: <file size>,
modified: "last modified date",
size: <file_size>,
modified: <unix_time>,
...]
```
@@ -360,7 +482,7 @@ path relative to the specified "root". Note that if the query st
`GET /server/files/metadata?filename=<filename>`
- Websocket command:\
`{jsonrpc: "2.0", method: "get_file_metadata", params: {filename: "filename"}
`{jsonrpc: "2.0", method: "server.files.metadata", params: {filename: "filename"}
, id: <request id>}`
- Returns:\
@@ -371,20 +493,25 @@ path relative to the specified "root". Note that if the query st
```json
{
filename: "file name",
size: <file size>,
modified: "last modified date",
size: <file_size>,
modified: <unix_time>,
slicer: "Slicer Name",
first_layer_height: <in mm>,
layer_height: <in mm>,
object_height: <in mm>,
estimated_time: <time in seconds>,
filament_total: <in mm>,
slicer_version: "<version>",
first_layer_height: <mm>,
first_layer_bed_temp: <C>,
first_layer_extr_temp: <C>,
layer_height: <mm>,
object_height: <mm>,
estimated_time: <time_in_seconds>,
filament_total: <mm>,
gcode_start_byte: <byte_location_of_first_gcode_command>,
gcode_end_byte: <byte_location_of_last_gcode_command>,
thumbnails: [
{
width: <in pixels>,
height: <in pixels>,
size: <length of string>,
data: <base64 string>
width: <in_pixels>,
height: <in_pixels>,
size: <length_of_string>,
data: <base64_string>
}, ...
]
}
@@ -396,18 +523,23 @@ Unlike `/server/files/list`, this command does not walk through
subdirectories.
- HTTP command:\
`GET /server/files/directory?path=gcodes/my_subdir`
`GET /server/files/directory?path=gcodes/my_subdir&extended=true`
If the query string is omitted then the command will return
the "gcodes" file list by default.
- Websocket command:\
`{jsonrpc: "2.0", method: "get_directory", params: {path: "gcodes/my_subdir"}
, id: <request id>}`
`{jsonrpc: "2.0", method: "server.files.get_directory",
params: {path: "gcodes/my_subdir", extended: true} ,
id: <request id>}`
If the "params" are omitted then the command will return
the "gcodes" file list by default.
The `extended` argument is optional, and defaults to false. If
specified and set to true, then data returned for gcode files
will also include metadata if it is available.
- Returns:\
An object containing file and subdirectory information in the
following format:
@@ -417,14 +549,14 @@ subdirectories.
files: [
{
filename: "file name",
size: <file size>,
modified: "last modified date"
size: <file_size>,
modified: <unix_time>
}, ...
],
dirs: [
{
dirname: "directory name",
modified: "last modified date"
modified: <unix_time>
}
]
}
@@ -437,7 +569,7 @@ Creates a new directory at the specified path.
`POST /server/files/directory?path=gcodes/my_new_dir`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_directory", params:
`{jsonrpc: "2.0", method: "server.files.post_directory", params:
{path: "gcodes/my_new_dir"}, id: <request id>}`
Returns:\
@@ -450,7 +582,7 @@ Deletes a directory at the specified path.
`DELETE /server/files/directory?path=gcodes/my_subdir`
- Websocket command:\
`{jsonrpc: "2.0", method: "delete_directory", params:
`{jsonrpc: "2.0", method: "server.files.delete_directory", params:
{path: "gcodes/my_subdir"} , id: <request id>}`
If the specified directory contains files then the delete request
@@ -490,7 +622,7 @@ in *moving* the source directory to the destination directory.
&dest=gcodes/subdir/my_file.gcode`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_file_move", params:
`{jsonrpc: "2.0", method: "server.files.move", params:
{source: "gcodes/my_file.gcode",
dest: "gcodes/subdir/my_file.gcode"}, id: <request id>}`
@@ -505,7 +637,7 @@ the source and destination should have the root prefixed.
&dest=gcodes/subdir/my_file.gcode`
- Websocket command:\
`{jsonrpc: "2.0", method: "post_file_copy", params:
`{jsonrpc: "2.0", method: "server.files.copy", params:
{source: "gcodes/my_file.gcode", dest: "gcodes/subdir/my_file.gcode"},
id: <request id>}`
@@ -563,7 +695,11 @@ to delete a file in a subdirectory.
`DELETE /server/files/gcodes/<file_name>`
- Websocket command:\
Not Available
`{jsonrpc: "2.0", method: "server.files.delete_file", params:
{path: "gcodes/<file_name>"}, id: <request id>}`
If the gcode file exists within a subdirectory, the relative
path should be included in the file name.
- Returns:\
The HTTP request returns the name of the deleted file.
@@ -585,7 +721,8 @@ to delete a file in a subdirectory.
`DELETE /server/files/config/<file_name>`
- Websocket command:\
Not Available
`{jsonrpc: "2.0", method: "server.files.delete_file", params:
{path: "config/<file_name>}, id: <request id>}`
- Returns:\
The HTTP request returns the name of the deleted file.
@@ -600,6 +737,16 @@ to delete a file in a subdirectory.
- Returns:\
The requested file
### Download Klipper documentation
- HTTP command:\
`GET /server/files/docs/<file_name>`
- Websocket command:\
Not Available
- Returns:\
The requested file
### Download klippy.log
- HTTP command:\
`GET /server/files/klippy.log`
@@ -666,6 +813,225 @@ only be used once, making them relatively for inclusion in the query string.
to any API endpoint. The query string should be added in the form of:
`?token=randomly_generated_token`
## Update Manager APIs
The following endpoints are availabe when the `[update_manager]` plugin has
been configured:
### Get update status
Retreives the current state of each "package" available for update. Typically
this will consist of information regarding `moonraker`, `klipper`, and
a `client`. If moonraker has not yet received information from Klipper then
its status will be omitted. If a client has not been configured then its
status will also be omitted. If the parameter "refresh" is passed and set
to true then Moonraker will query Github for the most recent release
information.
- HTTP command:\
`GET /machine/update/status?refresh=false`
If the query string is omitted then "refresh" will default
to false.
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.status",
params: {refresh: false} , id: <request id>}`
If the "params" are omitted then "refresh" will default to false.
- Returns:\
Status information in the following format:
```json
{
'version_info': {
'moonraker': {
version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
},
'klipper': {
version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
}
'client': {
name: <string>,
version: <string>,
remote_version: <string>
}
},
busy: false
}
```
- The `busy` field is set to true if an update is in progress. Moonraker
will not allow concurrent updates.
- The `moonraker` and `klipper` objects have the following fields:
- `version`: version of the current repo on disk
- `current_hash`: hash of the most recent commit on disk
- `remote_hash`: hash of the most recent commit pushed to the remote
- `is_valid`: True if installation is a valid git repo on the master branch
and an "origin" set to the official remote
- `is_dirty`: True if the repo has been modified
- The `client` object has the following fields:
`name`: Name of the configured client
`version`: version of the installed client.
`remote_version`: version of the latest release published to GitHub
### Update Moonraker
Pulls the most recent version of Moonraker from GitHub and restarts
the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
Note that Moonraker uses semantic versioning to check for dependency changes
automatically, so it is generally not necessary to set `include_deps`
to `true`.
- HTTP command:\
`POST /machine/update/moonraker?include_deps=false`
If the query string is omitted then "include_deps" will default
to false.
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.moonraker",
params: {include_deps: false}, id: <request id>}`
If the "params" are omitted then "include_deps" will default to false.
- Returns:\
`ok` when complete
### Update Klipper
Pulls the most recent version of Klipper from GitHub and restarts
the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
At the moment there is no method for automatically checking for updated
Klipper dependencies, so clients might wish to make this option available
to users via the UI.
- HTTP command:\
`POST /machine/update/klipper?include_deps=false`
If the query string is omitted then "include_deps" will default
to false.
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.klipper",
params: {include_deps: false}, id: <request id>}`
If the "params" are omitted then "include_deps" will default to false.
- Returns:\
`ok` when complete
### Update Client
If `client_repo` and `client_path` have been configured in `[update_manager]`
this endpoint can be used to install the most recently publish release
of the client.
- HTTP command:\
`POST /machine/update/client`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.client",
id: <request id>}`
- Returns:\
`ok` when complete
### Update System Packages
Upgrades the system packages. Currently only `apt-get` is supported.
- HTTP command:\
`POST /machine/update/system`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.system",
id: <request id>}`
- Returns:\
`ok` when complete
## Power APIs
The APIs below are available when the `[power]` plugin has been configured.
### Get Devices
- HTTP command:\
`GET /machine/device_power/devices`
- Websocket command:\
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`
- Returns:\
An array of objects containing info for each configured device.
```json
{
devices: [
{
device: <device_name>,
status: <device_status>,
type: <device_type>
}, ...
]
}
```
### Get Device Status
- HTTP command:\
`GET /machine/device_power/status?dev_one&dev_two`
- Websocket command:\
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
"params":{"dev_one":null, "dev_two": null}}`
- Returns:\
An object containing status for each requested device
```json
{
dev_one: <device_status>,
dev_two: <device_status>,
...
}
```
### Power On Device(s)
- HTTP command:\
`POST /machine/device_power/on?dev_one&dev_two`
- Websocket command:\
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
"params":{"dev_one":null, "dev_two": null}}`
- Returns:\
An object containing status for each requested device
```json
{
dev_one: <device_status>,
dev_two: <device_status>,
...
}
```
### Power Off Device(s)
- HTTP command:\
`POST /machine/device_power/off?dev_one&dev_two`
- Websocket command:\
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
"params":{"dev_one":null, "dev_two": null}}`
- Returns:\
An object containing status for each requested device
```json
{
dev_one: <device_status>,
dev_two: <device_status>,
...
}
```
## Websocket notifications
Printer generated events are sent over the websocket as JSON-RPC 2.0
notifications. These notifications are sent to all connected clients
@@ -696,6 +1062,11 @@ Status Subscriptions arrive as a "notify_status_update" notification:
The structure of the status data is identical to the structure that is
returned from an object query's "status" attribute.
### Klippy Ready:
Notify clients when Klippy has reported a ready state
`{jsonrpc: "2.0", method: "notify_klippy_ready"}`
### Klippy Disconnected:
Notify clients when Moonraker's connection to Klippy has terminated
@@ -777,9 +1148,31 @@ Where `metadata` is an object in the following format:
}
```
### Update Manager Responses
The update manager will send asyncronous messages to the client during an
update:
`{jsonrpc: "2.0", method: "notify_update_response", params: [response]}`
Where `response` is an object int he following format:
```json
{
application: <string>,
proc_id: <int>,
message: <string>
}
```
- The `application` field contains the name of application currently being
updated. Generally this will be either "moonraker", "klipper", "system",
or "client".
- The `proc_id` field contains a unique id associated with the current update
process. This id is generated for each update request.
- The `message` field contains an asyncronous message sent during the update
process.
# Appendix
### Websocket setup
## Websocket setup
All transmissions over the websocket are done via json using the JSON-RPC 2.0
protocol. While the websever expects a json encoded string, one limitation
of Eventlet's websocket is that it can not send string encoded frames. Thus
@@ -800,13 +1193,13 @@ ws://host:port/websocket?token=<32 character base32 string>
```
This is necessary as it isn't currently possible to add `X-Api-Key` to a
websocket's request header.
Websocket object's request header.
The following startup sequence is recommened for clients which make use of
the websocket:
1) Attempt to connect to `/websocket` until successful using a timer-like
mechanism
2) Once connected, query `/printer/info` (or `get_printer_info`) for the ready
2) Once connected, query `/printer/info` (or `printer.info`) for the ready
status.
- If the response returns an error (such as 404), set a timeout for
2 seconds and try again.
@@ -818,8 +1211,121 @@ the websocket:
get a description of the error from the `state_message` attribute
- If `state == "shutdown"` then Klippy is in a shutdown state.
- If `state == "startup"` then re-request printer info in 2s.
- Repeat step 2s until Klipper reports ready. T
- Client's should watch for the `notify_klippy_state_changed` event. If it reports
- Repeat step 2 until Klipper reports ready.
- Client's should watch for the `notify_klippy_disconnected` event. If it reports
disconnected then Klippy has either been stopped or restarted. In this
instance the client should repeat the steps above to determine when
klippy is ready.
klippy is ready.
## Basic Print Status
An advanced client will likely use subscriptions and notifications
to interact with Moonraker, however simple clients such as home automation
software and embedded devices (ie: ESP32) may only wish to monitor the
status of a print. Below is a high level walkthrough for receiving print state
via polling.
- Set up a timer to poll at the desired interval. Depending on your use
case, 1 to 2 seconds is recommended.
- On each cycle, issue the following request:
- `GET http://host/printer/objects/query?webhooks&virtual_sdcard&print_stats`\
Or via json-rpc:\
`{'jsonrpc': "2.0", 'method': "printer.objects.query", 'params':
{'objects': {'webhooks': null, 'virtual_sdcard': null,
'print_stats': null}}, id: <request id>}`
- If the request returns an error or the returned `result.status` is an empty
object printer objects are not available for query. Each queried object
should be available in `result.status`. The client should check to make
sure that all objects are received before proceeding.
- Inspect `webhooks.ready`. If the value is not "ready" the printer
is not available. `webhooks.message` contains a message pertaining
to the current state.
- If the printer is ready, inspect `print_stats.state`. It may be one
of the following values:
- "standby": No print in progress
- "printing": The printer is currently printing
- "paused": A print in progress has been paused
- "error": The print exited with an error. `print_stats.message`
contains a related error message
- "complete": The last print has completed
- If `print_stats.state` is not "standby" then `print_stats.filename`
will report the name of the currently loaded file.
- `print_stats.filename` can be used to fetch file metadata. It
is only necessary to fetch metadata once per print.\
`GET http://host/server/files/metadata?filename=<filename>`\
Or via json-rpc:\
`{jsonrpc: "2.0", method: "server.files.metadata",
params: {filename: "filename"}
, id: <request id>}`\
If metadata extraction failed then this request will return an error.
Some metadata fields are only populated for specific slicers, and
unsupported slicers will only return the size and modifed date.
- There are multiple ways to calculate the ETA, this example will use
file progress, as it is possible calculate the ETA with or without
metadata.
- If `metadata.estimated_time` is available, the eta calculation can
be done as:
```javascript
// assume "result" is the response from the status query
let vsd = result.status.virtual_sdcard;
let prog_time = vsd.progress * metadata.estimated_time;
let eta = metadata.estimated_time - prog_time
```
Alternatively, one can simply subtract the print duration from
the estimated time:
```javascript
// assume "result" is the response from the status query
let pstats = result.status.print_status;
let eta = metadata.estimated_time - pstats.print_duration;
if (eta < 0)
eta = 0;
```
- If no metadata is available, print duration and progress can be used to
calculate the ETA:
```javascript
// assume "result" is the response from the status query
let vsd = result.status.virtual_sdcard;
let pstats = result.status.print_stats;
let total_time = pstats.print_duration / vsd.progress;
let eta = total_time - pstats.print_duration;
```
- It is possible to query additional object if a client wishes to display
more information (ie: temperatures). See
[printer_objects.md](printer_objects.md) for more information.
## Bed Mesh Coordinates
The [bed_mesh](printer_objects.md#bed_mesh) printer object may be used
to generate three dimensional coordinates of a probed area (or mesh).
Below is an example (in javascript) of how to transform the data received
from a bed_mesh object query into an array of 3D coordinates.
```javascript
// assume that we have executed an object query for bed_mesh and have the
// result. This example generates 3D coordinates for the probed matrix,
// however it would work with the mesh matrix as well
function process_mesh(result) {
let bed_mesh = result.status.bed_mesh
let matrix = bed_mesh.probed_matrix;
if (!(matrix instanceof Array) || matrix.length < 3 ||
!(matrix[0] instanceof Array) || matrix[0].length < 3)
// make sure that the matrix is valid
return;
let coordinates = [];
let x_distance = (bed_mesh.mesh_max[0] - bed_mesh.mesh_min[0]) /
(matrix[0].length - 1);
let y_distance = (bed_mesh.mesh_max[1] - bed_mesh.mesh_min[1]) /
(matrix.length - 1);
let x_idx = 0;
let y_idx = 0;
for (const x_axis of matrix) {
x_idx = 0;
let y_coord = bed_mesh.mesh_min[1] + (y_idx * y_distance);
for (const z_coord of x_axis) {
let x_coord = bed_mesh.mesh_min[0] + (x_idx * x_distance);
x_idx++;
coordinates.push([x_coord, y_coord, z_coord]);
}
y_idx++;
}
}
// Use the array of coordinates visualize the probed area
// or mesh..
```
+114 -116
View File
@@ -9,44 +9,47 @@ import mimetypes
import logging
import tornado
from inspect import isclass
from tornado.escape import url_unescape
from tornado.routing import Rule, PathMatches, AnyMatches
from utils import ServerError
from websockets import WebsocketManager, WebSocket
from websockets import WebRequest, WebsocketManager, WebSocket
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
from authorization import Authorization
# Max Upload Size of 200MB
MAX_UPLOAD_SIZE = 200 * 1024 * 1024
# These endpoints are reserved for klippy/server communication only and are
# not exposed via http or the websocket
RESERVED_ENDPOINTS = [
"list_endpoints", "gcode/subscribe_output"
"list_endpoints", "gcode/subscribe_output",
"register_remote_method"
]
EXCLUDED_ARGS = ["_", "token", "connection_id"]
# Status objects require special parsing
def _status_parser(request):
query_args = request.query_arguments
def _status_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key, vals in query_args.items():
parsed = []
for v in vals:
if v:
parsed += v.decode().split(',')
if parsed == []:
parsed = None
args[key] = parsed
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
val = request_handler.get_argument(key)
if not val:
args[key] = None
else:
args[key] = val.split(',')
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
# Built-in Query String Parser
def _default_parser(request):
query_args = request.query_arguments
def _default_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key, vals in query_args.items():
if len(vals) != 1:
raise tornado.web.HTTPError(404, "Invalid Query String")
args[key] = vals[0].decode()
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
args[key] = request_handler.get_argument(key)
return args
class MutableRouter(tornado.web.ReversibleRuleRouter):
@@ -82,11 +85,11 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
logging.exception(f"Unable to remove rule: {pattern}")
class APIDefinition:
def __init__(self, endpoint, http_uri, ws_method,
def __init__(self, endpoint, http_uri, ws_methods,
request_methods, parser):
self.endpoint = endpoint
self.uri = http_uri
self.ws_method = ws_method
self.ws_methods = ws_methods
if not isinstance(request_methods, list):
request_methods = [request_methods]
self.request_methods = request_methods
@@ -98,6 +101,8 @@ class MoonrakerApp:
self.tornado_server = None
self.api_cache = {}
self.registered_base_handlers = []
self.max_upload_size = config.getint('max_upload_size', 200)
self.max_upload_size *= 1024 * 1024
# Set Up Websocket and Authorization Managers
self.wsm = WebsocketManager(self.server)
@@ -106,86 +111,89 @@ class MoonrakerApp:
mimetypes.add_type('text/plain', '.log')
mimetypes.add_type('text/plain', '.gcode')
mimetypes.add_type('text/plain', '.cfg')
debug = config.getboolean('enable_debug_logging', True)
enable_cors = config.getboolean('enable_cors', False)
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
app_handlers = [
(AnyMatches(), self.mutable_router),
(r"/websocket", WebSocket,
{'wsm': self.wsm, 'auth': self.auth}),
(r"/api/version", EmulateOctoprintHandler,
{'server': self.server, 'auth': self.auth})]
(r"/websocket", WebSocket),
(r"/api/version", EmulateOctoprintHandler)]
self.app = tornado.web.Application(
app_handlers,
serve_traceback=debug,
websocket_ping_interval=10,
websocket_ping_timeout=30,
enable_cors=enable_cors)
parent=self)
self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers
logfile = config['cmd_args'].get('logfile')
logfile = config['system_args'].get('logfile')
self.register_static_file_handler("moonraker.log", logfile)
self.auth.register_handlers(self)
def listen(self, host, port):
self.tornado_server = self.app.listen(
port, address=host, max_body_size=MAX_UPLOAD_SIZE,
port, address=host, max_body_size=self.max_upload_size,
xheaders=True)
def get_server(self):
return self.server
def get_auth(self):
return self.auth
def get_websocket_manager(self):
return self.wsm
async def close(self):
if self.tornado_server is not None:
self.tornado_server.stop()
await self.tornado_server.close_all_connections()
await self.wsm.close()
self.auth.close()
def register_remote_handler(self, endpoint):
if endpoint in RESERVED_ENDPOINTS:
return
api_def = self.api_cache.get(
endpoint, self._create_api_definition(endpoint))
api_def = self._create_api_definition(endpoint)
if api_def.uri in self.registered_base_handlers:
# reserved handler or already registered
return
logging.info(
f"Registering remote endpoint: "
f"({' '.join(api_def.request_methods)}) {api_def.uri}")
self.wsm.register_handler(api_def)
f"Registering remote endpoint - "
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
f"Websocket: {', '.join(api_def.ws_methods)}")
self.wsm.register_remote_handler(api_def)
params = {}
params['server'] = self.server
params['auth'] = self.auth
params['arg_parser'] = api_def.parser
params['remote_callback'] = api_def.endpoint
self.mutable_router.add_handler(
api_def.uri, RemoteRequestHandler, params)
self.registered_base_handlers.append(api_def.uri)
def register_local_handler(self, uri, ws_method, request_methods,
callback, http_only=False):
def register_local_handler(self, uri, request_methods,
callback, protocol=["http", "websocket"]):
if uri in self.registered_base_handlers:
return
api_def = self._create_api_definition(
uri, ws_method, request_methods)
logging.info(
f"Registering local endpoint: "
f"({' '.join(request_methods)}) {uri}")
if not http_only:
self.wsm.register_handler(api_def, callback)
params = {}
params['server'] = self.server
params['auth'] = self.auth
params['methods'] = request_methods
params['arg_parser'] = api_def.parser
params['callback'] = callback
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
self.registered_base_handlers.append(uri)
uri, request_methods, is_remote=False)
msg = "Registering local endpoint"
if "http" in protocol:
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
params = {}
params['methods'] = request_methods
params['arg_parser'] = api_def.parser
params['callback'] = callback
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
self.registered_base_handlers.append(uri)
if "websocket" in protocol:
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
self.wsm.register_local_handler(api_def, callback)
logging.info(msg)
def register_static_file_handler(self, pattern, file_path,
can_delete=False, op_check_cb=None):
def register_static_file_handler(self, pattern, file_path):
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path):
@@ -198,17 +206,11 @@ class MoonrakerApp:
logging.info(f"Invalid file path: {file_path}")
return
logging.debug(f"Registering static file: ({pattern}) {file_path}")
methods = ['GET']
if can_delete:
methods.append('DELETE')
params = {
'server': self.server, 'auth': self.auth,
'path': file_path, 'methods': methods, 'op_check_cb': op_check_cb}
params = {'path': file_path}
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
def register_upload_handler(self, pattern):
params = {'server': self.server, 'auth': self.auth}
self.mutable_router.add_handler(pattern, FileUploadHandler, params)
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
def remove_handler(self, endpoint):
api_def = self.api_cache.get(endpoint)
@@ -216,29 +218,49 @@ class MoonrakerApp:
self.wsm.remove_handler(api_def.uri)
self.mutable_router.remove_handler(api_def.ws_method)
def _create_api_definition(self, endpoint, ws_method=None,
request_methods=['GET', 'POST']):
def _create_api_definition(self, endpoint, request_methods=[],
is_remote=True):
if endpoint in self.api_cache:
return self.api_cache[endpoint]
if endpoint[0] == '/':
uri = endpoint
else:
elif is_remote:
uri = "/printer/" + endpoint
if ws_method is None:
ws_method = uri[1:].replace('/', '_')
else:
uri = "/server/" + endpoint
ws_methods = []
if is_remote:
# Remote requests accept both GET and POST requests. These
# requests execute the same callback, thus they resolve to
# only a single websocket method.
ws_methods.append(uri[1:].replace('/', '.'))
request_methods = ['GET', 'POST']
else:
name_parts = uri[1:].split('/')
if len(request_methods) > 1:
for req_mthd in request_methods:
func_name = req_mthd.lower() + "_" + name_parts[-1]
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
else:
ws_methods.append(".".join(name_parts))
if not is_remote and len(request_methods) != len(ws_methods):
raise self.server.error(
"Invalid API definition. Number of websocket methods must "
"match the number of request methods")
if endpoint.startswith("objects/"):
parser = _status_parser
else:
parser = _default_parser
api_def = APIDefinition(endpoint, uri, ws_method,
api_def = APIDefinition(endpoint, uri, ws_methods,
request_methods, parser)
self.api_cache[endpoint] = api_def
return api_def
# ***** Dynamic Handlers*****
class RemoteRequestHandler(AuthorizedRequestHandler):
def initialize(self, remote_callback, server, auth, arg_parser):
super(RemoteRequestHandler, self).initialize(server, auth)
def initialize(self, remote_callback, arg_parser):
super(RemoteRequestHandler, self).initialize()
self.remote_callback = remote_callback
self.query_parser = arg_parser
@@ -249,21 +271,19 @@ class RemoteRequestHandler(AuthorizedRequestHandler):
await self._process_http_request()
async def _process_http_request(self):
args = {}
if self.request.query:
args = self.query_parser(self.request)
conn = self.get_associated_websocket()
args = self.query_parser(self)
try:
result = await self.server.make_request(
self.remote_callback, args)
WebRequest(self.remote_callback, args, conn=conn))
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
self.finish({'result': result})
class LocalRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, server, auth,
methods, arg_parser):
super(LocalRequestHandler, self).initialize(server, auth)
def initialize(self, callback, methods, arg_parser):
super(LocalRequestHandler, self).initialize()
self.callback = callback
self.methods = methods
self.query_parser = arg_parser
@@ -287,11 +307,11 @@ class LocalRequestHandler(AuthorizedRequestHandler):
raise tornado.web.HTTPError(405)
async def _process_http_request(self, method):
args = {}
if self.request.query:
args = self.query_parser(self.request)
conn = self.get_associated_websocket()
args = self.query_parser(self)
try:
result = await self.callback(self.request.path, method, args)
result = await self.callback(
WebRequest(self.request.path, args, method, conn=conn))
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
@@ -299,13 +319,6 @@ class LocalRequestHandler(AuthorizedRequestHandler):
class FileRequestHandler(AuthorizedFileHandler):
def initialize(self, server, auth, path, methods,
op_check_cb=None, default_filename=None):
super(FileRequestHandler, self).initialize(
server, auth, path, default_filename)
self.methods = methods
self.op_check_cb = op_check_cb
def set_extra_headers(self, path):
# The call below shold never return an empty string,
# as the path should have already been validated to be
@@ -315,35 +328,20 @@ class FileRequestHandler(AuthorizedFileHandler):
"Content-Disposition", f"attachment; filename={basename}")
async def delete(self, path):
if 'DELETE' not in self.methods:
raise tornado.web.HTTPError(405)
# Use the same method Tornado uses to validate the path
self.path = self.parse_url_path(path)
del path # make sure we don't refer to path instead of self.path again
absolute_path = self.get_absolute_path(self.root, self.path)
self.absolute_path = self.validate_absolute_path(
self.root, absolute_path)
if self.op_check_cb is not None:
try:
await self.op_check_cb(self.absolute_path)
except ServerError as e:
if e.status_code == 403:
raise tornado.web.HTTPError(
403, "File is loaded, DELETE not permitted")
os.remove(self.absolute_path)
base = self.request.path.lstrip("/").split("/")[2]
filename = self.path.lstrip("/")
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path)
file_manager = self.server.lookup_plugin('file_manager')
file_manager.notify_filelist_changed('delete_file', filename, base)
try:
filename = await file_manager.delete_file(path)
except self.server.error as e:
if e.status_code == 403:
raise tornado.web.HTTPError(
403, "File is loaded, DELETE not permitted")
else:
raise tornado.web.HTTPError(e.status_code, str(e))
self.finish({'result': filename})
class FileUploadHandler(AuthorizedRequestHandler):
def initialize(self, server, auth):
super(FileUploadHandler, self).initialize(server, auth)
async def post(self):
file_manager = self.server.lookup_plugin('file_manager')
try:
+84 -38
View File
@@ -8,6 +8,7 @@ import uuid
import os
import time
import ipaddress
import re
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
@@ -26,6 +27,11 @@ class Authorization:
self.trusted_connections = {}
self.access_tokens = {}
# Get allowed cors domains
cors_cfg = config.get('cors_domains', "").strip()
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
for d in cors_cfg.split('\n')if d.strip()]
# Get Trusted Clients
self.trusted_ips = []
self.trusted_ranges = []
@@ -52,11 +58,13 @@ class Authorization:
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\n"
f"Trusted Clients:\n{t_clients}")
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
@@ -65,18 +73,19 @@ class Authorization:
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", None, ['GET', 'POST'],
self._handle_apikey_request, http_only=True)
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
app.register_local_handler(
"/access/oneshot_token", None, ['GET'],
self._handle_token_request, http_only=True)
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, path, method, args):
if method.upper() == 'POST':
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, path, method, args):
async def _handle_token_request(self, web_request):
return self.get_access_token()
def _read_api_key(self):
@@ -175,63 +184,100 @@ class Authorization:
return True
return False
def check_cors(self, origin, request=None):
if origin is None:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self, origin, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self, server, auth):
self.server = server
self.auth = auth
def initialize(self):
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
conn = self.wsm.get_websocket(conn_id)
return conn
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, server, auth, path, default_filename=None):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = server
self.auth = auth
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def set_default_headers(self):
if self.settings['enable_cors']:
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
self.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.settings['enable_cors']:
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
+11 -3
View File
@@ -31,6 +31,12 @@ class ConfigHelper:
def __contains__(self, key):
return key in self.config
def get_name(self):
return self.section
def get_prefix_sections(self, prefix):
return [s for s in self.sections() if s.startswith(prefix)]
def getsection(self, section):
if section not in self.config:
raise ConfigError(f"No section [{section}] in config")
@@ -64,9 +70,9 @@ class ConfigHelper:
return self._get_item(
self.config[self.section].getfloat, option, default)
def get_configuration(server, cmd_line_args):
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
cmd_line_args.configfile))
system_args.configfile))
if not os.path.isfile(cfg_file_path):
raise ConfigError(f"Configuration File Not Found: '{cfg_file_path}''")
config = configparser.ConfigParser(interpolation=None)
@@ -83,5 +89,7 @@ def get_configuration(server, cmd_line_args):
if server_cfg.get('enable_debug_logging', True):
logging.getLogger().setLevel(logging.DEBUG)
config['cmd_args'] = {'logfile': cmd_line_args.logfile}
config['system_args'] = {
'logfile': system_args.logfile,
'software_version': system_args.software_version}
return ConfigHelper(server, config, 'server')
+187 -83
View File
@@ -13,7 +13,8 @@ import logging
import json
import confighelper
import utils
from tornado import iostream
import asyncio
from tornado import iostream, gen
from tornado.ioloop import IOLoop
from tornado.util import TimeoutError
from tornado.locks import Event
@@ -26,7 +27,7 @@ MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
CORE_PLUGINS = [
'file_manager', 'klippy_apis', 'machine',
'temperature_store', 'shell_command']
'data_store', 'shell_command']
class Sentinel:
pass
@@ -46,17 +47,12 @@ class Server:
'klippy_uds_address', "/tmp/klippy_uds")
self.klippy_connection = KlippyConnection(
self.process_command, self.on_connection_closed)
self.klippy_info = {}
self.init_list = []
self.init_handle = None
self.init_attempts = 0
self.klippy_state = "disconnected"
# XXX - currently moonraker maintains a superset of all
# subscriptions, the results of which are forwarded to all
# connected websockets. A better implementation would open a
# unique unix domain socket for each websocket client and
# allow Klipper to forward only those subscriptions back to
# correct client.
self.all_subscriptions = {}
self.subscriptions = {}
# Server/IOLoop
self.server_running = False
@@ -66,15 +62,23 @@ class Server:
self.register_upload_handler = app.register_upload_handler
self.ioloop = IOLoop.current()
self.register_endpoint(
"/server/info", ['GET'], self._handle_info_request)
self.register_endpoint(
"/server/restart", ['POST'], self._handle_server_restart)
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
self.pending_requests = {}
self.remote_methods = {}
self.klippy_reg_methods = []
self.register_remote_method(
'process_gcode_response', self._process_gcode_response)
'process_gcode_response', self._process_gcode_response,
need_klippy_reg=False)
self.register_remote_method(
'process_status_update', self._process_status_update)
'process_status_update', self._process_status_update,
need_klippy_reg=False)
# Plugin initialization
self.plugins = {}
@@ -82,8 +86,10 @@ class Server:
self._load_plugins(config)
def start(self):
hostname, hostport = self.get_host_info()
logging.info(
f"Starting Moonraker on ({self.host}, {self.port})")
f"Starting Moonraker on ({self.host}, {hostport}), "
f"Hostname: {hostname}")
self.moonraker_app.listen(self.host, self.port)
self.server_running = True
self.ioloop.spawn_callback(self._connect_klippy)
@@ -95,10 +101,10 @@ class Server:
self.load_plugin(config, plugin)
# check for optional plugins
opt_sections = set(config.sections()) - \
set(['server', 'authorization', 'cmd_args'])
opt_sections = set([s.split()[0] for s in config.sections()]) - \
set(['server', 'authorization', 'system_args'])
for section in opt_sections:
self.load_plugin(config[section], section, None)
self.load_plugin(config, section, None)
def load_plugin(self, config, plugin_name, default=Sentinel):
if plugin_name in self.plugins:
@@ -114,11 +120,16 @@ class Server:
return default
module = importlib.import_module("plugins." + plugin_name)
try:
load_func = getattr(module, "load_plugin")
func_name = "load_plugin"
if hasattr(module, "load_plugin_multi"):
func_name = "load_plugin_multi"
if plugin_name not in CORE_PLUGINS and func_name == "load_plugin":
config = config[plugin_name]
load_func = getattr(module, func_name)
plugin = load_func(config)
except Exception:
msg = f"Unable to load plugin ({plugin_name})"
logging.info(msg)
logging.exception(msg)
if default == Sentinel:
raise ServerError(msg)
return default
@@ -140,15 +151,27 @@ class Server:
for evt in events:
self.ioloop.spawn_callback(evt, *args)
def register_remote_method(self, method_name, cb):
def register_remote_method(self, method_name, cb, need_klippy_reg=True):
if method_name in self.remote_methods:
# XXX - may want to raise an exception here
logging.info(f"Remote method ({method_name}) already registered")
return
self.remote_methods[method_name] = cb
if need_klippy_reg:
# These methods need to be registered with Klippy
self.klippy_reg_methods.append(method_name)
def get_host_info(self):
hostname = socket.gethostname()
return hostname, self.port
def get_klippy_info(self):
return dict(self.klippy_info)
# ***** Klippy Connection *****
async def _connect_klippy(self):
if not self.server_running:
return
ret = await self.klippy_connection.connect(self.klippy_address)
if not ret:
self.ioloop.call_later(.25, self._connect_klippy)
@@ -160,10 +183,10 @@ class Server:
method = cmd.get('method', None)
if method is not None:
# This is a remote method called from klippy
cb = self.remote_methods.get(method, None)
if cb is not None:
if method in self.remote_methods:
params = cmd.get('params', {})
cb(**params)
self.ioloop.spawn_callback(
self._execute_method, method, **params)
else:
logging.info(f"Unknown method received: {method}")
return
@@ -184,17 +207,31 @@ class Server:
result = ServerError(err, 400)
request.notify(result)
async def _execute_method(self, method_name, **kwargs):
try:
ret = self.remote_methods[method_name](**kwargs)
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception(f"Error running remote method: {method_name}")
def on_connection_closed(self):
self.init_list = []
self.klippy_state = "disconnected"
for request in self.pending_requests.values():
request.notify(ServerError("Klippy Disconnected", 503))
self.pending_requests = {}
self.subscriptions = {}
logging.info("Klippy Connection Removed")
self.send_event("server:klippy_disconnect")
self.ioloop.call_later(.25, self._connect_klippy)
if self.init_handle is not None:
self.ioloop.remove_timeout(self.init_handle)
if self.server_running:
self.ioloop.call_later(.25, self._connect_klippy)
async def _initialize(self):
if not self.server_running:
return
await self._check_ready()
await self._request_endpoints()
# Subscribe to "webhooks"
@@ -217,14 +254,16 @@ class Server:
else:
logging.info("GCode Output Subscribed")
self.init_list.append("gcode_output_sub")
if "klippy_ready" in self.init_list:
# Moonraker is enabled in the Klippy module
# and Klippy is ready. We can stop the init
# procedure.
if "klippy_ready" in self.init_list or \
not self.klippy_connection.is_connected():
# Either Klippy is ready or the connection dropped
# during initialization. Exit initialization
self.init_attempts = 0
self.init_handle = None
else:
self.init_attempts += 1
self.ioloop.call_later(INIT_TIME, self._initialize)
self.init_handle = self.ioloop.call_later(
INIT_TIME, self._initialize)
async def _request_endpoints(self):
result = await self.klippy_apis.list_endpoints(default=None)
@@ -248,18 +287,18 @@ class Server:
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:
self.klippy_info = dict(result)
self.klippy_state = result.get('state', "unknown")
if self.klippy_state == "ready":
await self._verify_klippy_requirements()
logging.info("Klippy ready")
self.klippy_state = "ready"
self.init_list.append('klippy_ready')
# register methods with klippy
for method in self.klippy_reg_methods:
try:
await self.klippy_apis.register_method(method)
except ServerError:
logging.exception(f"Unable to register method '{method}'")
self.send_event("server:klippy_ready")
elif self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
self.init_attempts <= MAX_LOG_ATTEMPTS:
@@ -292,8 +331,7 @@ class Server:
vsd_path = vsd_config.get('path', None)
if vsd_path is not None:
file_manager = self.lookup_plugin('file_manager')
file_manager.register_directory(
'gcodes', vsd_path, can_delete=True)
file_manager.register_directory('gcodes', vsd_path)
else:
logging.info(
"Configuration for [virtual_sdcard] not found,"
@@ -311,49 +349,104 @@ class Server:
logging.info("Klippy has shutdown")
self.send_event("server:klippy_shutdown")
self.klippy_state = state
self.send_event("server:status_update", status)
for conn, sub in self.subscriptions.items():
conn_status = {}
for name, fields in sub.items():
if name in status:
val = status[name]
if fields is None:
conn_status[name] = dict(val)
else:
conn_status[name] = {
k: v for k, v in val.items() if k in fields}
conn.send_status(conn_status)
async def make_request(self, rpc_method, params):
# XXX - This adds the "response_template" to a subscription
# request and tracks all subscriptions so that each
# client gets what its requesting. In the future we should
# track subscriptions per client and send clients only
# the data they are asking for.
async def make_request(self, web_request):
rpc_method = web_request.get_endpoint()
if rpc_method == "objects/subscribe":
for obj, items in params.get('objects', {}).items():
if obj in self.all_subscriptions:
pi = self.all_subscriptions[obj]
return await self._request_subscripton(web_request)
else:
return await self._request_standard(web_request)
async def _request_subscripton(self, web_request):
args = web_request.get_args()
conn = web_request.get_connection()
# Build the subscription request from a superset of all client
# subscriptions
sub = args.get('objects', {})
if conn is None:
raise self.error(
"No connection associated with subscription request")
self.subscriptions[conn] = sub
all_subs = {}
# request superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
if obj in all_subs:
pi = all_subs[obj]
if items is None or pi is None:
self.all_subscriptions[obj] = None
all_subs[obj] = None
else:
uitems = list(set(pi) | set(items))
self.all_subscriptions[obj] = uitems
all_subs[obj] = uitems
else:
self.all_subscriptions[obj] = items
params['objects'] = dict(self.all_subscriptions)
params['response_template'] = {'method': "process_status_update"}
all_subs[obj] = items
args['objects'] = all_subs
args['response_template'] = {'method': "process_status_update"}
base_request = BaseRequest(rpc_method, params)
result = await self._request_standard(web_request)
# prune the status response
pruned_status = {}
all_status = result['status']
sub = self.subscriptions.get(conn, {})
for obj, fields in all_status.items():
if obj in sub:
valid_fields = sub[obj]
if valid_fields is None:
pruned_status[obj] = fields
else:
pruned_status[obj] = {k: v for k, v in fields.items()
if k in valid_fields}
result['status'] = pruned_status
return result
async def _request_standard(self, web_request):
rpc_method = web_request.get_endpoint()
args = web_request.get_args()
# Create a base klippy request
base_request = BaseRequest(rpc_method, args)
self.pending_requests[base_request.id] = base_request
self.ioloop.spawn_callback(
self.klippy_connection.send_request, base_request)
result = await base_request.wait()
return result
return await base_request.wait()
def remove_subscription(self, conn):
self.subscriptions.pop(conn, None)
async def _stop_server(self):
# XXX - Currently this function is not used.
# Should I expose functionality to shutdown
# or restart the server, or simply remove this?
logging.info(
"Shutting Down Webserver")
for plugin in self.plugins:
self.server_running = False
for name, plugin in self.plugins.items():
if hasattr(plugin, "close"):
await plugin.close()
ret = plugin.close()
if asyncio.iscoroutine(ret):
await ret
self.klippy_connection.close()
if self.server_running:
self.server_running = False
await self.moonraker_app.close()
self.ioloop.stop()
while self.klippy_state != "disconnected":
await gen.sleep(.1)
await self.moonraker_app.close()
self.ioloop.stop()
async def _handle_server_restart(self, web_request):
self.ioloop.spawn_callback(self._stop_server)
return "ok"
async def _handle_info_request(self, web_request):
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_state,
'plugins': list(self.plugins.keys())}
class KlippyConnection:
def __init__(self, on_recd, on_close):
@@ -456,12 +549,14 @@ def main():
parser.add_argument(
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
help="log file name and location")
cmd_line_args = parser.parse_args()
system_args = parser.parse_args()
# Setup Logging
log_file = os.path.normpath(os.path.expanduser(cmd_line_args.logfile))
cmd_line_args.logfile = log_file
ql = utils.setup_logging(log_file)
version = utils.get_software_version()
log_file = os.path.normpath(os.path.expanduser(system_args.logfile))
system_args.logfile = log_file
system_args.software_version = version
ql = utils.setup_logging(log_file, version)
if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \
@@ -473,20 +568,29 @@ def main():
# Start IOLoop and Server
io_loop = IOLoop.current()
try:
server = Server(cmd_line_args)
except Exception:
logging.exception("Moonraker Error")
ql.stop()
exit(1)
try:
server.start()
io_loop.start()
except Exception:
logging.exception("Server Running Error")
estatus = 0
while True:
try:
server = Server(system_args)
except Exception:
logging.exception("Moonraker Error")
estatus = 1
break
try:
server.start()
io_loop.start()
except Exception:
logging.exception("Server Running Error")
estatus = 1
break
# Since we are running outside of the the server
# it is ok to use a blocking sleep here
time.sleep(.5)
logging.info("Attempting Server Restart...")
io_loop.close(True)
logging.info("Server Shutdown")
ql.stop()
exit(estatus)
if __name__ == '__main__':
@@ -1,21 +1,25 @@
# Heater sensor temperature storage
# Klipper data logging and storage storage
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import time
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
TEMPERATURE_STORE_SIZE = 20 * 60
class TemperatureStore:
MAX_GCODE_LINES = 1000
class DataStore:
def __init__(self, config):
self.server = config.get_server()
# Temperature Store Tracking
self.last_temps = {}
self.gcode_queue = deque(maxlen=MAX_GCODE_LINES)
self.temperature_store = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
@@ -23,13 +27,18 @@ class TemperatureStore:
# Register status update event
self.server.register_event_handler(
"server:status_update", self._set_current_temps)
self.server.register_event_handler(
"server:gcode_response", self._update_gcode_store)
self.server.register_event_handler(
"server:klippy_ready", self._init_sensors)
# Register endpoint
# Register endpoints
self.server.register_endpoint(
"/server/temperature_store", "server_temperature_store", ['GET'],
"/server/temperature_store", ['GET'],
self._handle_temp_store_request)
self.server.register_endpoint(
"/server/gcode_store", ['GET'],
self._handle_gcode_store_request)
async def _init_sensors(self):
klippy_apis = self.server.lookup_plugin('klippy_apis')
@@ -89,7 +98,7 @@ class TemperatureStore:
self.temperature_store[sensor]['temperatures'].append(temp)
self.temperature_store[sensor]['targets'].append(target)
async def _handle_temp_store_request(self, path, method, args):
async def _handle_temp_store_request(self, web_request):
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
@@ -98,5 +107,17 @@ class TemperatureStore:
async def close(self):
self.temp_update_cb.stop()
def _update_gcode_store(self, response):
curtime = time.time()
self.gcode_queue.append({'message': response, 'time': curtime})
async def _handle_gcode_store_request(self, web_request):
count = web_request.get_int("count", None)
if count is not None:
res = list(self.gcode_queue)[-count:]
else:
res = list(self.gcode_queue)
return {'gcode_store': res}
def load_plugin(config):
return TemperatureStore(config)
return DataStore(config)
+309 -177
View File
@@ -6,59 +6,64 @@
import os
import sys
import shutil
import time
import io
import zipfile
import logging
import json
from tornado.ioloop import IOLoop
from tornado.locks import Lock
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Event
VALID_GCODE_EXTS = ['gcode', 'g', 'gco']
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py")
METADATA_SCRIPT = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
class FileManager:
def __init__(self, config):
self.server = config.get_server()
self.file_paths = {}
self.file_lists = {}
self.gcode_metadata = MetadataStorage(self.server)
self.fixed_path_args = {}
# Register file management endpoints
self.server.register_endpoint(
"/server/files/list", "file_list", ['GET'],
self._handle_filelist_request)
"/server/files/list", ['GET'], self._handle_filelist_request)
self.server.register_endpoint(
"/server/files/metadata", "file_metadata", ['GET'],
self._handle_metadata_request)
"/server/files/metadata", ['GET'], self._handle_metadata_request)
self.server.register_endpoint(
"/server/files/directory", "directory", ['GET', 'POST', 'DELETE'],
"/server/files/directory", ['GET', 'POST', 'DELETE'],
self._handle_directory_request)
self.server.register_endpoint(
"/server/files/move", "file_move", ['POST'],
self._handle_file_move_copy)
"/server/files/move", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/copy", "file_copy", ['POST'],
self._handle_file_move_copy)
"/server/files/copy", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
protocol=["websocket"])
# Register APIs to handle file uploads
self.server.register_upload_handler("/server/files/upload")
self.server.register_upload_handler("/api/files/local")
self.server.register_event_handler(
"server:klippy_ready", self._update_fixed_paths)
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
if config_path is not None:
ret = self.register_directory(
'config', config_path, can_delete=True)
ret = self.register_directory('config', config_path)
if not ret:
raise config.error(
"Option 'config_path' is not a valid directory")
def update_fixed_paths(self, paths):
def _update_fixed_paths(self):
kinfo = self.server.get_klippy_info()
paths = {k: kinfo.get(k) for k in
['klipper_path', 'python_path',
'log_file', 'config_file']}
if paths == self.fixed_path_args:
# No change in fixed paths
return
self.fixed_path_args = dict(paths)
self.fixed_path_args = paths
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
@@ -67,16 +72,15 @@ class FileManager:
if klipper_path is not None:
example_cfg_path = os.path.join(klipper_path, "config")
self.register_directory("config_examples", example_cfg_path)
docs_path = os.path.join(klipper_path, "docs")
self.register_directory("docs", docs_path)
# Register log path
log_file = paths.get('log_file')
log_path = os.path.normpath(os.path.expanduser(log_file))
self.server.register_static_file_handler("klippy.log", log_path)
def register_directory(self, base, path, can_delete=False):
op_check_cb = None
if base == 'gcodes':
op_check_cb = self._handle_operation_check
def register_directory(self, root, path):
if path is None:
return False
home = os.path.expanduser('~')
@@ -84,19 +88,21 @@ class FileManager:
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"
f"\nSupplied path ({path}) for ({root}) not valid. Please\n"
"check that the path exists and is a subfolder in the HOME\n"
"directory. Note that the path may not BE the home directory.")
return False
if path != self.file_paths.get(base, ""):
self.file_paths[base] = path
self.server.register_static_file_handler(
base, path, can_delete=can_delete, op_check_cb=op_check_cb)
try:
self._update_file_list(base=base)
except Exception:
logging.exception(
f"Unable to initialize file list: <{base}>")
if path != self.file_paths.get(root, ""):
self.file_paths[root] = path
self.server.register_static_file_handler(root, path)
if root == "gcodes":
# scan metadata
self.gcode_metadata.update_gcode_path(path)
try:
self.get_file_list("gcodes")
except Exception:
logging.exception(
f"Unable to initialize gcode metadata")
return True
def get_sd_directory(self):
@@ -105,55 +111,68 @@ class FileManager:
def get_fixed_path_args(self):
return dict(self.fixed_path_args)
async def _handle_filelist_request(self, path, method, args):
root = args.get('root', "gcodes")
return self.get_file_list(format_list=True, base=root)
async def _handle_filelist_request(self, web_request):
root = web_request.get_str('root', "gcodes")
return self.get_file_list(root, list_format=True, notify=True)
async def _handle_metadata_request(self, path, method, args):
requested_file = args.get('filename')
metadata = self.gcode_metadata.get(requested_file)
async def _handle_metadata_request(self, web_request):
requested_file = web_request.get_str('filename')
metadata = self.gcode_metadata.get(requested_file, None)
if metadata is None:
raise self.server.error(
f"Metadata not available for <{requested_file}>", 404)
metadata['filename'] = requested_file
return metadata
async def _handle_directory_request(self, path, method, args):
directory = args.get('path', "gcodes")
base, url_path, dir_path = self._convert_path(directory)
method = method.upper()
if method == 'GET':
async def _handle_directory_request(self, web_request):
directory = web_request.get_str('path', "gcodes")
root, rel_path, dir_path = self._convert_path(directory)
action = web_request.get_action()
if action == 'GET':
is_extended = web_request.get_boolean('extended', False)
# Get list of files and subdirectories for this target
return self._list_directory(dir_path)
elif method == 'POST' and base in FULL_ACCESS_ROOTS:
dir_info = self._list_directory(dir_path)
# Check to see if a filelist update is necessary
for f in dir_info['files']:
fname = os.path.join(rel_path, f['filename'])
ext = os.path.splitext(f['filename'])[-1].lower()
if root != 'gcodes' or ext not in VALID_GCODE_EXTS:
continue
self.gcode_metadata.parse_metadata(
fname, f['size'], f['modified'], notify=True)
metadata = self.gcode_metadata.get(fname, None)
if metadata is not None and is_extended:
f.update(metadata)
return dir_info
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
# Create a new directory
try:
os.mkdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed("create_dir", url_path, base)
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
self.notify_filelist_changed("create_dir", rel_path, root)
elif action == 'DELETE' and root in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == base:
if directory.strip("/") == root:
raise self.server.error(
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
f"Directory does not exist ({directory})")
force = args.get('force', False)
if isinstance(force, str):
force = force.lower() == "true"
force = web_request.get_boolean('force', False)
if force:
# Make sure that the directory does not contain a file
# loaded by the virtual_sdcard
await self._handle_operation_check(dir_path)
shutil.rmtree(dir_path)
if root == "gcodes":
self.gcode_metadata.prune_metadata()
else:
try:
os.rmdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed("delete_dir", url_path, base)
self.notify_filelist_changed("delete_dir", rel_path, root)
else:
raise self.server.error("Operation Not Supported", 405)
return "ok"
@@ -177,51 +196,58 @@ class FileManager:
ongoing = state in ["printing", "paused"]
return ongoing
def _convert_path(self, url_path):
parts = url_path.strip("/").split("/")
def _convert_path(self, request_path):
# Parse the root, relative path, and disk path from a remote request
parts = request_path.strip("/").split("/")
if not parts:
raise self.server.error(f"Invalid path: {url_path}")
base = parts[0]
if base not in self.file_paths:
raise self.server.error(f"Invalid base path ({base})")
root_path = local_path = self.file_paths[base]
url_path = ""
raise self.server.error(f"Invalid path: {request_path}")
root = parts[0]
if root not in self.file_paths:
raise self.server.error(f"Invalid root path ({root})")
disk_path = self.file_paths[root]
rel_path = ""
if len(parts) > 1:
url_path = "/".join(parts[1:])
local_path = os.path.join(root_path, url_path)
return base, url_path, local_path
rel_path = "/".join(parts[1:])
disk_path = os.path.join(disk_path, rel_path)
return root, rel_path, disk_path
async def _handle_file_move_copy(self, path, method, args):
source = args.get("source")
destination = args.get("dest")
async def _handle_file_move_copy(self, web_request):
source = web_request.get_str("source")
destination = web_request.get_str("dest")
ep = web_request.get_endpoint()
if source is None:
raise self.server.error("File move/copy request issing source")
if destination is None:
raise self.server.error(
"File move/copy request missing destination")
source_base, src_url_path, source_path = self._convert_path(source)
dest_base, dst_url_path, dest_path = self._convert_path(destination)
if dest_base not in FULL_ACCESS_ROOTS:
source_root, src_rel_path, source_path = self._convert_path(source)
dest_root, dst_rel_path, dest_path = self._convert_path(destination)
if dest_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Destination path is read-only: {dest_base}")
f"Destination path is read-only: {dest_root}")
if not os.path.exists(source_path):
raise self.server.error(f"File {source_path} does not exist")
# make sure the destination is not in use
if os.path.exists(dest_path):
await self._handle_operation_check(dest_path)
action = op_result = ""
if path == "/server/files/move":
if source_base not in FULL_ACCESS_ROOTS:
if ep == "/server/files/move":
if source_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Source path is read-only, cannot move: {source_base}")
f"Source path is read-only, cannot move: {source_root}")
# if moving the file, make sure the source is not in use
await self._handle_operation_check(source_path)
try:
op_result = shutil.move(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
if source_root == "gcodes":
if os.path.isdir(op_result):
self.gcode_metadata.prune_metadata()
else:
self.gcode_metadata.remove_file(src_rel_path)
action = "move_item"
elif path == "/server/files/copy":
elif ep == "/server/files/copy":
try:
if os.path.isdir(source_path):
op_result = shutil.copytree(source_path, dest_path)
@@ -231,11 +257,11 @@ class FileManager:
raise self.server.error(str(e))
action = "copy_item"
if op_result != dest_path:
dst_url_path = os.path.join(
dst_url_path, os.path.basename(op_result))
dst_rel_path = os.path.join(
dst_rel_path, os.path.basename(op_result))
self.notify_filelist_changed(
action, dst_url_path, dest_base,
{'path': src_url_path, 'root': source_base})
action, dst_rel_path, dest_root,
{'path': src_rel_path, 'root': source_root})
return "ok"
def _list_directory(self, path):
@@ -255,37 +281,11 @@ class FileManager:
return flist
def _get_path_info(self, path):
modified = time.ctime(os.path.getmtime(path))
modified = os.path.getmtime(path)
size = os.path.getsize(path)
path_info = {'modified': modified, 'size': size}
return path_info
def _update_file_list(self, base='gcodes', do_notify=False):
# Use os.walk find files in sd path and subdirs
path = self.file_paths.get(base, None)
if path is None:
msg = f"No known path for root: {base}"
logging.info(msg)
raise self.server.error(msg)
elif not os.path.isdir(path):
msg = f"Cannot generate file list for root: {base}"
logging.info(msg)
raise self.server.error(msg)
logging.info(f"Updating File List <{base}>...")
new_list = {}
for root, dirs, files in os.walk(path, followlinks=True):
for name in files:
ext = name[name.rfind('.')+1:]
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(root, name)
r_path = full_path[len(path) + 1:]
new_list[r_path] = self._get_path_info(full_path)
self.file_lists[base] = new_list
if base == 'gcodes':
self.gcode_metadata.refresh_metadata(new_list, path, do_notify)
return dict(new_list)
async def process_file_upload(self, request):
# lookup root file path
root = self._get_argument(request, 'root', "gcodes")
@@ -299,15 +299,20 @@ class FileManager:
async def _do_gcode_upload(self, request):
start_print = print_ongoing = False
base_path = self.file_paths.get("gcodes", "")
if not base_path:
root_path = self.file_paths.get("gcodes", "")
if not root_path:
raise self.server.error("Gcodes root not available")
start_print = self._get_argument(request, 'print', "false") == "true"
upload = self._get_upload_info(request, base_path)
upload = self._get_upload_info(request, root_path)
fparts = os.path.splitext(upload['full_path'])
is_ufp = fparts[-1].lower() == ".ufp"
# Verify that the operation can be done if attempting to upload a gcode
try:
check_path = upload['full_path']
if is_ufp:
check_path = fparts[0] + ".gcode"
print_ongoing = await self._handle_operation_check(
upload['full_path'])
check_path)
except self.server.error as e:
if e.status_code == 403:
raise self.server.error(
@@ -318,7 +323,12 @@ class FileManager:
start_print = False
# Don't start if another print is currently in progress
start_print = start_print and not print_ongoing
self._write_file(upload)
self._write_file(upload, is_ufp)
# Fetch Metadata
finfo = self._get_path_info(upload['full_path'])
evt = self.gcode_metadata.parse_metadata(
upload['filename'], finfo['size'], finfo['modified'])
await evt.wait()
if start_print:
# Make a Klippy Request to "Start Print"
klippy_apis = self.server.lookup_plugin('klippy_apis')
@@ -346,7 +356,7 @@ class FileManager:
return args[0].decode().strip()
return default
def _get_upload_info(self, request, base_path):
def _get_upload_info(self, request, root_path):
# check relative path
dir_path = self._get_argument(request, 'path', "")
# fetch the upload from the request
@@ -358,17 +368,18 @@ class FileManager:
raise self.server.error(
"Bad Request, can only process a single file upload")
upload = f_list[0]
if os.path.isfile(base_path):
filename = os.path.basename(base_path)
full_path = base_path
if os.path.isfile(root_path):
filename = os.path.basename(root_path)
full_path = root_path
dir_path = ""
else:
filename = "_".join(upload['filename'].strip().split()).lstrip("/")
parts = os.path.split(upload['filename'].strip().lstrip("/"))
filename = os.path.join(parts[0], "_".join(parts[1].split()))
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(base_path, filename))
full_path = os.path.normpath(os.path.join(root_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(base_path):
if not full_path.startswith(root_path):
raise self.server.error(
f"Cannot write to path: {full_path}")
return {
@@ -377,23 +388,79 @@ class FileManager:
'dir_path': dir_path,
'full_path': full_path}
def _write_file(self, upload):
def _write_file(self, upload, unzip_ufp=False):
try:
if upload['dir_path']:
os.makedirs(os.path.dirname(upload['full_path']), exist_ok=True)
with open(upload['full_path'], 'wb') as fh:
fh.write(upload['body'])
os.makedirs(os.path.dirname(
upload['full_path']), exist_ok=True)
if unzip_ufp:
self._unzip_ufp(upload)
else:
with open(upload['full_path'], 'wb') as fh:
fh.write(upload['body'])
except Exception:
raise self.server.error("Unable to save file", 500)
def get_file_list(self, format_list=False, base='gcodes'):
try:
filelist = self._update_file_list(base)
except Exception:
msg = "Unable to update file list"
logging.exception(msg)
# UFP Extraction Implementation inspired by by GitHub user @cdkeito
def _unzip_ufp(self, upload):
base_name = os.path.splitext(
os.path.basename(upload['filename']))[0]
working_dir = os.path.dirname(upload['full_path'])
thumb_dir = os.path.join(working_dir, "thumbs")
ufp_bytes = io.BytesIO(upload['body'])
gc_bytes = img_bytes = None
with zipfile.ZipFile(ufp_bytes) as zf:
gc_bytes = zf.read("/3D/model.gcode")
try:
img_bytes = zf.read("/Metadata/thumbnail.png")
except Exception:
img_bytes = None
if gc_bytes is not None:
gc_name = base_name + ".gcode"
gc_path = os.path.join(working_dir, gc_name)
with open(gc_path, "wb") as gc_file:
gc_file.write(gc_bytes)
# update upload file name to extracted gcode file
upload['full_path'] = gc_path
upload['filename'] = os.path.join(
os.path.dirname(upload['filename']), gc_name)
else:
raise self.server.error(
f"UFP file {upload['filename']} does not "
"contain a gcode file")
if img_bytes is not None:
thumb_name = base_name + ".png"
thumb_path = os.path.join(thumb_dir, thumb_name)
try:
if not os.path.exists(thumb_dir):
os.mkdir(thumb_dir)
with open(thumb_path, "wb") as thumb_file:
thumb_file.write(img_bytes)
except Exception:
logging.exception("Unable to write Image")
def get_file_list(self, root, list_format=False, notify=False):
# Use os.walk find files in sd path and subdirs
filelist = {}
path = self.file_paths.get(root, None)
if path is None or not os.path.isdir(path):
msg = f"Failed to build file list, invalid path: {root}: {path}"
logging.info(msg)
raise self.server.error(msg)
if format_list:
logging.info(f"Updating File List <{root}>...")
for root_path, dirs, files in os.walk(path, followlinks=True):
for name in files:
ext = os.path.splitext(name)[-1].lower()
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(root_path, name)
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
if root == 'gcodes':
self.gcode_metadata.parse_metadata(
fname, finfo['size'], finfo['modified'], notify)
if list_format:
flist = []
for fname in sorted(filelist, key=str.lower):
fdict = {'filename': fname}
@@ -411,7 +478,7 @@ class FileManager:
if filename.startswith('gcodes/'):
filename = filename[7:]
flist = self.get_file_list()
flist = self.get_file_list("gcodes")
return self.gcode_metadata.get(filename, flist.get(filename, {}))
def list_dir(self, directory, simple_format=False):
@@ -439,45 +506,86 @@ class FileManager:
simple_list.append("*" + dirobj['dirname'])
for fileobj in flist['files']:
fname = fileobj['filename']
ext = fname[fname.rfind('.')+1:]
ext = os.path.splitext(fname)[-1].lower()
if root == "gcodes" and ext in VALID_GCODE_EXTS:
simple_list.append(fname)
return simple_list
return flist
def delete_file(self, path):
parts = path.split("/", 1)
async def _handle_file_delete(self, web_request):
file_path = web_request.get_str("path")
return await self.delete_file(file_path)
async def delete_file(self, path):
parts = path.lstrip("/").split("/", 1)
if len(parts) != 2:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root = parts[0]
if root not in self.file_paths or len(parts) != 2:
raise self.server.error(f"Invalid file path: {path}")
filename = parts[1]
if root not in self.file_paths or root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root_path = self.file_paths[root]
full_path = os.path.join(root_path, parts[1])
full_path = os.path.join(root_path, filename)
if not os.path.isfile(full_path):
raise self.server.error(f"Invalid file path: {path}")
if root == "gcodes":
try:
await self._handle_operation_check(full_path)
except self.server.error as e:
if e.status_code == 403:
raise
self.gcode_metadata.remove_file(filename)
os.remove(full_path)
self.notify_filelist_changed('delete_file', filename, root)
return filename
def notify_filelist_changed(self, action, fname, base, source_item={}):
self._update_file_list(base, do_notify=True)
file_info = dict(self.file_lists[base].get(
fname, {'size': 0, 'modified': ""}))
file_info.update({'path': fname, 'root': base})
def notify_filelist_changed(self, action, fname, root, source_item={}):
flist = self.get_file_list(root, notify=True)
file_info = flist.get(fname, {'size': 0, 'modified': 0})
file_info.update({'path': fname, 'root': root})
result = {'action': action, 'item': file_info}
if source_item:
result.update({'source_item': source_item})
self.server.send_event("file_manager:filelist_changed", result)
def close(self):
self.gcode_metadata.close()
METADATA_PRUNE_TIME = 600000
class MetadataStorage:
def __init__(self, server):
self.server = server
self.lock = Lock()
self.metadata = {}
self.pending_requests = {}
self.events = {}
self.script_response = None
self.busy = False
self.gc_path = os.path.expanduser("~")
self.prune_cb = PeriodicCallback(
self.prune_metadata, METADATA_PRUNE_TIME)
def update_gcode_path(self, path):
if path == self.gc_path:
return
self.metadata = {}
self.gc_path = path
if not self.prune_cb.is_running():
self.prune_cb.start()
def close(self):
self.prune_cb.stop()
def get(self, key, default=None):
return self.metadata.get(key, default)
if key not in self.metadata:
return default
return dict(self.metadata[key])
def __getitem__(self, key):
return self.metadata[key]
return dict(self.metadata[key])
def _handle_script_response(self, result):
try:
@@ -492,40 +600,61 @@ class MetadataStorage:
if 'file' in proc_resp:
self.script_response = proc_resp
def refresh_metadata(self, filelist, gc_path, do_notify=False):
IOLoop.current().spawn_callback(
self._do_metadata_update, filelist, gc_path, do_notify)
def prune_metadata(self):
for fname in list(self.metadata.keys()):
fpath = os.path.join(self.gc_path, fname)
if not os.path.exists(fpath):
del self.metadata[fname]
logging.info(f"Pruned file: {fname}")
continue
async def _do_metadata_update(self, filelist, gc_path, do_notify=False):
async with self.lock:
exisiting_data = {}
update_list = []
for fname, fdata in filelist.items():
mdata = self.metadata.get(fname, {})
if mdata.get('size', "") == fdata.get('size') \
and mdata.get('modified', "") == fdata.get('modified'):
# file metadata has already been extracted
exisiting_data[fname] = mdata
else:
update_list.append(fname)
self.metadata = exisiting_data
for fname in update_list:
retries = 3
while retries:
try:
await self._extract_metadata(fname, gc_path, do_notify)
except Exception:
logging.exception("Error running extract_metadata.py")
retries -= 1
else:
break
else:
logging.info(
f"Unable to extract medatadata from file: {fname}")
def _has_valid_data(self, fname, fsize, modified):
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
return mdata['size'] == fsize and mdata['modified'] == modified
async def _extract_metadata(self, filename, path, do_notify=False):
def remove_file(self, fname):
self.metadata.pop(fname)
def parse_metadata(self, fname, fsize, modified, notify=False):
evt = Event()
if fname in self.pending_requests or \
self._has_valid_data(fname, fsize, modified):
# request already pending or not necessary
evt.set()
return evt
self.pending_requests[fname] = (fsize, modified, notify, evt)
if self.busy:
return evt
self.busy = True
IOLoop.current().spawn_callback(self._process_metadata_update)
return evt
async def _process_metadata_update(self):
while self.pending_requests:
fname, (fsize, modified, notify, evt) = \
self.pending_requests.popitem()
if self._has_valid_data(fname, fsize, modified):
evt.set()
continue
retries = 3
while retries:
try:
await self._run_extract_metadata(fname, notify)
except Exception:
logging.exception("Error running extract_metadata.py")
retries -= 1
else:
break
else:
self.metadata[fname] = {'size': fsize, 'modified': modified}
logging.info(
f"Unable to extract medatadata from file: {fname}")
evt.set()
self.busy = False
async def _run_extract_metadata(self, filename, notify):
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
path, "-f", "'" + filename + "'"])
self.gc_path, "-f", "'" + filename + "'"])
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(
cmd, self._handle_script_response)
@@ -535,9 +664,12 @@ class MetadataStorage:
raise self.server.error("Unable to extract metadata")
path = self.script_response['file']
metadata = self.script_response['metadata']
if not metadata:
# This indicates an error, do not add metadata for this
raise self.server.error("Unable to extract metadata")
self.metadata[path] = dict(metadata)
metadata['filename'] = path
if do_notify:
if notify:
self.server.send_event(
"file_manager:metadata_update", metadata)
+42 -22
View File
@@ -4,6 +4,7 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import utils
from websockets import WebRequest
INFO_ENDPOINT = "info"
ESTOP_ENDPOINT = "emergency_stop"
@@ -13,6 +14,7 @@ GCODE_ENDPOINT = "gcode/script"
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
STATUS_ENDPOINT = "objects/query"
OBJ_LIST_ENDPOINT = "objects/list"
REG_METHOD_ENDPOINT = "register_remote_method"
class Sentinel:
pass
@@ -21,48 +23,47 @@ class KlippyAPI:
def __init__(self, config):
self.server = config.get_server()
# Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them
self.host_subscription = {}
# Register GCode Aliases
self.server.register_endpoint(
"/printer/print/pause", "printer_print_pause", ['POST'],
self._gcode_pause)
"/printer/print/pause", ['POST'], self._gcode_pause)
self.server.register_endpoint(
"/printer/print/resume", "printer_print_resume", ['POST'],
self._gcode_resume)
"/printer/print/resume", ['POST'], self._gcode_resume)
self.server.register_endpoint(
"/printer/print/cancel", "printer_print_cancel", ['POST'],
self._gcode_cancel)
"/printer/print/cancel", ['POST'], self._gcode_cancel)
self.server.register_endpoint(
"/printer/print/start", "printer_print_start", ['POST'],
self._gcode_start_print)
"/printer/print/start", ['POST'], self._gcode_start_print)
self.server.register_endpoint(
"/printer/restart", "printer_restart", ['POST'],
self._gcode_restart)
"/printer/restart", ['POST'], self._gcode_restart)
self.server.register_endpoint(
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
self._gcode_firmware_restart)
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
async def _gcode_pause(self, path, method, args):
async def _gcode_pause(self, web_request):
return await self.run_gcode("PAUSE")
async def _gcode_resume(self, path, method, args):
async def _gcode_resume(self, web_request):
return await self.run_gcode("RESUME")
async def _gcode_cancel(self, path, method, args):
async def _gcode_cancel(self, web_request):
return await self.run_gcode("CANCEL_PRINT")
async def _gcode_start_print(self, path, method, args):
filename = args.get('filename')
async def _gcode_start_print(self, web_request):
filename = web_request.get_str('filename')
return await self.start_print(filename)
async def _gcode_restart(self, path, method, args):
async def _gcode_restart(self, web_request):
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, path, method, args):
async def _gcode_firmware_restart(self, web_request):
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(self, method, params, default=Sentinel):
try:
result = await self.server.make_request(method, params)
result = await self.server.make_request(
WebRequest(method, params, conn=self))
except self.server.error as e:
if default == Sentinel:
raise
@@ -79,7 +80,7 @@ class KlippyAPI:
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
script = "SDCARD_PRINT_FILE FILENAME=" + filename
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
return await self.run_gcode(script)
async def do_restart(self, gc):
@@ -122,7 +123,17 @@ class KlippyAPI:
return result
async def subscribe_objects(self, objects, default=Sentinel):
params = {'objects': objects}
for obj, items in objects.items():
if obj in self.host_subscription:
prev = self.host_subscription[obj]
if items is None or prev is None:
self.host_subscription[obj] = None
else:
uitems = list(set(prev) | set(items))
self.host_subscription[obj] = uitems
else:
self.host_subscription[obj] = items
params = {'objects': self.host_subscription}
result = await self._send_klippy_request(
SUBSCRIPTION_ENDPOINT, params, default)
if isinstance(result, dict) and 'status' in result:
@@ -135,5 +146,14 @@ class KlippyAPI:
return await self._send_klippy_request(
GC_OUTPUT_ENDPOINT, template, default)
async def register_method(self, method_name):
return await self._send_klippy_request(
REG_METHOD_ENDPOINT,
{'response_template': {"method": method_name},
'remote_method': method_name})
def send_status(self, status):
self.server.send_event("server:status_update", status)
def load_plugin(config):
return KlippyAPI(config)
+40 -10
View File
@@ -4,31 +4,61 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
from tornado.ioloop import IOLoop
class Machine:
def __init__(self, config):
self.server = config.get_server()
self.server.register_endpoint(
"/machine/reboot", "machine_reboot", ['POST'],
self._handle_machine_request)
"/machine/reboot", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
"/machine/shutdown", "machine_shutdown", ['POST'],
self._handle_machine_request)
"/machine/shutdown", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
"/machine/services/restart", ['POST'],
self._handle_service_restart)
async def _handle_machine_request(self, path, method, args):
if path == "/machine/shutdown":
cmd = "sudo shutdown now"
elif path == "/machine/reboot":
cmd = "sudo reboot now"
# Register remote methods
self.server.register_remote_method(
"shutdown_machine", self.shutdown_machine)
self.server.register_remote_method(
"reboot_machine", self.reboot_machine)
async def _handle_machine_request(self, web_request):
ep = web_request.get_endpoint()
if ep == "/machine/shutdown":
await self.shutdown_machine()
elif ep == "/machine/reboot":
await self.reboot_machine()
else:
raise self.server.error("Unsupported machine request")
return "ok"
async def shutdown_machine(self):
await self._execute_cmd("sudo shutdown now")
async def reboot_machine(self):
await self._execute_cmd("sudo shutdown -r now")
async def _handle_service_restart(self, web_request):
name = web_request.get('service')
if name == "klipper":
await self._execute_cmd(f'sudo systemctl restart {name}')
elif name == "moonraker":
IOLoop.current().spawn_callback(
self._execute_cmd, f'sudo systemctl restart {name}')
else:
raise self.sever.error(
f"Invalid argument recevied for 'name': {name}")
return "ok"
async def _execute_cmd(self, cmd):
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception(f"Error running cmd '{cmd}'")
return "ok"
raise
def load_plugin(config):
return Machine(config)
+51 -48
View File
@@ -9,6 +9,7 @@ import time
import json
import errno
import logging
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
@@ -19,6 +20,7 @@ MIN_EST_TIME = 10.
class PanelDueError(ServerError):
pass
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
@@ -139,6 +141,8 @@ class PanelDue:
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
self.enable_checksum = config.getboolean('enable_checksum', True)
self.debug_queue = deque(maxlen=100)
# Initialize tracked state.
self.printer_state = {
@@ -154,7 +158,6 @@ class PanelDue:
# Set up macros
self.confirmed_gcode = ""
self.mbox_sequence = 0
self.beep_sequence = 0
self.available_macros = {}
self.confirmed_macros = {
"RESTART": "RESTART",
@@ -189,6 +192,9 @@ class PanelDue:
self.server.register_event_handler(
"server:gcode_response", self.handle_gcode_response)
self.server.register_remote_method(
"paneldue_beep", self.paneldue_beep)
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
@@ -285,62 +291,55 @@ class PanelDue:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
if "gcode_macro PANELDUE_BEEP" in status:
# This only processes a paneldue beep when the macro's
# variables have changed
params = self.printer_state["gcode_macro PANELDUE_BEEP"]
try:
self.handle_paneldue_beep(**params)
except Exception:
logging.exception("Unable to process PANELDUE_BEEP")
def handle_paneldue_beep(self, sequence, frequency, duration):
if sequence != self.beep_sequence:
self.beep_sequence = sequence
duration = int(duration * 1000.)
self.ioloop.spawn_callback(
self.write_response,
{'beep_freq': frequency, 'beep_length': duration})
async def paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
await self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self.klippy_apis.emergency_stop()
return
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
if self.enable_checksum:
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Verify checksum
cs_index = line.rfind('*')
try:
checksum = int(line[cs_index+1:])
except Exception:
# Invalid checksum, do not process
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.exception("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
# Checksum is calculated by XORing every byte in the line other
# than the checksum itself
calculated_cs = 0
for c in line[:cs_index]:
calculated_cs ^= ord(c)
if calculated_cs & 0xFF != checksum:
msg = "!! Invalid Checksum"
if line_no is not None:
msg += f" Line Number: {line_no}"
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
await self._run_gcode(line[line_index+1:cs_index])
await self._run_gcode(line[line_index+1:cs_index])
else:
await self._run_gcode(line)
async def _run_gcode(self, script):
# Execute the gcode. Check for special RRF gcodes that
@@ -666,7 +665,7 @@ class PanelDue:
if not path.startswith("gcodes/"):
path = "gcodes/" + path
self.file_manager.delete_file(path)
await self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
response = {}
@@ -701,7 +700,7 @@ class PanelDue:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + metadata['modified']
response['lastModified'] = "T" + time.ctime(metadata['modified'])
slicer = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
@@ -723,6 +722,10 @@ class PanelDue:
async def close(self):
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
msg += f"\nSequence {i}: {gc}"
logging.debug(msg)
def load_plugin(config):
return PanelDue(config)
+366 -133
View File
@@ -6,169 +6,402 @@
import logging
import os
import asyncio
import json
import struct
import socket
import gpiod
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from tornado.escape import json_decode
class PrinterPower:
def __init__(self, config):
self.server = config.get_server()
self.server.register_endpoint(
"/printer/power/devices", "power_devices", ['GET'],
"/machine/device_power/devices", ['GET'],
self._handle_list_devices)
self.server.register_endpoint(
"/printer/power/status", "power_status", ['GET'],
"/machine/device_power/status", ['GET'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/on", "power_on", ['POST'],
"/machine/device_power/on", ['POST'],
self._handle_power_request)
self.server.register_endpoint(
"/printer/power/off", "power_off", ['POST'],
"/machine/device_power/off", ['POST'],
self._handle_power_request)
self.server.register_remote_method(
"set_device_power", self.set_device_power)
self.chip_factory = GpioChipFactory()
self.current_dev = None
self.devices = {}
dev_names = config.get('devices')
dev_names = [d.strip() for d in dev_names.split(',') if d.strip()]
logging.info("Power plugin loading devices: " + str(dev_names))
devices = {}
for dev in dev_names:
pin = config.getint(dev + "_pin")
name = config.get(dev + "_name", dev)
active_low = config.getboolean(dev + "_active_low", False)
devices[dev] = {
"name": name,
"pin": pin,
"active_low": int(active_low),
"status": None
}
ioloop = IOLoop.current()
ioloop.spawn_callback(self.initialize_devices, devices)
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power plugin loading devices: {prefix_sections}")
for section in prefix_sections:
cfg = config[section]
dev_type = cfg.get("type")
if dev_type == "gpio":
dev = GpioDevice(cfg, self.chip_factory)
elif dev_type == "tplink_smartplug":
dev = TPLinkSmartPlug(cfg)
elif dev_type == "tasmota":
dev = Tasmota(cfg)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
self.devices[dev.get_name()] = dev
async def _handle_list_devices(self, path, method, args):
output = {"devices": []}
for dev in self.devices:
output['devices'].append({
"name": self.devices[dev]["name"],
"id": dev
})
async def _handle_list_devices(self, web_request):
dev_list = [d.get_device_info() for d in self.devices.values()]
output = {"devices": dev_list}
return output
async def _handle_power_request(self, path, method, args):
if len(args) == 0:
if path == "/printer/power/status":
args = self.devices
else:
return "no_devices"
async def _handle_power_request(self, web_request):
args = web_request.get_args()
ep = web_request.get_endpoint()
if not args:
raise self.server.error("No arguments provided")
requsted_devs = {k: self.devices.get(k, None) for k in args}
result = {}
for dev in args:
if dev not in self.devices:
result[dev] = "device_not_found"
continue
await GPIO.verify_pin(self.devices[dev]["pin"],
self.devices[dev]["active_low"])
if path == "/printer/power/on":
GPIO.set_pin_value(self.devices[dev]["pin"], 1)
elif path == "/printer/power/off":
GPIO.set_pin_value(self.devices[dev]["pin"], 0)
elif path != "/printer/power/status":
raise self.server.error("Unsupported power request")
self.devices[dev]["status"] = GPIO.is_pin_on(
self.devices[dev]["pin"])
result[dev] = self.devices[dev]["status"]
req = ep.split("/")[-1]
for name, device in requsted_devs.items():
if device is not None:
result[name] = await self._process_request(device, req)
else:
result[name] = "device_not_found"
return result
async def initialize_devices(self, devices):
for name, device in devices.items():
try:
logging.debug(
f"Attempting to configure pin GPIO{device['pin']}")
await GPIO.setup_pin(device["pin"], device["active_low"])
device["status"] = GPIO.is_pin_on(device["pin"])
except Exception:
logging.exception(
f"Power plugin: ERR Problem configuring the output pin for"
f" device {name}. Removing device")
continue
self.devices[name] = device
async def _process_request(self, device, req):
if req in ["on", "off"]:
ret = device.set_power(req)
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
self.server.send_event("gpio_power:power_changed", dev_info)
elif req == "status":
ret = device.refresh_status()
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
else:
raise self.server.error(f"Unsupported power request: {req}")
return dev_info['status']
class GPIO:
gpio_root = "/sys/class/gpio"
@staticmethod
def _set_gpio_option(pin, option, value):
GPIO._write(
os.path.join(GPIO.gpio_root, f"gpio{pin}", option),
value
)
@staticmethod
def _get_gpio_option(pin, option):
return GPIO._read(
os.path.join(GPIO.gpio_root, f"gpio{pin}", option)
)
@staticmethod
def _write(file, data):
with open(file, 'w') as f:
f.write(str(data))
f.flush()
@staticmethod
def _read(file):
with open(file, 'r') as f:
f.seek(0)
return f.read().strip()
@staticmethod
async def verify_pin(pin, active_low=1):
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
if not os.path.exists(gpiopath):
logging.info(f"Re-intializing GPIO{pin}")
await GPIO.setup_pin(pin, active_low)
def set_device_power(self, device, state):
status = None
if isinstance(state, bool):
status = "on" if state else "off"
elif isinstance(state, str):
status = state.lower()
if status in ["true", "false"]:
status = "on" if status == "true" else "off"
if status not in ["on", "off"]:
logging.info(f"Invalid state received: {state}")
return
if device not in self.devices:
logging.info(f"No device found: {device}")
return
ioloop = IOLoop.current()
ioloop.spawn_callback(
self._process_request, self.devices[device], status)
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
async def add_device(self, name, device):
if name in self.devices:
raise self.server.error(
f"Device [{name}] already configured")
ret = device.initialize()
if asyncio.iscoroutine(ret):
await ret
self.devices[name] = device
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
@staticmethod
async def setup_pin(pin, active_low=1):
pin = int(pin)
active_low = 1 if active_low == 1 else 0
gpiopath = os.path.join(GPIO.gpio_root, f"gpio{pin}")
if not os.path.exists(gpiopath):
GPIO._write(
os.path.join(GPIO.gpio_root, "export"),
pin)
logging.info(f"Waiting for GPIO{pin} to initialize")
while os.stat(os.path.join(
GPIO.gpio_root, f"gpio{pin}",
"active_low")).st_gid == 0:
await gen.sleep(.1)
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
GPIO._set_gpio_option(pin, "active_low", active_low)
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
GPIO._set_gpio_option(pin, "direction", "out")
async def close(self):
for device in self.devices.values():
if hasattr(device, "close"):
ret = device.close()
if asyncio.iscoroutine(ret):
await ret
self.chip_factory.close()
@staticmethod
def is_pin_on(pin):
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
class GpioChipFactory:
def __init__(self):
self.chips = {}
@staticmethod
def set_pin_value(pin, active):
value = 1 if (active == 1) else 0
GPIO._set_gpio_option(pin, "value", value)
def get_gpio_chip(self, chip_name):
if chip_name in self.chips:
return self.chips[chip_name]
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
self.chips[chip_name] = chip
return chip
def close(self):
for chip in self.chips.values():
chip.close()
class GpioDevice:
def __init__(self, config, chip_factory):
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
pin, chip_id, invert = self._parse_pin(config)
try:
chip = chip_factory.get_gpio_chip(chip_id)
self.line = chip.get_line(pin)
if invert:
self.line.request(
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT,
flags=gpiod.LINE_REQ_FLAG_ACTIVE_LOW)
else:
self.line.request(
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT)
except Exception:
self.state = "error"
logging.exception(
f"Unable to init {pin}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise config.error("Power GPIO Config Error")
self.set_power("off")
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
invert = False
if pin[0] == "!":
pin = pin[1:]
invert = True
chip_id = "gpiochip0"
pin_parts = pin.split("/")
if len(pin_parts) == 2:
chip_id, pin = pin_parts
elif len(pin_parts) == 1:
pin = pin_parts[0]
# Verify pin
if not chip_id.startswith("gpiochip") or \
not chip_id[-1].isdigit() or \
not pin.startswith("gpio") or \
not pin[4:].isdigit():
raise config.error(
f"Invalid Power Pin configuration: {cfg_pin}")
pin = int(pin[4:])
return pin, chip_id, invert
def initialize(self):
pass
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'type': "gpio"
}
def refresh_status(self):
try:
val = self.line.get_value()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if val else "off"
def set_power(self, state):
try:
self.line.set_value(int(state == "on"))
except Exception:
self.state = "error"
msg = f"Error Toggling Device Power: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
def close(self):
self.line.release()
def load_plugin(config):
# This implementation based off the work tplink_smartplug
# script by Lubomir Stroetmann available at:
#
# https://github.com/softScheck/tplink-smartplug
#
# Copyright 2016 softScheck GmbH
class TPLinkSmartPlug:
START_KEY = 0xAB
def __init__(self, config):
self.server = config.get_server()
self.addr = config.get("address")
self.port = config.getint("port", 9999)
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tplink_command(self, command):
out_cmd = {}
if command in ["on", "off"]:
out_cmd = {'system': {'set_relay_state':
{'state': int(command == "on")}}}
elif command == "info":
out_cmd = {'system': {'get_sysinfo': {}}}
else:
raise self.server.error(f"Invalid tplink command: {command}")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
stream = IOStream(s)
try:
await stream.connect((self.addr, self.port))
await stream.write(self._encrypt(out_cmd))
data = await stream.read_bytes(2048, partial=True)
length = struct.unpack(">I", data[:4])[0]
data = data[4:]
retries = 5
remaining = length - len(data)
while remaining and retries:
data += await stream.read_bytes(remaining)
remaining = length - len(data)
retries -= 1
if not retries:
raise self.server.error("Unable to read tplink packet")
except Exception:
msg = f"Error sending tplink command: {command}"
logging.exception(msg)
raise self.server.error(msg)
finally:
stream.close()
return json.loads(self._decrypt(data))
def _encrypt(self, data):
data = json.dumps(data)
key = self.START_KEY
res = struct.pack(">I", len(data))
for c in data:
val = key ^ ord(c)
key = val
res += bytes([val])
return res
def _decrypt(self, data):
key = self.START_KEY
res = ""
for c in data:
val = key ^ c
key = c
res += chr(val)
return res
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'type': "tplink_smartplug"
}
async def refresh_status(self):
try:
res = await self._send_tplink_command("info")
state = res['system']['get_sysinfo']['relay_state']
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
async def set_power(self, state):
try:
res = await self._send_tplink_command(state)
err = res['system']['set_relay_state']['err_code']
except Exception:
err = 1
logging.exception(f"Power Toggle Error: {self.name}")
if err:
self.state = "error"
raise self.server.error(
f"Error Toggling Device Power: {self.name}")
self.state = state
class Tasmota:
def __init__(self, config):
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tasmota_command(self, command, password=None):
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
elif command == "info":
out_cmd = "Power{self.output_id}"
else:
raise self.server.error(f"Invalid tasmota command: {command}")
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
data = ""
http_client = AsyncHTTPClient()
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending tplink command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'type': "tasmota"
}
async def refresh_status(self):
try:
res = await self._send_tasmota_command("info")
state = res[f"POWER{self.output_id}"].lower()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
async def set_power(self, state):
try:
res = await self._send_tasmota_command(state)
state = res[f"POWER{self.output_id}"].lower()
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
# The power plugin has multiple configuration sections
def load_plugin_multi(config):
return PrinterPower(config)
+37 -14
View File
@@ -12,13 +12,14 @@ from tornado import gen
from tornado.ioloop import IOLoop
class ShellCommand:
def __init__(self, cmd, callback=None):
def __init__(self, cmd, callback):
self.io_loop = IOLoop.current()
self.name = cmd
self.output_cb = callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.partial_output = b""
self.cancelled = False
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
@@ -28,19 +29,22 @@ class ShellCommand:
except Exception:
return
data = self.partial_output + data
if b'\n' not in data:
self.partial_output = data
return
elif data[-1] != b'\n':
split = data.rfind(b'\n') + 1
self.partial_output = data[split:]
data = data[:split]
try:
self.output_cb(data)
except Exception:
logging.exception("Error writing command output")
lines = data.split(b'\n')
self.partial_output = lines.pop()
for line in lines:
try:
self.output_cb(line)
except Exception:
logging.exception("Error writing command output")
def cancel(self):
self.cancelled = True
async def run(self, timeout=2., verbose=True):
fd = None
if timeout is None:
# Never timeout
timeout = 9999999999999999.
if not timeout or self.output_cb is None:
# Fire and forget commands cannot be verbose as we can't
# clean up after the process terminates
@@ -58,7 +62,7 @@ class ShellCommand:
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
elif not timeout:
# fire and forget, return from execution
return
return True
sleeptime = 0
complete = False
while sleeptime < timeout:
@@ -67,6 +71,8 @@ class ShellCommand:
if proc.poll() is not None:
complete = True
break
if self.cancelled:
break
if not complete:
proc.terminate()
if verbose:
@@ -75,13 +81,30 @@ class ShellCommand:
self.partial_output = b""
if complete:
msg = f"Command ({self.name}) finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
else:
msg = f"Command ({self.name}) timed out"
logging.info(msg)
self.io_loop.remove_handler(fd)
return complete
async def run_with_response(self, timeout=2.):
result = []
def cb(data):
data = data.strip()
if data:
result.append(data.decode())
prev_cb = self.output_cb
self.output_cb = cb
await self.run(timeout)
self.output_cb = prev_cb
return "\n".join(result)
class ShellCommandFactory:
def build_shell_command(self, cmd, callback):
def build_shell_command(self, cmd, callback=None):
return ShellCommand(cmd, callback)
def load_plugin(config):
+475
View File
@@ -0,0 +1,475 @@
# Provides updates for Klipper and Moonraker
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import re
import logging
import json
import sys
import shutil
import zipfile
import io
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
# TODO: May want to attempt to look up the disto for the correct
# klippy install script or have the user configure it
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
REPO_PREFIX = "https://api.github.com/repos"
REPO_DATA = {
'moonraker': {
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
'origin': "https://github.com/Arksine/moonraker.git",
'install_script': "scripts/install-moonraker.sh",
'requirements': "scripts/moonraker-requirements.txt",
'venv_args': "-p python3 --system-site-packages"
},
'klipper': {
'repo_url': f"{REPO_PREFIX}/kevinoconnor/klipper/branches/master",
'origin': "https://github.com/KevinOConnor/klipper.git",
'install_script': "scripts/install-octopi.sh",
'requirements': "scripts/klippy-requirements.txt",
'venv_args': "-p python2"
}
}
class UpdateManager:
def __init__(self, config):
self.server = config.get_server()
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
sw_version = config['system_args'].get('software_version')
self.updaters = {
"system": PackageUpdater(self),
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH,
sw_version, sys.executable)
}
self.current_update = None
client_repo = config.get("client_repo", None)
if client_repo is not None:
client_path = os.path.expanduser(config.get("client_path"))
if os.path.islink(client_path):
raise config.error(
"Option 'client_path' cannot be set to a symbolic link")
self.updaters['client'] = ClientUpdater(
self, client_repo, client_path)
self.server.register_endpoint(
"/machine/update/moonraker", ["POST"],
self._handle_update_request)
self.server.register_endpoint(
"/machine/update/klipper", ["POST"],
self._handle_update_request)
self.server.register_endpoint(
"/machine/update/system", ["POST"],
self._handle_update_request)
self.server.register_endpoint(
"/machine/update/client", ["POST"],
self._handle_update_request)
self.server.register_endpoint(
"/machine/update/status", ["GET"],
self._handle_status_request)
# Register Ready Event
self.server.register_event_handler(
"server:klippy_ready", self._set_klipper_repo)
async def _set_klipper_repo(self):
kinfo = self.server.get_klippy_info()
if not kinfo:
logging.info("No valid klippy info received")
return
kpath = kinfo['klipper_path']
kversion = kinfo['software_version']
env = kinfo['python_path']
self.updaters['klipper'] = GitUpdater(
self, "klipper", kpath, kversion, env)
async def _check_versions(self):
for updater in self.updaters.values():
await updater.check_remote_version()
async def _handle_update_request(self, web_request):
app = web_request.get_endpoint().split("/")[-1]
inc_deps = web_request.get_boolean('include_deps', False)
if self.current_update:
raise self.server.error("A current update is in progress")
updater = self.updaters.get(app, None)
if updater is None:
raise self.server.error(f"Updater {app} not available")
self.current_update = (app, id(web_request))
try:
await updater.update(inc_deps)
except Exception:
self.current_update = None
raise
self.current_update = None
return "ok"
async def _handle_status_request(self, web_request):
if web_request.get_boolean('refresh', False):
await self._check_versions()
vinfo = {}
for name, updater in self.updaters.items():
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
return {
'version_info': vinfo,
'busy': self.current_update is not None}
async def execute_cmd(self, cmd, timeout=10., notify=False):
shell_command = self.server.lookup_plugin('shell_command')
cb = self.notify_update_response if notify else None
scmd = shell_command.build_shell_command(cmd, callback=cb)
await scmd.run(timeout=timeout, verbose=notify)
async def execute_cmd_with_response(self, cmd, timeout=10.):
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
return await scmd.run_with_response(timeout)
async def github_request(self, url, is_download=False):
cto = rto = 5.
content_type = "application/vnd.github.v3+json"
if is_download:
content_type = "application/zip"
rto = 120.
timeout = cto + rto + 2.
request = HTTPRequest(url, headers={"Accept": content_type},
connect_timeout=cto, request_timeout=rto)
retries = 5
while True:
to = IOLoop.current().time() + timeout
try:
fut = self.http_client.fetch(request)
resp = await tornado.gen.with_timeout(to, fut)
except Exception as e:
retries -= 1
if not retries:
raise
logging.info(f"Github request error, retrying: {e}")
continue
if is_download:
return resp.body
decoded = json.loads(resp.body)
return decoded
def notify_update_response(self, resp):
resp = resp.strip()
if isinstance(resp, bytes):
resp = resp.decode()
notification = {
'message': resp,
'application': None,
'proc_id': None}
if self.current_update is not None:
notification['application'] = self.current_update[0]
notification['proc_id'] = self.current_update[1]
self.server.send_event(
"update_manager:update_response", notification)
def close(self):
self.http_client.close()
class GitUpdater:
def __init__(self, umgr, name, path, ver, env):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
self.notify_update_response = umgr.notify_update_response
self.github_request = umgr.github_request
self.name = name
self.repo_path = path
self.env = env
self.version = self.cur_hash = self.remote_hash = "?"
self.is_valid = False
self.is_dirty = ver.endswith("dirty")
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
self.version = tag_version
IOLoop.current().spawn_callback(self._init_repo)
def _get_version_info(self):
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
vinfo = {}
if os.path.isfile(ver_path):
data = ""
with open(ver_path, 'r') as f:
data = f.read()
try:
entries = [e.strip() for e in data.split('\n') if e.strip()]
vinfo = dict([i.split('=') for i in entries])
vinfo = {k: tuple(re.findall(r"\d+", v)) for k, v in
vinfo.items()}
except Exception:
pass
else:
self._log_info(f"Version Info Found: {vinfo}")
vinfo['version'] = tuple(re.findall(r"\d+", self.version))
return vinfo
def _log_exc(self, msg, traceback=True):
log_msg = f"Repo {self.name}: {msg}"
if traceback:
logging.exception(log_msg)
else:
logging.info(log_msg)
return self.server.error(msg)
def _log_info(self, msg):
log_msg = f"Repo {self.name}: {msg}"
logging.info(log_msg)
def _notify_status(self, msg):
log_msg = f"Repo {self.name}: {msg}"
logging.debug(log_msg)
self.notify_update_response(log_msg)
async def _init_repo(self):
self.is_valid = False
self.cur_hash = "?"
try:
branch = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse --abbrev-ref HEAD")
origin = await self.execute_cmd_with_response(
f"git -C {self.repo_path} remote get-url origin")
hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse HEAD")
except Exception:
self._log_exc("Error retreiving git info")
return
if not branch.startswith("fatal:"):
self.cur_hash = hash
if branch == "master":
if origin == REPO_DATA[self.name]['origin']:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
self._log_info(f"Invalid git origin '{origin}''")
else:
self._log_info("Git repo not on master branch")
else:
self._log_info(f"Invalid git repo at path '{self.repo_path}''")
try:
await self.check_remote_version()
except Exception:
pass
async def check_remote_version(self):
repo_url = REPO_DATA[self.name]['repo_url']
try:
branch_info = await self.github_request(repo_url)
except Exception:
raise self._log_exc(f"Error retreiving github info")
commit_hash = branch_info.get('commit', {}).get('sha', None)
if commit_hash is None:
self.is_valid = False
self.upstream_version = "?"
raise self._log_exc(f"Invalid github response", False)
self._log_info(f"Received latest commit hash: {commit_hash}")
self.remote_hash = commit_hash
async def update(self, update_deps=False):
if not self.is_valid:
raise self._log_exc("Update aborted, repo is not valid", False)
if self.is_dirty:
raise self._log_exc(
"Update aborted, repo is has been modified", False)
if self.remote_hash == "?":
await self.check_remote_version()
if self.remote_hash == self.cur_hash:
# No need to update
return
self._notify_status("Updating Repo...")
try:
await self.execute_cmd(f"git -C {self.repo_path} pull -q")
except Exception:
raise self._log_exc("Error running 'git pull'")
# Check Semantic Versions
vinfo = self._get_version_info()
cur_version = vinfo.get('version', ())
update_deps |= cur_version < vinfo.get('deps_version', ())
need_env_rebuild = cur_version < vinfo.get('env_version', ())
if update_deps:
await self._install_packages()
await self._update_virtualenv(need_env_rebuild)
if self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
IOLoop.current().spawn_callback(self.restart_service)
else:
await self.restart_service()
async def _install_packages(self):
# Open install file file and read
inst_script = REPO_DATA[self.name]['install_script']
inst_path = os.path.join(self.repo_path, inst_script)
if not os.path.isfile(inst_path):
self._log_info(f"Unable to open install script: {inst_path}")
return
with open(inst_path, 'r') as f:
data = f.read()
packages = re.findall(r'PKGLIST="(.*)"', data)
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
if not packages:
self._log_info(f"No packages found in script: {inst_path}")
return
# TODO: Log and notify that packages will be installed
pkgs = " ".join(packages)
logging.debug(f"Repo {self.name}: Detected Packages: {pkgs}")
self._notify_status("Installing system dependencies...")
# Install packages with apt-get
try:
await self.execute_cmd(
f"{APT_CMD} update", timeout=300., notify=True)
await self.execute_cmd(
f"{APT_CMD} install --yes {pkgs}", timeout=3600.,
notify=True)
except Exception:
self._log_exc("Error updating packages via apt-get")
return
async def _update_virtualenv(self, rebuild_env=False):
# Update python dependencies
bin_dir = os.path.dirname(self.env)
if rebuild_env:
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
env_args = REPO_DATA[self.name]['venv_args']
self._notify_status(f"Creating virtualenv at: {env_path}...")
if os.path.exists(env_path):
shutil.rmtree(env_path)
try:
await self.execute_cmd(
f"virtualenv {env_args} {env_path}")
except Exception:
self._log_exc(f"Error creating virtualenv")
return
if not os.path.expanduser(self.env):
raise self._log_exc("Failed to create new virtualenv", False)
reqs = os.path.join(
self.repo_path, REPO_DATA[self.name]['requirements'])
if not os.path.isfile(reqs):
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
return
pip = os.path.join(bin_dir, "pip")
self._notify_status("Updating python packages...")
try:
await self.execute_cmd(
f"{pip} install -r {reqs}", timeout=1200., notify=True)
except Exception:
self._log_exc("Error updating python requirements")
async def restart_service(self):
self._notify_status("Restarting Service...")
try:
await self.execute_cmd(f"sudo systemctl restart {self.name}")
except Exception:
raise self._log_exc("Error restarting service")
def get_update_status(self):
return {
'version': self.version,
'current_hash': self.cur_hash,
'remote_hash': self.remote_hash,
'is_dirty': self.is_dirty,
'is_valid': self.is_valid}
class PackageUpdater:
def __init__(self, umgr):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.notify_update_response = umgr.notify_update_response
async def check_remote_version(self):
pass
async def update(self, *args):
self.notify_update_response("Updating packages...")
try:
await self.execute_cmd(
f"{APT_CMD} update", timeout=300., notify=True)
await self.execute_cmd(
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
except Exception:
raise self.server.error("Error updating system packages")
class ClientUpdater:
def __init__(self, umgr, repo, path):
self.server = umgr.server
self.github_request = umgr.github_request
self.notify_update_response = umgr.notify_update_response
self.repo = repo.strip().strip("/")
self.name = self.repo.split("/")[-1]
self.path = path
self.version = self.remote_version = self.dl_url = "?"
version_path = os.path.join(self.path, ".version")
if os.path.isfile(os.path.join(self.path, ".version")):
with open(version_path, "r") as f:
v = f.read()
self.version = v.strip()
logging.info(f"\nInitializing repo '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.check_remote_version)
async def check_remote_version(self):
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
result = await self.github_request(url)
except Exception:
logging.exception(f"Client {self.repo}: Github Request Error")
result = {}
self.remote_version = result.get('name', "?")
release_assets = result.get('assets', [{}])[0]
self.dl_url = release_assets.get('browser_download_url', "?")
logging.info(
f"Github client Info Received: {self.name}, "
f"version: {self.remote_version} "
f"url: {self.dl_url}")
async def update(self, *args):
if self.remote_version == "?":
await self.check_remote_version()
if self.remote_version == "?":
raise self.server.error(
f"Client {self.repo}: Unable to locate update")
if self.dl_url == "?":
raise self.server.error(
f"Client {self.repo}: Invalid download url")
if self.version == self.remote_version:
# Already up to date
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.github_request(self.dl_url, is_download=True)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
self.version = self.remote_version
version_path = os.path.join(self.path, ".version")
if not os.path.exists(version_path):
with open(version_path, "w") as f:
f.write(self.version)
self.notify_update_response(f"Client Updated: {self.name}")
def get_update_status(self):
return {
'name': self.name,
'version': self.version,
'remote_version': self.remote_version
}
def load_plugin(config):
return UpdateManager(config)
+4 -4
View File
@@ -28,10 +28,10 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
self.handleError(record)
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, filename, **kwargs):
def __init__(self, software_version, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.header = "Moonraker Log Start...\n"
self.header += "Git Version: " + get_software_version() + "\n"
self.header += f"Git Version: {software_version}\n"
self.header += "="*80 + "\n"
if self.stream is not None:
self.stream.write(self.header)
@@ -67,14 +67,14 @@ def get_software_version():
return "?"
def setup_logging(log_file):
def setup_logging(log_file, software_version):
root_logger = logging.getLogger()
queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
file_hdlr = MoonrakerLoggingHandler(
log_file, when='midnight', backupCount=2)
software_version, log_file, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
+137 -44
View File
@@ -14,6 +14,65 @@ from utils import ServerError
class Sentinel:
pass
class WebRequest:
def __init__(self, endpoint, args, action="", conn=None):
self.endpoint = endpoint
self.action = action
self.args = args
self.conn = conn
def get_endpoint(self):
return self.endpoint
def get_action(self):
return self.action
def get_args(self):
return self.args
def get_connection(self):
return self.conn
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
if key not in self.args:
if default == Sentinel:
raise ServerError(f"No data for argument: {key}")
return default
val = self.args[key]
try:
if dtype != bool:
return dtype(val)
else:
if isinstance(val, str):
val = val.lower()
if val in ["true", "false"]:
return True if val == "true" else False
elif isinstance(val, bool):
return val
raise TypeError
except Exception:
raise ServerError(
f"Unable to convert argument [{key}] to {dtype}: "
f"value recieved: {val}")
def get(self, key, default=Sentinel):
val = self.args.get(key, default)
if val == Sentinel:
raise ServerError(f"No data for argument: {key}")
return val
def get_str(self, key, default=Sentinel):
return self._get_converted_arg(key, default)
def get_int(self, key, default=Sentinel):
return self._get_converted_arg(key, default, int)
def get_float(self, key, default=Sentinel):
return self._get_converted_arg(key, default, float)
def get_boolean(self, key, default=Sentinel):
return self._get_converted_arg(key, default, bool)
class JsonRPC:
def __init__(self):
self.methods = {}
@@ -24,7 +83,7 @@ class JsonRPC:
def remove_method(self, name):
self.methods.pop(name, None)
async def dispatch(self, data):
async def dispatch(self, data, ws):
response = None
try:
request = json.loads(data)
@@ -37,19 +96,19 @@ class JsonRPC:
if isinstance(request, list):
response = []
for req in request:
resp = await self.process_request(req)
resp = await self.process_request(req, ws)
if resp is not None:
response.append(resp)
if not response:
response = None
else:
response = await self.process_request(request)
response = await self.process_request(request, ws)
if response is not None:
response = json.dumps(response)
logging.debug("Websocket Response::" + response)
return response
async def process_request(self, request):
async def process_request(self, request, ws):
req_id = request.get('id', None)
rpc_version = request.get('jsonrpc', "")
method_name = request.get('method', None)
@@ -61,20 +120,22 @@ class JsonRPC:
if 'params' in request:
params = request['params']
if isinstance(params, list):
response = await self.execute_method(method, req_id, *params)
response = await self.execute_method(
method, req_id, ws, *params)
elif isinstance(params, dict):
response = await self.execute_method(method, req_id, **params)
response = await self.execute_method(
method, req_id, ws, **params)
else:
return self.build_error(-32600, "Invalid Request", req_id)
else:
response = await self.execute_method(method, req_id)
response = await self.execute_method(method, req_id, ws)
return response
async def execute_method(self, method, req_id, *args, **kwargs):
async def execute_method(self, method, req_id, ws, *args, **kwargs):
try:
result = await method(*args, **kwargs)
result = await method(ws, *args, **kwargs)
except TypeError as e:
return self.build_error(-32603, "Invalid params", req_id)
return self.build_error(-32603, f"Invalid params:\n{e}", req_id)
except ServerError as e:
return self.build_error(e.status_code, str(e), req_id)
except Exception as e:
@@ -106,17 +167,26 @@ class WebsocketManager:
self.ws_lock = tornado.locks.Lock()
self.rpc = JsonRPC()
self.rpc.register_method("server.websocket.id", self._handle_id_request)
# Register events
self.server.register_event_handler(
"server:klippy_ready", self._handle_klippy_ready)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_klippy_disconnect)
self.server.register_event_handler(
"server:gcode_response", self._handle_gcode_response)
self.server.register_event_handler(
"server:status_update", self._handle_status_update)
self.server.register_event_handler(
"file_manager:filelist_changed", self._handle_filelist_changed)
self.server.register_event_handler(
"file_manager:metadata_update", self._handle_metadata_update)
self.server.register_event_handler(
"gpio_power:power_changed", self._handle_power_changed)
self.server.register_event_handler(
"update_manager:update_response", self._handle_update_response)
async def _handle_klippy_ready(self):
await self.notify_websockets("klippy_ready")
async def _handle_klippy_disconnect(self):
await self.notify_websockets("klippy_disconnected")
@@ -124,46 +194,56 @@ class WebsocketManager:
async def _handle_gcode_response(self, response):
await self.notify_websockets("gcode_response", response)
async def _handle_status_update(self, status):
await self.notify_websockets("status_update", status)
async def _handle_filelist_changed(self, flist):
await self.notify_websockets("filelist_changed", flist)
async def _handle_metadata_update(self, metadata):
await self.notify_websockets("metadata_update", metadata)
def register_handler(self, api_def, callback=None):
for r_method in api_def.request_methods:
cmd = r_method.lower() + '_' + api_def.ws_method
if callback is not None:
# Callback is a local method
rpc_cb = self._generate_local_callback(
api_def.endpoint, r_method, callback)
else:
# Callback is a remote method
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(cmd, rpc_cb)
async def _handle_power_changed(self, pstatus):
await self.notify_websockets("power_changed", pstatus)
async def _handle_update_response(self, response):
await self.notify_websockets("update_response", response)
def register_local_handler(self, api_def, callback):
for ws_method, req_method in \
zip(api_def.ws_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, callback)
self.rpc.register_method(ws_method, rpc_cb)
def register_remote_handler(self, api_def):
ws_method = api_def.ws_methods[0]
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(ws_method, rpc_cb)
def remove_handler(self, ws_method):
for prefix in ["get", "post", "delete"]:
self.rpc.remove_method(prefix + "_" + ws_method)
self.rpc.remove_method(ws_method)
def _generate_callback(self, endpoint):
async def func(**kwargs):
result = await self.server.make_request(endpoint, kwargs)
async def func(ws, **kwargs):
result = await self.server.make_request(
WebRequest(endpoint, kwargs, conn=ws))
return result
return func
def _generate_local_callback(self, endpoint, request_method, callback):
async def func(**kwargs):
result = await callback(endpoint, request_method, kwargs)
async def func(ws, **kwargs):
result = await callback(
WebRequest(endpoint, kwargs, request_method, ws))
return result
return func
async def _handle_id_request(self, ws, **kwargs):
return {'websocket_id': ws.uid}
def has_websocket(self, ws_id):
return ws_id in self.websockets
def get_websocket(self, ws_id):
return self.websockets.get(ws_id, None)
async def add_websocket(self, ws):
async with self.ws_lock:
self.websockets[ws.uid] = ws
@@ -173,17 +253,17 @@ class WebsocketManager:
async with self.ws_lock:
old_ws = self.websockets.pop(ws.uid, None)
if old_ws is not None:
self.server.remove_subscription(old_ws)
logging.info(f"Websocket Removed: {ws.uid}")
async def notify_websockets(self, name, data=Sentinel):
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
if data != Sentinel:
msg['params'] = [data]
notification = json.dumps(msg)
async with self.ws_lock:
for ws in list(self.websockets.values()):
try:
ws.write_message(notification)
ws.write_message(msg)
except WebSocketClosedError:
self.websockets.pop(ws.uid, None)
logging.info(f"Websocket Removed: {ws.uid}")
@@ -198,9 +278,10 @@ class WebsocketManager:
self.websockets = {}
class WebSocket(WebSocketHandler):
def initialize(self, wsm, auth):
self.wsm = wsm
self.auth = auth
def initialize(self):
app = self.settings['parent']
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
@@ -213,23 +294,35 @@ class WebSocket(WebSocketHandler):
async def _process_message(self, message):
try:
response = await self.rpc.dispatch(message)
response = await self.rpc.dispatch(message, self)
if response is not None:
self.write_message(response)
except Exception:
logging.exception("Websocket Command Error")
def send_status(self, status):
if not status:
return
try:
self.write_message({
'jsonrpc': "2.0",
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.websockets.pop(self.uid, None)
logging.info(f"Websocket Removed: {self.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
def on_close(self):
io_loop = IOLoop.current()
io_loop.spawn_callback(self.wsm.remove_websocket, self)
def check_origin(self, origin):
if self.settings['enable_cors']:
# allow CORS
return True
else:
return super(WebSocket, self).check_origin(origin)
if not super(WebSocket, self).check_origin(origin):
return self.auth.check_cors(origin)
return True
# Check Authorized User
def prepare(self):
if not self.auth.check_authorized(self.request):
+346 -103
View File
@@ -9,8 +9,10 @@ import argparse
import re
import os
import sys
import time
import base64
import traceback
import io
from PIL import Image
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
@@ -38,69 +40,150 @@ def _regex_find_ints(pattern, data):
pass
return []
def _regex_find_first(pattern, data, cast=float):
match = re.search(pattern, data)
val = None
if match:
try:
val = cast(match.group(1))
except Exception:
return None
return val
# Slicer parsing implementations
class BaseSlicer(object):
def __init__(self, name, id_pattern):
self.name = name
self.id_pattern = id_pattern
def __init__(self, file_path):
self.path = file_path
self.header_data = self.footer_data = self.log = None
def set_data(self, header_data, footer_data, log):
def set_data(self, header_data, footer_data, fsize, log):
self.header_data = header_data
self.footer_data = footer_data
self.size = fsize
self.log = log
def get_name(self):
return self.name
def get_id_pattern(self):
return self.id_pattern
def _parse_min_float(self, pattern, data):
result = _regex_find_floats(pattern, data)
def _parse_min_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
if result:
return min(result)
else:
return None
def _parse_max_float(self, pattern, data):
result = _regex_find_floats(pattern, data)
def _parse_max_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
if result:
return max(result)
else:
return None
class PrusaSlicer(BaseSlicer):
def __init__(self, name="PrusaSlicer", id_pattern=r"PrusaSlicer\s.*\son"):
super(PrusaSlicer, self).__init__(name, id_pattern)
def check_identity(self, data):
return None
def parse_gcode_start_byte(self):
m = re.search(r"\n[MG]\d+\s.*\n", self.header_data)
if m is None:
return None
return m.start()
def parse_gcode_end_byte(self):
rev_data = self.footer_data[::-1]
m = re.search(r"\n.*\s\d+[MG]\n", rev_data)
if m is None:
return None
return self.size - m.start()
def parse_first_layer_height(self):
return self._parse_min_float(
r"; first_layer_height =.*", self.footer_data)
return None
def parse_layer_height(self):
return self._parse_min_float(r"; layer_height =.*", self.footer_data)
return None
def parse_object_height(self):
return None
def parse_filament_total(self):
return None
def parse_estimated_time(self):
return None
def parse_first_layer_bed_temp(self):
return None
def parse_first_layer_extr_temp(self):
return None
def parse_thumbnails(self):
return None
class UnknownSlicer(BaseSlicer):
def check_identity(self, data):
return {'slicer': "Unknown"}
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class PrusaSlicer(BaseSlicer):
def check_identity(self, data):
match = re.search(r"PrusaSlicer\s(.*)\son", data)
if match:
return {
'slicer': "PrusaSlicer",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self):
return _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
def parse_object_height(self):
matches = re.findall(
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
if matches:
try:
matches = [float(m) for m in matches]
except Exception:
pass
else:
return max(matches)
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
def parse_filament_total(self):
return self._parse_max_float(
r"filament\sused\s\[mm\]\s=\s\d+\.\d*", self.footer_data)
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
time_match = re.search(
r';\sestimated\sprinting\stime.*', self.footer_data)
if not time_matches:
if not time_match:
return None
total_time = 0
time_match = time_matches[0]
time_patterns = [(r"\d+d", 24*60*60), (r"\d+h", 60*60),
(r"\d+m", 60), (r"\d+s", 1)]
for pattern, multiplier in time_patterns:
t = _regex_find_ints(pattern, time_match)
if t:
total_time += max(t) * multiplier
time_match = time_match.group()
time_patterns = [(r"(\d+)d", 24*60*60), (r"(\d+)h", 60*60),
(r"(\d+)m", 60), (r"(\d+)s", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self):
@@ -126,48 +209,79 @@ class PrusaSlicer(BaseSlicer):
parsed_matches.append({
'width': info[0], 'height': info[1],
'size': info[2], 'data': data})
return parsed_matches
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
class Slic3rPE(PrusaSlicer):
def __init__(self, name="Slic3r PE",
id_pattern=r"Slic3r\sPrusa\sEdition\s.*\son"):
super(Slic3rPE, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
if match:
return {
'slicer': "Slic3r PE",
'slicer_version': match.group(1)
}
return None
def parse_filament_total(self):
return self._parse_max_float(
r"filament\sused\s=\s\d+\.\d+mm", self.footer_data)
return _regex_find_first(
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
def parse_thumbnails(self):
return None
class Slic3r(Slic3rPE):
def __init__(self, name="Slic3r", id_pattern=r"Slic3r\s\d.*\son"):
super(Slic3r, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"Slic3r\s(\d.*)\son", data)
if match:
return {
'slicer': "Slic3r",
'slicer_version': match.group(1)
}
return None
def parse_estimated_time(self):
return None
class SuperSlicer(PrusaSlicer):
def __init__(self, name="SuperSlicer", id_pattern=r"SuperSlicer\s.*\son"):
super(SuperSlicer, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"SuperSlicer\s(.*)\son", data)
if match:
return {
'slicer': "SuperSlicer",
'slicer_version': match.group(1)
}
return None
class Cura(BaseSlicer):
def __init__(self, name="Cura", id_pattern=r"Cura_SteamEngine.*"):
super(Cura, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"Cura_SteamEngine\s(.*)", data)
if match:
return {
'slicer': "Cura",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
return self._parse_min_float(r";MINZ:.*", self.header_data)
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(r";Layer\sheight:.*", self.header_data)
return _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r";MAXZ:.*", self.header_data)
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
def parse_filament_total(self):
filament = self._parse_max_float(
r";Filament\sused:.*", self.header_data)
filament = _regex_find_first(
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
if filament is not None:
filament *= 1000
return filament
@@ -175,55 +289,132 @@ class Cura(BaseSlicer):
def parse_estimated_time(self):
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self):
return None
thumbName = os.path.splitext(
os.path.basename(self.path))[0] + ".png"
thumbPath = os.path.join(
os.path.dirname(self.path), "thumbs", thumbName)
if not os.path.isfile(thumbPath):
return None
# read file
thumbs = []
try:
with open(thumbPath, 'rb') as thumbFile:
fbytes = thumbFile.read()
with Image.open(io.BytesIO(fbytes)) as im:
thumbFull = base64.b64encode(fbytes).decode()
thumbs.append({
'width': im.width, 'height': im.height,
'size': len(thumbFull), 'data': thumbFull
})
# Create 32x32 thumbnail
im.thumbnail((32, 32), Image.ANTIALIAS)
tmpThumb = io.BytesIO()
im.save(tmpThumb, format="PNG")
thumbSmall = base64.b64encode(
tmpThumb.getbuffer()).decode()
tmpThumb.close()
thumbs.insert(0, {
'width': im.width, 'height': im.height,
'size': len(thumbSmall), 'data': thumbSmall
})
except Exception as e:
self.log.append(str(e))
return None
return thumbs
class Simplify3D(BaseSlicer):
def __init__(self, name="Simplify3D", id_pattern=r"Simplify3D\(R\)"):
super(Simplify3D, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
if match:
return {
'slicer': "Simplify3D",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(r";\s+layerHeight,.*", self.header_data)
return _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_filament_total(self):
return self._parse_max_float(
r";\s+Filament\slength:.*mm", self.footer_data)
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_estimated_time(self):
time_matches = re.findall(
time_match = re.search(
r';\s+Build time:.*', self.footer_data)
if not time_matches:
if not time_match:
return None
total_time = 0
time_match = time_matches[0]
time_patterns = [(r"\d+\shours", 60*60), (r"\d+\smin", 60),
(r"\d+\ssec", 1)]
for pattern, multiplier in time_patterns:
t = _regex_find_ints(pattern, time_match)
if t:
total_time += max(t) * multiplier
time_match = time_match.group()
time_patterns = [(r"(\d+)\shours", 60*60), (r"(\d+)\smin", 60),
(r"(\d+)\ssec", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self):
def _get_temp_items(self, pattern):
match = re.search(pattern, self.header_data)
if match is None:
return []
return match.group().split(",")[1:]
def _get_first_layer_temp(self, heater):
heaters = self._get_temp_items(r"temperatureName.*")
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
for h, temp in zip(heaters, temps):
if h == heater:
try:
return float(temp)
except Exception:
return None
return None
def parse_first_layer_extr_temp(self):
return self._get_first_layer_temp("Extruder 1")
def parse_first_layer_bed_temp(self):
return self._get_first_layer_temp("Heated Bed")
class KISSlicer(BaseSlicer):
def __init__(self, name="KISSlicer", id_pattern=r";\sKISSlicer"):
super(KISSlicer, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r";\sKISSlicer", data)
if match:
ident = {'slicer': "KISSlicer"}
vmatch = re.search(r";\sversion\s(.*)", data)
if vmatch:
version = vmatch.group(1).replace(" ", "-")
ident['slicer_version'] = version
return ident
return None
def parse_first_layer_height(self):
return self._parse_min_float(
r";\s+first_layer_thickness_mm\s=\s\d.*", self.header_data)
return _regex_find_first(
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return self._parse_min_float(
r";\s+max_layer_thickness_mm\s=\s\d.*", self.header_data)
return _regex_find_first(
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_object_height(self):
return self._parse_max_float(
@@ -237,18 +428,32 @@ class KISSlicer(BaseSlicer):
return None
def parse_estimated_time(self):
time = self._parse_max_float(
r";\sCalculated.*Build\sTime:.*", self.footer_data)
time = _regex_find_first(
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
self.footer_data)
if time is not None:
time *= 60
return round(time, 2)
def parse_thumbnails(self):
return round(time, 2)
return None
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_C = (\d+\.?\d*)", self.header_data)
class IdeaMaker(BaseSlicer):
def __init__(self, name="IdeaMaker", id_pattern=r"\sideaMaker\s.*,",):
super(IdeaMaker, self).__init__(name, id_pattern)
def check_identity(self, data):
match = re.search(r"\sideaMaker\s(.*),", data)
if match:
return {
'slicer': "IdeaMaker",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
layer_info = _regex_find_floats(
@@ -266,7 +471,7 @@ class IdeaMaker(BaseSlicer):
def parse_object_height(self):
bounds = _regex_find_floats(
r";Bounding Box:.*", self.footer_data)
r";Bounding Box:.*", self.header_data)
if len(bounds) >= 6:
return bounds[5]
return None
@@ -279,53 +484,91 @@ class IdeaMaker(BaseSlicer):
return None
def parse_estimated_time(self):
return self._parse_max_float(r";Print\sTime:.*", self.footer_data)
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
def parse_thumbnails(self):
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 T0 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class IceSL(BaseSlicer):
def check_identity(self, data):
match = re.search(r"; <IceSL.*>", data)
if match:
return {'slicer': "IceSL"}
return None
def parse_first_layer_height(self):
return _regex_find_first(
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
self.header_data, float)
def parse_layer_height(self):
return _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
def parse_object_height(self):
return self._parse_max_float(
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker]
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails']
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path, log):
metadata = {}
slicers = [s() for s in SUPPORTED_SLICERS]
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = time.ctime(os.path.getmtime(file_path))
metadata['modified'] = os.path.getmtime(file_path)
with open(file_path, 'r') as f:
# read the default size, which should be enough to
# identify the slicer
header_data = f.read(READ_SIZE)
for s in slicers:
if re.search(s.get_id_pattern(), header_data) is not None:
ident = s.check_identity(header_data)
if ident is not None:
slicer = s
metadata.update(ident)
break
if slicer is not None:
metadata['slicer'] = slicer.get_name()
if size > READ_SIZE * 2:
f.seek(size - READ_SIZE)
footer_data = f.read()
elif size > READ_SIZE:
remaining = size - READ_SIZE
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, log)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
if result is not None:
metadata[key] = result
else:
if slicer is None:
slicer = UnknownSlicer(file_path)
metadata['slicer'] = "Unknown"
if size > READ_SIZE * 2:
f.seek(size - READ_SIZE)
footer_data = f.read()
elif size > READ_SIZE:
remaining = size - READ_SIZE
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, size, log)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
if result is not None:
metadata[key] = result
return metadata
def main(path, filename):
+26 -9
View File
@@ -3,6 +3,9 @@
# Raspbian/Raspberry Pi OS based distributions.
PYTHONDIR="${HOME}/moonraker-env"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
# Step 1: Verify Klipper has been installed
check_klipper()
@@ -19,7 +22,7 @@ check_klipper()
# Step 2: Install packages
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx"
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
# Update system package info
report_status "Running apt-get update..."
@@ -33,10 +36,15 @@ install_packages()
# Step 3: Create python virtual environment
create_virtualenv()
{
report_status "Updating python virtual environment..."
report_status "Installing python virtual environment..."
# Create virtualenv if it doesn't already exist
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 ${PYTHONDIR}
# If venv exists and user prompts a rebuild, then do so
if [ -d ${PYTHONDIR} ] && [ $REBUILD_ENV = "y" ]; then
report_status "Removing old virtualenv"
rm -rf ${PYTHONDIR}
fi
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
# Install/update dependencies
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
@@ -54,7 +62,7 @@ install_script()
install_config()
{
DEFAULTS_FILE=/etc/default/moonraker
[ -f $DEFAULTS_FILE ] && return
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start configuration..."
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
@@ -64,18 +72,18 @@ MOONRAKER_USER=$USER
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py"
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
EOF
}
# Step 4: Start server
# Step 6: Start server
start_software()
{
report_status "Launching Moonraker API Server..."
sudo /etc/init.d/klipper stop
sudo systemctl stop klipper
sudo /etc/init.d/moonraker restart
sudo /etc/init.d/klipper start
sudo systemctl start klipper
}
# Helper functions
@@ -98,6 +106,15 @@ set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
# Parse command line arguments
while getopts "rfc:" arg; do
case $arg in
r) REBUILD_ENV="y";;
f) FORCE_DEFAULTS="y";;
c) CONFIG_PATH=$OPTARG;;
esac
done
# Run installation steps defined above
verify_ready
check_klipper
+2 -1
View File
@@ -1,3 +1,4 @@
# Python dependencies for Moonraker
tornado==6.0.4
tornado==6.1.0
pyserial==3.4
pillow==8.0.1
+2
View File
@@ -0,0 +1,2 @@
env_version=0.2.0
deps_version=0.2.0
+8647
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
/*! jsTree - v3.3.10 - 2020-06-16 - (MIT) */
!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):"undefined"!=typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a,b){"use strict";if(!a.jstree){var c=0,d=!1,e=!1,f=!1,g=[],h=a("script:last").attr("src"),i=window.document,j=window.setImmediate,k=window.Promise;!j&&k&&(j=function(a,b){k.resolve(b).then(a)}),a.jstree={version:"3.3.10",defaults:{plugins:[]},plugins:{},path:h&&-1!==h.indexOf("/")?h.replace(/\/[^\/]+$/,""):"",idregex:/[\\:&!^|()\[\]<>@*'+~#";.,=\- \/${}%?`]/g,root:"#"},a.jstree.create=function(b,d){var e=new a.jstree.core(++c),f=d;return d=a.extend(!0,{},a.jstree.defaults,d),f&&f.plugins&&(d.plugins=f.plugins),a.each(d.plugins,function(a,b){"core"!==a&&(e=e.plugin(b,d[b]))}),a(b).data("jstree",e),e.init(b,d),e},a.jstree.destroy=function(){a(".jstree:jstree").jstree("destroy"),a(i).off(".jstree")},a.jstree.core=function(a){this._id=a,this._cnt=0,this._wrk=null,this._data={core:{themes:{name:!1,dots:!1,icons:!1,ellipsis:!1},selected:[],last_error:{},working:!1,worker_queue:[],focused:null}}},a.jstree.reference=function(b){var c=null,d=null;if(!b||!b.id||b.tagName&&b.nodeType||(b=b.id),!d||!d.length)try{d=a(b)}catch(e){}if(!d||!d.length)try{d=a("#"+b.replace(a.jstree.idregex,"\\$&"))}catch(e){}return d&&d.length&&(d=d.closest(".jstree")).length&&(d=d.data("jstree"))?c=d:a(".jstree").each(function(){var d=a(this).data("jstree");return d&&d._model.data[b]?(c=d,!1):void 0}),c},a.fn.jstree=function(c){var d="string"==typeof c,e=Array.prototype.slice.call(arguments,1),f=null;return c!==!0||this.length?(this.each(function(){var g=a.jstree.reference(this),h=d&&g?g[c]:null;return f=d&&h?h.apply(g,e):null,g||d||c!==b&&!a.isPlainObject(c)||a.jstree.create(this,c),(g&&!d||c===!0)&&(f=g||!1),null!==f&&f!==b?!1:void 0}),null!==f&&f!==b?f:this):!1},a.expr.pseudos.jstree=a.expr.createPseudo(function(c){return function(c){return a(c).hasClass("jstree")&&a(c).data("jstree")!==b}}),a.jstree.defaults.core={data:!1,strings:!1,check_callback:!1,error:a.noop,animation:200,multiple:!0,themes:{name:!1,url:!1,dir:!1,dots:!0,icons:!0,ellipsis:!1,stripes:!1,variant:!1,responsive:!1},expand_selected_onload:!0,worker:!0,force_text:!1,dblclick_toggle:!0,loaded_state:!1,restore_focus:!0,keyboard:{"ctrl-space":function(b){b.type="click",a(b.currentTarget).trigger(b)},enter:function(b){b.type="click",a(b.currentTarget).trigger(b)},left:function(b){if(b.preventDefault(),this.is_open(b.currentTarget))this.close_node(b.currentTarget);else{var c=this.get_parent(b.currentTarget);c&&c.id!==a.jstree.root&&this.get_node(c,!0).children(".jstree-anchor").focus()}},up:function(a){a.preventDefault();var b=this.get_prev_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},right:function(b){if(b.preventDefault(),this.is_closed(b.currentTarget))this.open_node(b.currentTarget,function(a){this.get_node(a,!0).children(".jstree-anchor").focus()});else if(this.is_open(b.currentTarget)){var c=this.get_node(b.currentTarget,!0).children(".jstree-children")[0];c&&a(this._firstChild(c)).children(".jstree-anchor").focus()}},down:function(a){a.preventDefault();var b=this.get_next_dom(a.currentTarget);b&&b.length&&b.children(".jstree-anchor").focus()},"*":function(a){this.open_all()},home:function(b){b.preventDefault();var c=this._firstChild(this.get_container_ul()[0]);c&&a(c).children(".jstree-anchor").filter(":visible").focus()},end:function(a){a.preventDefault(),this.element.find(".jstree-anchor").filter(":visible").last().focus()},f2:function(a){a.preventDefault(),this.edit(a.currentTarget)}}},a.jstree.core.prototype={plugin:function(b,c){var d=a.jstree.plugins[b];return d?(this._data[b]={},d.prototype=this,new d(c,this)):this},init:function(b,c){this._model={data:{},changed:[],force_full_redraw:!1,redraw_timeout:!1,default_state:{loaded:!0,opened:!1,selected:!1,disabled:!1}},this._model.data[a.jstree.root]={id:a.jstree.root,parent:null,parents:[],children:[],children_d:[],state:{loaded:!1}},this.element=a(b).addClass("jstree jstree-"+this._id),this.settings=c,this._data.core.ready=!1,this._data.core.loaded=!1,this._data.core.rtl="rtl"===this.element.css("direction"),this.element[this._data.core.rtl?"addClass":"removeClass"]("jstree-rtl"),this.element.attr("role","tree"),this.settings.core.multiple&&this.element.attr("aria-multiselectable",!0),this.element.attr("tabindex")||this.element.attr("tabindex","0"),this.bind(),this.trigger("init"),this._data.core.original_container_html=this.element.find(" > ul > li").clone(!0),this._data.core.original_container_html.find("li").addBack().contents().filter(function(){return 3===this.nodeType&&(!this.nodeValue||/^\s+$/.test(this.nodeValue))}).remove(),this.element.html("<ul class='jstree-container-ul jstree-children' role='group'><li id='j"+this._id+"_loading' class='jstree-initial-node jstree-loading jstree-leaf jstree-last' role='presentation'><i class='jstree-icon jstree-ocl'></i><a class='jstree-anchor' role='treeitem' hLine truncated
if(a&&"object"==typeof a.state)for(f in a.state)a.state.hasOwnProperty(f)&&(l.state[f]=a.state[f]);if(a&&"object"==typeof a.li_attr)for(f in a.li_attr)a.li_attr.hasOwnProperty(f)&&(l.li_attr[f]=a.li_attr[f]);if(l.li_attr.id&&!l.id&&(l.id=l.li_attr.id.toString()),l.id||(l.id=e),l.li_attr.id||(l.li_attr.id=l.id),a&&"object"==typeof a.a_attr)for(f in a.a_attr)a.a_attr.hasOwnProperty(f)&&(l.a_attr[f]=a.a_attr[f]);if(a&&a.children&&a.children.length){for(f=0,g=a.children.length;g>f;f++)h=this._parse_model_from_json(a.children[f],l.id,d),i=j[h],l.children.push(h),i.children_d.length&&(l.children_d=l.children_d.concat(i.children_d));l.children_d=l.children.concat(l.children_d)}return a&&a.children&&a.children===!0&&(l.state.loaded=!1,l.children=[],l.children_d=[]),delete a.data,delete a.children,l.original=a,j[l.id]=l,l.state.selected&&this._data.core.selected.push(l.id),l.id},_redraw:function(){var b=this._model.force_full_redraw?this._model.data[a.jstree.root].children.concat([]):this._model.changed.concat([]),c=i.createElement("UL"),d,e,f,g=this._data.core.focused;for(e=0,f=b.length;f>e;e++)d=this.redraw_node(b[e],!0,this._model.force_full_redraw),d&&this._model.force_full_redraw&&c.appendChild(d);this._model.force_full_redraw&&(c.className=this.get_container_ul()[0].className,c.setAttribute("role","group"),this.element.empty().append(c)),null!==g&&this.settings.core.restore_focus&&(d=this.get_node(g,!0),d&&d.length&&d.children(".jstree-anchor")[0]!==i.activeElement?d.children(".jstree-anchor").focus():this._data.core.focused=null),this._model.force_full_redraw=!1,this._model.changed=[],this.trigger("redraw",{nodes:b})},redraw:function(a){a&&(this._model.force_full_redraw=!0),this._redraw()},draw_children:function(b){var c=this.get_node(b),d=!1,e=!1,f=!1,g=i;if(!c)return!1;if(c.id===a.jstree.root)return this.redraw(!0);if(b=this.get_node(b,!0),!b||!b.length)return!1;if(b.children(".jstree-children").remove(),b=b[0],c.children.length&&c.state.loaded){for(f=g.createElement("UL"),f.setAttribute("role","group"),f.className="jstree-children",d=0,e=c.children.length;e>d;d++)f.appendChild(this.redraw_node(c.children[d],!0,!0));b.appendChild(f)}},redraw_node:function(b,c,d,e){var f=this.get_node(b),g=!1,h=!1,j=!1,k=!1,l=!1,m=!1,n="",o=i,p=this._model.data,q=!1,r=!1,s=null,t=0,u=0,v=!1,w=!1;if(!f)return!1;if(f.id===a.jstree.root)return this.redraw(!0);if(c=c||0===f.children.length,b=i.querySelector?this.element[0].querySelector("#"+(-1!=="0123456789".indexOf(f.id[0])?"\\3"+f.id[0]+" "+f.id.substr(1).replace(a.jstree.idregex,"\\$&"):f.id.replace(a.jstree.idregex,"\\$&"))):i.getElementById(f.id))b=a(b),d||(g=b.parent().parent()[0],g===this.element[0]&&(g=null),h=b.index()),c||!f.children.length||b.children(".jstree-children").length||(c=!0),c||(j=b.children(".jstree-children")[0]),q=b.children(".jstree-anchor")[0]===i.activeElement,b.remove();else if(c=!0,!d){if(g=f.parent!==a.jstree.root?a("#"+f.parent.replace(a.jstree.idregex,"\\$&"),this.element)[0]:null,!(null===g||g&&p[f.parent].state.opened))return!1;h=a.inArray(f.id,null===g?p[a.jstree.root].children:p[f.parent].children)}b=this._data.core.node.cloneNode(!0),n="jstree-node ";for(k in f.li_attr)if(f.li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"!==k?b.setAttribute(k,f.li_attr[k]):n+=f.li_attr[k]}for(f.a_attr.id||(f.a_attr.id=f.id+"_anchor"),b.setAttribute("aria-selected",!!f.state.selected),b.childNodes[1].setAttribute("aria-selected",!!f.state.selected),b.setAttribute("aria-level",f.parents.length),b.childNodes[1].setAttribute("aria-level",f.parents.length),b.setAttribute("aria-labelledby",f.a_attr.id),f.state.disabled&&(b.setAttribute("aria-disabled",!0),b.childNodes[1].setAttribute("aria-disabled",!0)),k=0,l=f.children.length;l>k;k++)if(!p[f.children[k]].state.hidden){v=!0;break}if(null!==f.parent&&p[f.parent]&&!f.state.hidden&&(k=a.inArray(f.id,p[f.parent].children),w=f.id,-1!==k))for(k++,l=p[f.parent].children.length;l>k;k++)if(p[p[f.parent].children[k]].state.hidden||(w=p[f.parent].children[k]),w!==f.id)break;f.state.hidden&&(n+=" jstree-hidden"),f.state.loading&&(n+=" jstree-loading"),f.state.loaded&&!v?n+=" jstree-leaf":(n+=f.state.opened&&f.state.loaded?" jstree-open":" jstree-closed",b.setAttribute("aria-expanded",f.state.opened&&f.state.loaded),b.childNodes[1].setAttribute("aria-expanded",f.state.opened&&f.state.loaded)),w===f.id&&(n+=" jstree-last"),b.id=f.id,b.className=n,n=(f.state.selected?" jstree-clicked":"")+(f.state.disabled?" jstree-disabled":"");for(l in f.a_attr)if(f.a_attr.hasOwnProperty(l)){if("href"===l&&"#"===f.a_attr[l])continue;"class"!==l?b.childNodes[1].setAttribute(l,f.a_attr[l]):n+=" "+f.a_attr[l]}if(n.length&&(b.childNodes[1].className="jstree-anchor "+n),(f.icon&&f.icon!==!0||f.icon===!1)&&(f.icon===!1?b.childNodes[1].childNodes[0].className+=" jstree-themeicon-hidden":-1===f.icon.indexOf("/")&&-1===f.icon.indexOf(".")?b.childNodes[1].childNodes[0].className+=" "+f.icon+" jstree-themeicon-custom":(b.childNodes[1].childNodeLine truncated
!p)return!1;for(m=this.get_node(p),c&&c.state&&c.state.loaded===!1&&(m.state.loaded=!1),l=[],l.push(p),l=l.concat(m.children_d),this.trigger("model",{nodes:l,parent:r.id}),n=0,o=r.parents.length;o>n;n++)this._model.data[r.parents[n]].children_d=this._model.data[r.parents[n]].children_d.concat(l);for(l=[],n=0,o=r.children.length;o>n;n++)l[n>=e?n+1:n]=r.children[n];return l[e]=m.id,r.children=l,r.children_d.push(m.id),r.children_d=r.children_d.concat(m.children_d),r.id===a.jstree.root&&(this._model.force_full_redraw=!0),this._model.force_full_redraw||this._node_changed(r.id),h||this.redraw(r.id===a.jstree.root),f&&f.call(this,m,r,e),this.trigger("copy_node",{node:m,original:c,parent:r.id,position:e,old_parent:q,old_position:s&&s._id&&q&&s._model.data[q]&&s._model.data[q].children?a.inArray(c.id,s._model.data[q].children):-1,is_multi:s&&s._id&&s._id!==this._id,is_foreign:!s||!s._id,old_instance:s,new_instance:this}),m.id},cut:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="move_node",void this.trigger("cut",{node:b})):!1},copy:function(b){if(b||(b=this._data.core.selected.concat()),a.isArray(b)||(b=[b]),!b.length)return!1;var c=[],g,h,i;for(h=0,i=b.length;i>h;h++)g=this.get_node(b[h]),g&&g.id&&g.id!==a.jstree.root&&c.push(g);return c.length?(d=c,f=this,e="copy_node",void this.trigger("copy",{node:b})):!1},get_buffer:function(){return{mode:e,node:d,inst:f}},can_paste:function(){return e!==!1&&d!==!1},paste:function(a,b){return a=this.get_node(a),a&&e&&e.match(/^(copy_node|move_node)$/)&&d?(this[e](d,a,b,!1,!1,!1,f)&&this.trigger("paste",{parent:a.id,node:d,mode:e}),d=!1,e=!1,void(f=!1)):!1},clear_buffer:function(){d=!1,e=!1,f=!1,this.trigger("clear_buffer")},edit:function(b,c,d){var e,f,g,h,j,k,l,m,n,o=!1;return(b=this.get_node(b))?this.check("edit",b,this.get_parent(b))?(n=b,c="string"==typeof c?c:b.text,this.set_text(b,""),b=this._open_to(b),n.text=c,e=this._data.core.rtl,f=this.element.width(),this._data.core.focused=n.id,g=b.children(".jstree-anchor").focus(),h=a("<span></span>"),j=c,k=a("<div></div>",{css:{position:"absolute",top:"-200px",left:e?"0px":"-1000px",visibility:"hidden"}}).appendTo(i.body),l=a("<input />",{value:j,"class":"jstree-rename-input",css:{padding:"0",border:"1px solid silver","box-sizing":"border-box",display:"inline-block",height:this._data.core.li_height+"px",lineHeight:this._data.core.li_height+"px",width:"150px"},blur:a.proxy(function(c){c.stopImmediatePropagation(),c.preventDefault();var e=h.children(".jstree-rename-input"),f=e.val(),i=this.settings.core.force_text,m;""===f&&(f=j),k.remove(),h.replaceWith(g),h.remove(),j=i?j:a("<div></div>").append(a.parseHTML(j)).html(),b=this.get_node(b),this.set_text(b,j),m=!!this.rename_node(b,i?a("<div></div>").text(f).text():a("<div></div>").append(a.parseHTML(f)).html()),m||this.set_text(b,j),this._data.core.focused=n.id,setTimeout(a.proxy(function(){var a=this.get_node(n.id,!0);a.length&&(this._data.core.focused=n.id,a.children(".jstree-anchor").focus())},this),0),d&&d.call(this,n,m,o),l=null},this),keydown:function(a){var b=a.which;27===b&&(o=!0,this.value=j),(27===b||13===b||37===b||38===b||39===b||40===b||32===b)&&a.stopImmediatePropagation(),(27===b||13===b)&&(a.preventDefault(),this.blur())},click:function(a){a.stopImmediatePropagation()},mousedown:function(a){a.stopImmediatePropagation()},keyup:function(a){l.width(Math.min(k.text("pW"+this.value).width(),f))},keypress:function(a){return 13===a.which?!1:void 0}}),m={fontFamily:g.css("fontFamily")||"",fontSize:g.css("fontSize")||"",fontWeight:g.css("fontWeight")||"",fontStyle:g.css("fontStyle")||"",fontStretch:g.css("fontStretch")||"",fontVariant:g.css("fontVariant")||"",letterSpacing:g.css("letterSpacing")||"",wordSpacing:g.css("wordSpacing")||""},h.attr("class",g.attr("class")).append(g.contents().clone()).append(l),g.replaceWith(h),k.css(m),l.css(m).width(Math.min(k.text("pW"+l[0].value).width(),f))[0].select(),void a(i).one("mousedown.jstree touchstart.jstree dnd_start.vakata",function(b){l&&b.target!==l&&a(l).blur()})):(this.settings.core.error.call(this,this._data.core.last_error),!1):!1},set_theme:function(b,c){if(!b)return!1;if(c===!0){var d=this.settings.core.themes.dir;d||(d=a.jstree.path+"/themes"),c=d+"/"+b+"/style.css"}c&&-1===a.inArray(c,g)&&(a("head").append('<link rel="stylesheet" href="'+c+'" type="text/css" />'),g.push(c)),this._data.core.themes.name&&this.element.removeClass("jstree-"+this._data.core.themes.name),this._data.core.themes.name=b,this.element.addClass("jstree-"+b),this.element[this.settings.core.themes.responsive?"addClass":"removeClass"]("jstree-"+b+"-responsive"),this.trigger("set_theme",{theme:b})},get_theme:function(){return this._data.core.themes.name},set_theme_variant:function(a){this._data.core.themes.variant&&this.element.removeClass("jstree-"+this._data.core.theLine truncated
item:b,reference:c.reference,element:c.element}))&&b.action?b.action.call(null,{item:b,reference:c.reference,element:c.element,position:{x:c.position_x,y:c.position_y}}):!1},_parse:function(b,d){if(!b)return!1;d||(c.html="",c.items=[]);var e="",f=!1,g;return d&&(e+="<ul>"),a.each(b,function(b,d){return d?(c.items.push(d),!f&&d.separator_before&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+">&#160;</a></li>"),f=!1,e+="<li class='"+(d._class||"")+(d._disabled===!0||a.isFunction(d._disabled)&&d._disabled({item:d,reference:c.reference,element:c.element})?" vakata-contextmenu-disabled ":"")+"' "+(d.shortcut?" data-shortcut='"+d.shortcut+"' ":"")+">",e+="<a href='#' rel='"+(c.items.length-1)+"' "+(d.title?"title='"+d.title+"'":"")+">",a.vakata.context.settings.icons&&(e+="<i ",d.icon&&(e+=-1!==d.icon.indexOf("/")||-1!==d.icon.indexOf(".")?" style='background:url(\""+d.icon+"\") center center no-repeat' ":" class='"+d.icon+"' "),e+="></i><span class='vakata-contextmenu-sep'>&#160;</span>"),e+=(a.isFunction(d.label)?d.label({item:b,reference:c.reference,element:c.element}):d.label)+(d.shortcut?' <span class="vakata-contextmenu-shortcut vakata-contextmenu-shortcut-'+d.shortcut+'">'+(d.shortcut_label||"")+"</span>":"")+"</a>",d.submenu&&(g=a.vakata.context._parse(d.submenu,!0),g&&(e+=g)),e+="</li>",void(d.separator_after&&(e+="<li class='vakata-context-separator'><a href='#' "+(a.vakata.context.settings.icons?"":'style="margin-left:0px;"')+">&#160;</a></li>",f=!0))):!0}),e=e.replace(/<li class\='vakata-context-separator'\><\/li\>$/,""),d&&(e+="</ul>"),d||(c.html=e,a.vakata.context._trigger("parse")),e.length>10?e:!1},_show_submenu:function(c){if(c=a(c),c.length&&c.children("ul").length){var d=c.children("ul"),e=c.offset().left,f=e+c.outerWidth(),g=c.offset().top,h=d.width(),i=d.height(),j=a(window).width()+a(window).scrollLeft(),k=a(window).height()+a(window).scrollTop();b?c[f-(h+10+c.outerWidth())<0?"addClass":"removeClass"]("vakata-context-left"):c[f+h>j&&e>j-f?"addClass":"removeClass"]("vakata-context-right"),g+i+10>k&&d.css("bottom","-1px"),c.hasClass("vakata-context-right")?h>e&&d.css("margin-right",e-h):h>j-f&&d.css("margin-left",j-f-h),d.show()}},show:function(d,e,f){var g,h,j,k,l,m,n,o,p=!0;switch(c.element&&c.element.length&&c.element.width(""),p){case!e&&!d:return!1;case!!e&&!!d:c.reference=d,c.position_x=e.x,c.position_y=e.y;break;case!e&&!!d:c.reference=d,g=d.offset(),c.position_x=g.left+d.outerHeight(),c.position_y=g.top;break;case!!e&&!d:c.position_x=e.x,c.position_y=e.y}d&&!f&&a(d).data("vakata_contextmenu")&&(f=a(d).data("vakata_contextmenu")),a.vakata.context._parse(f)&&c.element.html(c.html),c.items.length&&(c.element.appendTo(i.body),h=c.element,j=c.position_x,k=c.position_y,l=h.width(),m=h.height(),n=a(window).width()+a(window).scrollLeft(),o=a(window).height()+a(window).scrollTop(),b&&(j-=h.outerWidth()-a(d).outerWidth(),j<a(window).scrollLeft()+20&&(j=a(window).scrollLeft()+20)),j+l+20>n&&(j=n-(l+20)),k+m+20>o&&(k=o-(m+20)),c.element.css({left:j,top:k}).show().find("a").first().focus().parent().addClass("vakata-context-hover"),c.is_visible=!0,a.vakata.context._trigger("show"))},hide:function(){c.is_visible&&(c.element.hide().find("ul").hide().end().find(":focus").blur().end().detach(),c.is_visible=!1,a.vakata.context._trigger("hide"))}},a(function(){b="rtl"===a(i.body).css("direction");var d=!1;c.element=a("<ul class='vakata-context'></ul>"),c.element.on("mouseenter","li",function(b){b.stopImmediatePropagation(),a.contains(this,b.relatedTarget)||(d&&clearTimeout(d),c.element.find(".vakata-context-hover").removeClass("vakata-context-hover").end(),a(this).siblings().find("ul").hide().end().end().parentsUntil(".vakata-context","li").addBack().addClass("vakata-context-hover"),a.vakata.context._show_submenu(this))}).on("mouseleave","li",function(b){a.contains(this,b.relatedTarget)||a(this).find(".vakata-context-hover").addBack().removeClass("vakata-context-hover")}).on("mouseleave",function(b){a(this).find(".vakata-context-hover").removeClass("vakata-context-hover"),a.vakata.context.settings.hide_onmouseleave&&(d=setTimeout(function(b){return function(){a.vakata.context.hide()}}(this),a.vakata.context.settings.hide_onmouseleave))}).on("click","a",function(b){b.preventDefault(),a(this).blur().parent().hasClass("vakata-context-disabled")||a.vakata.context._execute(a(this).attr("rel"))===!1||a.vakata.context.hide()}).on("keydown","a",function(b){var d=null;switch(b.which){case 13:case 32:b.type="click",b.preventDefault(),a(b.currentTarget).trigger(b);break;case 37:c.is_visible&&(c.element.find(".vakata-context-hover").last().closest("li").first().find("ul").hide().find(".vakata-context-hover").removeClass("vakata-context-hover").end().end().children("a").focus(),b.stopImmediatePropagation(),b.preventDefault());break;case 38:c.is_visible&&(d=c.element.find("ul:visible").addBack().last().children(".vakata-context-hover").removeClaLine truncated
e[f[h]].type=j,e[f[h]].icon===!0&&g[j].icon!==b&&(e[f[h]].icon=g[j].icon),g[j].li_attr!==b&&"object"==typeof g[j].li_attr)for(k in g[j].li_attr)if(g[j].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].li_attr[k]===b?e[f[h]].li_attr[k]=g[j].li_attr[k]:"class"===k&&(e[f[h]].li_attr["class"]=g[j].li_attr["class"]+" "+e[f[h]].li_attr["class"])}if(g[j].a_attr!==b&&"object"==typeof g[j].a_attr)for(k in g[j].a_attr)if(g[j].a_attr.hasOwnProperty(k)){if("id"===k)continue;e[f[h]].a_attr[k]===b?e[f[h]].a_attr[k]=g[j].a_attr[k]:"href"===k&&"#"===e[f[h]].a_attr[k]?e[f[h]].a_attr.href=g[j].a_attr.href:"class"===k&&(e[f[h]].a_attr["class"]=g[j].a_attr["class"]+" "+e[f[h]].a_attr["class"])}}e[a.jstree.root].type=a.jstree.root},this)),d.bind.call(this)},this.get_json=function(b,c,e){var f,g,h=this._model.data,i=c?a.extend(!0,{},c,{no_id:!1}):{},j=d.get_json.call(this,b,i,e);if(j===!1)return!1;if(a.isArray(j))for(f=0,g=j.length;g>f;f++)j[f].type=j[f].id&&h[j[f].id]&&h[j[f].id].type?h[j[f].id].type:"default",c&&c.no_id&&(delete j[f].id,j[f].li_attr&&j[f].li_attr.id&&delete j[f].li_attr.id,j[f].a_attr&&j[f].a_attr.id&&delete j[f].a_attr.id);else j.type=j.id&&h[j.id]&&h[j.id].type?h[j.id].type:"default",c&&c.no_id&&(j=this._delete_ids(j));return j},this._delete_ids=function(b){if(a.isArray(b)){for(var c=0,d=b.length;d>c;c++)b[c]=this._delete_ids(b[c]);return b}return delete b.id,b.li_attr&&b.li_attr.id&&delete b.li_attr.id,b.a_attr&&b.a_attr.id&&delete b.a_attr.id,b.children&&a.isArray(b.children)&&(b.children=this._delete_ids(b.children)),b},this.check=function(c,e,f,g,h){if(d.check.call(this,c,e,f,g,h)===!1)return!1;e=e&&e.id?e:this.get_node(e),f=f&&f.id?f:this.get_node(f);var i=e&&e.id?h&&h.origin?h.origin:a.jstree.reference(e.id):null,j,k,l,m;switch(i=i&&i._model&&i._model.data?i._model.data:null,c){case"create_node":case"move_node":case"copy_node":if("move_node"!==c||-1===a.inArray(e.id,f.children)){if(j=this.get_rules(f),j.max_children!==b&&-1!==j.max_children&&j.max_children===f.children.length)return this._data.core.last_error={error:"check",plugin:"types",id:"types_01",reason:"max_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(j.valid_children!==b&&-1!==j.valid_children&&-1===a.inArray(e.type||"default",j.valid_children))return this._data.core.last_error={error:"check",plugin:"types",id:"types_02",reason:"valid_children prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;if(i&&e.children_d&&e.parents){for(k=0,l=0,m=e.children_d.length;m>l;l++)k=Math.max(k,i[e.children_d[l]].parents.length);k=k-e.parents.length+1}(0>=k||k===b)&&(k=1);do{if(j.max_depth!==b&&-1!==j.max_depth&&j.max_depth<k)return this._data.core.last_error={error:"check",plugin:"types",id:"types_03",reason:"max_depth prevents function: "+c,data:JSON.stringify({chk:c,pos:g,obj:e&&e.id?e.id:!1,par:f&&f.id?f.id:!1})},!1;f=this.get_node(f.parent),j=this.get_rules(f),k++}while(f)}}return!0},this.get_rules=function(a){if(a=this.get_node(a),!a)return!1;var c=this.get_type(a,!0);return c.max_depth===b&&(c.max_depth=-1),c.max_children===b&&(c.max_children=-1),c.valid_children===b&&(c.valid_children=-1),c},this.get_type=function(b,c){return b=this.get_node(b),b?c?a.extend({type:b.type},this.settings.types[b.type]):b.type:!1},this.set_type=function(c,d){var e=this._model.data,f,g,h,i,j,k,l,m;if(a.isArray(c)){for(c=c.slice(),g=0,h=c.length;h>g;g++)this.set_type(c[g],d);return!0}if(f=this.settings.types,c=this.get_node(c),!f[d]||!c)return!1;if(l=this.get_node(c,!0),l&&l.length&&(m=l.children(".jstree-anchor")),i=c.type,j=this.get_icon(c),c.type=d,(j===!0||!f[i]||f[i].icon!==b&&j===f[i].icon)&&this.set_icon(c,f[d].icon!==b?f[d].icon:!0),f[i]&&f[i].li_attr!==b&&"object"==typeof f[i].li_attr)for(k in f[i].li_attr)if(f[i].li_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].li_attr["class"]=(e[c.id].li_attr["class"]||"").replace(f[i].li_attr[k],""),l&&l.removeClass(f[i].li_attr[k])):e[c.id].li_attr[k]===f[i].li_attr[k]&&(e[c.id].li_attr[k]=null,l&&l.removeAttr(k))}if(f[i]&&f[i].a_attr!==b&&"object"==typeof f[i].a_attr)for(k in f[i].a_attr)if(f[i].a_attr.hasOwnProperty(k)){if("id"===k)continue;"class"===k?(e[c.id].a_attr["class"]=(e[c.id].a_attr["class"]||"").replace(f[i].a_attr[k],""),m&&m.removeClass(f[i].a_attr[k])):e[c.id].a_attr[k]===f[i].a_attr[k]&&("href"===k?(e[c.id].a_attr[k]="#",m&&m.attr("href","#")):(delete e[c.id].a_attr[k],m&&m.removeAttr(k)))}if(f[d].li_attr!==b&&"object"==typeof f[d].li_attr)for(k in f[d].li_attr)if(f[d].li_attr.hasOwnProperty(k)){if("id"===k)continue;e[c.id].li_attr[k]===b?(e[c.id].li_attr[k]=f[d].li_attr[k],l&&("class"===k?l.addClass(f[d].li_attr[k]):l.attr(k,f[d].li_attr[k]))):"class"===k&&(e[c.id].li_attr["class"]=f[d].li_attr[k]+" "+e[c.id].li_attr["class"],l&&l.addClass(f[d].li_attr[k]))}if(f[d].a_attr!==b&&"object"==typeof f[d].a_attr)for(k in f[d].a_attr)if(f[d].a_attr.hasOwnProperty(k)){if("idLine truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:black;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-hidden,.jstree-node.jstree-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.jstree-contextmenu .jstree-anchor{-webkit-user-select:none;-webkit-touch-callout:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none}.vakata-context li>a{display:block;padding:0 2em 0 2em;text-decoration:none;width:auto;color:black;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 white;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==");background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:white;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context .vakata-contextmenu-disabled>a>i{filter:grayscale(100%)}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:transparent;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:white;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url("data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7");background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:white;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:Line truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

+8 -19
View File
@@ -1,8 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/main.js?v=0.1.18" type="module"></script>
<script src="dist/jstree.min.js"></script>
<script src="/js/main.js?v=0.1.2" type="module"></script>
</head>
<body>
<h3>Klippy Web API Test</h3>
@@ -37,27 +39,13 @@
</form>
<br/>
<div style="display: flex">
<input type="file" style="display:none" id="upload-file" />
<div style="width: 10em">
<button id="btnupload" class="toggleable" style="width: 9em">Upload File</button><br/><br/>
<button id="btndownload" class="toggleable" style="width: 9em">Download File</button><br/><br/>
<button id="btndelete" class="toggleable" style="width: 9em">Delete File</button><br/><br/>
<button id="btngetfiles" style="width: 9em">Refresh List</button>
<a id="hidden_link" href="#" hidden>hidden</a>
</div>
<div style="width: 10em">
<button id="btnstartprint" style="width: 9em">Start Print</button><br/><br/>
<button id="btnpauseresume" style="width: 9em">Pause Print</button><br/><br/>
<button id="btncancelprint" style="width: 9em">Cancel Print</button><br/><br/>
<button id="btngetmetadata" style="width: 9em">Get Metadata</button>
</div>
<div>
<select id="filelist" size="8"></select>
</div>
<div id=filetype>
<input type="radio" name="file_type" value="gcodes" checked="true">GCodes<br/>
<input type="radio" name="file_type" value="config">Config Files<br/>
<input type="radio" name="file_type" value="config_examples">Config Examples
<a id="hidden_link" href="#" hidden>hidden</a>
<input type="file" style="display:none" id="upload-file" />
<div id="filelist">
</div>
</div>
<br/>
@@ -65,9 +53,10 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
<span id="upload_progress">0%</span><br/><br/>
<button id="btnqueryendstops" style="width: 9em">Query Endstops</button>
<button id="btnsubscribe" style="width: 9em">Post Subscription</button>
<button id="btngetsub" style="width: 9em">Get Subscription</button>
<button id="btngetfiles" style="width: 9em">Get File List</button>
<button id="btngethelp" style="width: 9em">Get Gcode Help</button>
<button id="btngetobjs" style="width: 9em">Get Object List</button>
<button id="btntestmesh" style="width: 9em">Get Bed Mesh</button>
<button id="btnsendbatch" class="reqws" style="width: 9em">Test GC Batch</button>
<button id="btnsendmacro" class="reqws" style="width: 9em">Test GC Macro</button>
<br/><br/>
+713 -351
View File
File diff suppressed because it is too large. Load diff