Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
210f505157 | ||
|
|
61c62154ae | ||
|
|
c18f0dac60 | ||
|
|
daad55640b | ||
|
|
e489b795e6 | ||
|
|
6b91b1eac1 | ||
|
|
c0389fbf3f | ||
|
|
9b0c9810a4 | ||
|
|
da9b9e184d | ||
|
|
eb681fc960 | ||
|
|
6b0d981274 | ||
|
|
f1f318ea40 | ||
|
|
fb1f76e008 | ||
|
|
d6de095e66 | ||
|
|
b1f8eaae51 | ||
|
|
f0a6620267 | ||
|
|
eec85f86a9 | ||
|
|
e7f605327f | ||
|
|
4b13af4d86 | ||
|
|
f38cacd513 | ||
|
|
c48fe983de | ||
|
|
8acd0f2728 | ||
|
|
1dc920019c | ||
|
|
976f9a732c | ||
|
|
bf67bce65f | ||
|
|
f5c27f27ce | ||
|
|
480430720f | ||
|
|
fe8c7af79f | ||
|
|
891d6bd871 | ||
|
|
e251f26487 | ||
|
|
e2894b9907 | ||
|
|
92ac1ee21f | ||
|
|
6e6d974bad | ||
|
|
8e609c503f | ||
|
|
7949b6400b | ||
|
|
8d93bcf438 | ||
|
|
ce78e42065 | ||
|
|
ed217fb3e9 | ||
|
|
0c455fcc0d | ||
|
|
5e99378466 | ||
|
|
48621da6aa | ||
|
|
47902cb03c | ||
|
|
038fcec1f4 | ||
|
|
06c35fa0b2 | ||
|
|
3f48dd5510 | ||
|
|
d9d087b9f3 | ||
|
|
1e8ec5c517 | ||
|
|
06a07f09e5 | ||
|
|
94ed9fbd7f | ||
|
|
cd4641f959 | ||
|
|
4b89de53f7 | ||
|
|
62265fd086 | ||
|
|
e990e64ccd | ||
|
|
1615af731b | ||
|
|
dc60143ef8 | ||
|
|
7e230c1c77 | ||
|
|
78324e0df4 | ||
|
|
a04958b1bf | ||
|
|
f09cd413ca | ||
|
|
62012726da | ||
|
|
a5c455a305 | ||
|
|
ca2bd380cf | ||
|
|
05b8c4eaef | ||
|
|
3b99307109 | ||
|
|
5f741c28a5 | ||
|
|
91e59706fa | ||
|
|
ec3bb22c63 | ||
|
|
978fcffab5 | ||
|
|
083d63568c | ||
|
|
53ad4cb493 | ||
|
|
dd321a4754 | ||
|
|
84bc9aa311 | ||
|
|
1367083f99 | ||
|
|
9331031f55 | ||
|
|
f0adbcf62d | ||
|
|
d45ec3466e | ||
|
|
832eb6f130 | ||
|
|
9988da72c1 | ||
|
|
7c89756263 | ||
|
|
92de4b75ee | ||
|
|
93e7eaa5b5 | ||
|
|
0a3a83de37 | ||
|
|
df82730832 | ||
|
|
9632465a78 | ||
|
|
22b3a953c5 | ||
|
|
51fd460b59 | ||
|
|
2e0d3f36b4 | ||
|
|
5144508410 | ||
|
|
056a9db23e | ||
|
|
d20631e69f | ||
|
|
15890b9e87 | ||
|
|
9563bcff11 | ||
|
|
5d095125d3 | ||
|
|
44f1147f71 | ||
|
|
dc165636cb | ||
|
|
29644bd44c | ||
|
|
606625a3aa | ||
|
|
438ffece72 | ||
|
|
d108334c37 | ||
|
|
13ccdb4df1 | ||
|
|
4de33bae4a | ||
|
|
316fac1e75 | ||
|
|
d057795bee | ||
|
|
4efce1b868 | ||
|
|
db13827a48 | ||
|
|
4c914d7b4d | ||
|
|
f1edaa1f61 | ||
|
|
a111733431 | ||
|
|
c8a2aa7a6c | ||
|
|
84f663e2bc | ||
|
|
6ba45f6e35 | ||
|
|
39ab419c1f | ||
|
|
228ed34eb1 | ||
|
|
0fa3c14f51 | ||
|
|
46680f4cda | ||
|
|
e32c14b1a7 | ||
|
|
1f9d896e17 | ||
|
|
d9edcd9396 | ||
|
|
22a5f6720c | ||
|
|
cea9af1ef8 | ||
|
|
63c685e1c4 | ||
|
|
84f46b1cb1 | ||
|
|
d1dfa86081 | ||
|
|
dbf5f93919 | ||
|
|
d878340a7a | ||
|
|
fb24917f1a | ||
|
|
62324650e5 | ||
|
|
bf48744048 | ||
|
|
6c994f6c9c | ||
|
|
bb3eb27b3d | ||
|
|
94b690c2e9 | ||
|
|
aa4c13742e | ||
|
|
900345e2d9 | ||
|
|
ec85b31a62 | ||
|
|
ab6ed40bcb | ||
|
|
87e136003f | ||
|
|
7ff54d8f2f | ||
|
|
9e41d9d84b | ||
|
|
75dce0af1a | ||
|
|
4abfb886f5 | ||
|
|
979aef2903 | ||
|
|
958a0f3270 | ||
|
|
54b1bd8b04 | ||
|
|
1f61357dd6 | ||
|
|
b89aa77bc9 | ||
|
|
537ba281ab | ||
|
|
83c24ff765 | ||
|
|
b726747261 | ||
|
|
eb37ce767d | ||
|
|
60ba8ff1d5 | ||
|
|
45557b8260 | ||
|
|
f229c3ec2c | ||
|
|
0e22a0cfe8 | ||
|
|
f2135d7483 | ||
|
|
baf97f8ea4 | ||
|
|
29b89fb87d | ||
|
|
ec7936ee97 | ||
|
|
ceaa4911bb | ||
|
|
f9dcda7ba9 | ||
|
|
0fcae5b6e4 | ||
|
|
dd81beab47 | ||
|
|
9648630392 | ||
|
|
fe2cec1087 | ||
|
|
81104a6618 | ||
|
|
980912270e | ||
|
|
39334d1098 | ||
|
|
943b78195b | ||
|
|
49c5583e95 | ||
|
|
e8776a5d85 | ||
|
|
9c385ce067 | ||
|
|
9e240c3b86 | ||
|
|
c365de32cf | ||
|
|
aa9bf0fb9c | ||
|
|
ddc7405249 | ||
|
|
25b3911d3d | ||
|
|
19bc2bfbb8 | ||
|
|
578ce740c5 | ||
|
|
6a88df095e | ||
|
|
c17d86aa09 | ||
|
|
0ad97fd9eb | ||
|
|
f3ae6da635 | ||
|
|
e9ab5fb480 | ||
|
|
21d1726bfd | ||
|
|
0b3b8cede8 | ||
|
|
00db209d5d | ||
|
|
b4602115d7 | ||
|
|
ff8e53b269 | ||
|
|
e2c325a724 | ||
|
|
a1f2228473 | ||
|
|
d70bd8d2e0 | ||
|
|
8c365c62cb | ||
|
|
6f4a72fe2e | ||
|
|
bdd270fa4a | ||
|
|
d194ce00ab | ||
|
|
5f986ab770 | ||
|
|
e0f4b46364 | ||
|
|
fb3706c54f | ||
|
|
d1388080c4 | ||
|
|
f1a75117db | ||
|
|
4ae63dbbf8 | ||
|
|
30637011e6 | ||
|
|
8a18fa6c2f | ||
|
|
4cd97d61f9 | ||
|
|
40f876192c | ||
|
|
fa53d889d0 | ||
|
|
6fcb26ddd7 | ||
|
|
67adcfc448 | ||
|
|
0c280122fb | ||
|
|
5b9f637c2d | ||
|
|
2bb9128b5b | ||
|
|
222f0c4695 | ||
|
|
ea1ad0277d | ||
|
|
1e81297624 | ||
|
|
ae3661b100 | ||
|
|
67f5b32d84 | ||
|
|
14b5384572 | ||
|
|
c261ee51f3 | ||
|
|
67f992dabd | ||
|
|
a535e6e94a | ||
|
|
4aa2a86e3b | ||
|
|
7d738c7a8b | ||
|
|
f753263c60 | ||
|
|
2f8a1567a8 | ||
|
|
933622adda | ||
|
|
1814a11a8d | ||
|
|
77c483ea0f | ||
|
|
96941922bc | ||
|
|
1f2c1b3fcd | ||
|
|
2953c3f16f | ||
|
|
8fc5aab2f0 | ||
|
|
1acb00e2f1 | ||
|
|
b0fda218f1 | ||
|
|
34af0b4bfb | ||
|
|
fad6bc4ad7 | ||
|
|
9501d72059 | ||
|
|
9993b1e656 | ||
|
|
b5394228ef | ||
|
|
6bf4ef8b00 | ||
|
|
0a7080741c | ||
|
|
223c125106 | ||
|
|
f9fc679831 | ||
|
|
586bb6a7ca | ||
|
|
76ccc8b3e1 | ||
|
|
f91e425463 | ||
|
|
46de7c48c8 | ||
|
|
063ef7194a | ||
|
|
313357061e | ||
|
|
0f62b283bd | ||
|
|
9f9a05cabb | ||
|
|
40fbe1abf1 | ||
|
|
9a309ffd59 | ||
|
|
684ff07ba2 | ||
|
|
0a7eed2767 | ||
|
|
6898ff8ab6 | ||
|
|
653c9190c4 | ||
|
|
cdbaaedc8a | ||
|
|
fa20d106cf | ||
|
|
40b74cefb5 | ||
|
|
20d27b0be6 | ||
|
|
44bdf708e6 | ||
|
|
2ddd1966fe | ||
|
|
8bb7139468 | ||
|
|
ba4d771d10 | ||
|
|
eea2abd60e | ||
|
|
70501772c1 | ||
|
|
119b0bf60c | ||
|
|
59e58226ff | ||
|
|
ec5be560d5 | ||
|
|
d19e9e2d28 | ||
|
|
abbd02aa73 | ||
|
|
1b997b7457 | ||
|
|
6dfd3ca915 | ||
|
|
aaa6ec8eb2 | ||
|
|
aba5bdf339 | ||
|
|
43e2893e01 | ||
|
|
e025a5ce01 | ||
|
|
2e44766e1e | ||
|
|
77f79fcc20 | ||
|
|
1d0a790ef5 | ||
|
|
e2a8a9b49f |
No files matched your search
@@ -0,0 +1,4 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
@@ -0,0 +1,10 @@
|
||||
version: 2
|
||||
|
||||
mkdocs:
|
||||
configuration: mkdocs.yml
|
||||
fail_on_warning: false
|
||||
|
||||
python:
|
||||
version: 3.8
|
||||
install:
|
||||
- requirements: docs/doc-requirements.txt
|
||||
@@ -1,14 +1,21 @@
|
||||
# Moonraker - API Web Server for Klipper
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use to interact with Klipper. Communcation between
|
||||
client applications may use to interact with
|
||||
[Klipper](https://github.com/KevinOConnor/klipper). Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
|
||||
is used to provide Moonraker's server functionality.
|
||||
|
||||
Documentation for users and developers can be found on
|
||||
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
|
||||
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following web clients are currently available:
|
||||
install one. The following clients are currently available:
|
||||
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
|
||||
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
|
||||
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -17,7 +24,7 @@ to see if any action is necessary on their part. The date of the most
|
||||
recent change is included.
|
||||
|
||||
Users:\
|
||||
[user_changes.md](/docs/user_changes.md) - November 19th 2020
|
||||
[user_changes.md](https://moonraker.readthedocs.io/en/latest/user_changes/) - March 10th 2021
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - November 28th 2020
|
||||
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
|
||||
@@ -1,5 +1,53 @@
|
||||
##
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
|
||||
### March 15th 2021
|
||||
- The `data` field for gcode thumbnails is now deprecated and will
|
||||
be removed in the near future. Thumbnails are now saved to png
|
||||
files in a `thumbs` directory relative to a gcode file's location.
|
||||
This path is available in the `relative_path` field for each
|
||||
thumbnail entry in the metadata.
|
||||
|
||||
### January 31st 2021
|
||||
- The `GET /server/temperature_store` endpoint now only returns fields
|
||||
that each sensor reports. For example, if a particuarly temperature
|
||||
sensor does not report "target" or "power", then the corresponding
|
||||
fields will not be reported for that sensor in response to the
|
||||
`temperature_store` request.
|
||||
|
||||
### January 22nd 2021
|
||||
- The `POST /machine/update/client` endpoint now requires a `name`
|
||||
argument. This change added multiple client support
|
||||
- The response to `GET /machine/update/status` no longer returns a
|
||||
`client` field. Instead it will add fields matching the `name` of
|
||||
each configured client. Keep in mind that the client object could
|
||||
have a different set of fields depending on the type of a client. The
|
||||
easy way to check for this is to see if a `branch` field is present.
|
||||
If so, this client is a `git repo`. Otherwise it is a `web` client.
|
||||
|
||||
### January 4th 2021
|
||||
- A `notify_update_refreshed` notification has been added. Moonraker now
|
||||
auto-refreshes the update status at roughly a 2 hour interval. When
|
||||
an auto-refresh is complete this notification is broadcast. Included
|
||||
is an object that matches the response from `/machine/update/status`.
|
||||
- The behavior of some of the `update_manager` APIs has changed:
|
||||
- The `refresh` argument for `/machine/update/status` is now more
|
||||
of a suggestion than a rule. If an update or a print is in
|
||||
progress then the request will ignore the refresh argument
|
||||
and immediately return the current status. Generally speaking requesting
|
||||
a refresh should not be necessary with addition of auto refresh.
|
||||
- The update requests (ie `/machine/update/klipper`) will now return
|
||||
an error if a print is in progress. If the requested update is in
|
||||
progress then the request will return valid with a message stating
|
||||
that the update is in progress. If another object is being updated
|
||||
then the request will be queued and block until it its complete.
|
||||
### January 1st 2021
|
||||
- A `notify_klippy_shutdown` websocket notification has been added
|
||||
|
||||
### December 30th 2020
|
||||
- Some additional fields are now reported in the response to
|
||||
`GET /machine/update/status`.
|
||||
|
||||
### November 28th 2020
|
||||
- The following new endpoints are available when the `[update_manager]`
|
||||
section has been configured:
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
## Components
|
||||
|
||||
Components in Moonraker are used to extend Moonraker's functionality,
|
||||
similar to "extras" in Klipper. Moonraker divides components into
|
||||
two categories, "core" components and "optional" components. A core
|
||||
component gets its configuration from the `[server]` section and is
|
||||
loaded when Moonraker starts. For example, the `file_manager` is a
|
||||
core component. If a core component fails to load Moonraker will
|
||||
exit with an error.
|
||||
|
||||
Optional components must be configured in `moonraker.conf`. If they
|
||||
have no specific configuration, a bare section, such as `[octoprint_compat]`
|
||||
must be present in `moonraker.conf`. Unlike with core components,
|
||||
Moonraker will still start if an optional component fails to load.
|
||||
Its failed status will be available for clients to query and present
|
||||
to the user.
|
||||
|
||||
### Basic Example
|
||||
|
||||
Components exist in the `components` directory. The below example
|
||||
shows how an `example.py` component might look:
|
||||
```python
|
||||
# Example Component
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
class Example:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.name = config.get_name()
|
||||
|
||||
# Raises an error if "example_int_option" is not configured in
|
||||
# the [example] section
|
||||
self.example_int_opt = config.getint("example_int_option")
|
||||
|
||||
# Returns a NoneType if "example_float_option is not configured
|
||||
# in the config
|
||||
self.example_float_opt = config.getfloat("example_float_option", None)
|
||||
|
||||
self.server.register_endpoint("/server/example", ['GET'],
|
||||
self._handle_example request)
|
||||
|
||||
async def request_some_klippy_state(self):
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
return await klippy_apis.query_objects({'print_stats': None})
|
||||
|
||||
async def _handle_example_request(self, web_request):
|
||||
web_request.get_int("required_reqest_param")
|
||||
web_request.get_float("optional_request_param", None)
|
||||
state = await self.request_some_klippy_state()
|
||||
return {"example_return_value": state}
|
||||
|
||||
def load_component(config):
|
||||
return Example(config)
|
||||
|
||||
```
|
||||
If you have created a "Klippy extras" module then the above should look
|
||||
look familiar. Moonraker attempts to use similar method for adding
|
||||
extensions, making easier Klipper contributors to add new functionality
|
||||
to Moonraker. Be aware that there is no "Reactor" object in Moonraker,
|
||||
it uses `asyncio` for coroutines. Like Klippy, you should not write
|
||||
code that blocks the main thread.
|
||||
|
||||
### The ConfigHelper Object
|
||||
|
||||
As shown above, each component is passed a config object. This object
|
||||
will be a `ConfigHelper` type, which is an object that wraps a
|
||||
configuration section to simply access to the native `ConfigParser`.
|
||||
A `ConfigHelper` should never be directly instantiated.
|
||||
|
||||
#### *ConfigHelper.get_server()*
|
||||
|
||||
Returns the primary [server](#the-server-object) instance.
|
||||
|
||||
#### *ConfigHelper.get_name()*
|
||||
|
||||
Returns the configuration section name associated with this `ConfigHelper`.
|
||||
|
||||
#### *ConfigHelper.get(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a string. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getint(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as an integer. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getfloat(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a float. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getboolean(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a boolean. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.has_section(section_name)*
|
||||
|
||||
Returns True if a section matching `section_name` is in the configuration,
|
||||
otherwise False.
|
||||
|
||||
Note that a ConfigHelper object also implements `__contains__`,
|
||||
which is an alias for `has_section`, ie: `section_name in config_instance`
|
||||
|
||||
#### *ConfigHelper.getsection(section_name)*
|
||||
|
||||
Returns a Config object for the section matching `section_name`. If the
|
||||
section does not exist in the configuration raises a `ConfigError`.
|
||||
|
||||
Note that a ConfigHelper object also implements `__getitem__`,
|
||||
which is an alias for `get_section`, ie: `config_instance[section_name]`
|
||||
|
||||
#### *ConfigHelper.get_options()*
|
||||
|
||||
Returns a dict mapping options to values for all options in the Config
|
||||
object.
|
||||
|
||||
#### *ConfigHelper.get_prefix_sections(prefix)*
|
||||
|
||||
Returns a list section names in the configuration that start with `prefix`.
|
||||
These strings can be used to retreve ConfigHelpers via
|
||||
[get_section()](#confighelpergetsectionsection_name).
|
||||
|
||||
### The Server Object
|
||||
|
||||
The server instance represents the central management object in Moonraker.
|
||||
It can be used to register endpoints, register notifications, look up other
|
||||
components, send events, and more.
|
||||
|
||||
#### *Server.lookup_component(component_name, default=Sentinel)*
|
||||
|
||||
Attempts to look up a loaded component, returning the result. If
|
||||
the component has not been loaded, `default` will be returned.
|
||||
If `default` is not provided a `ServerError` will be raised.
|
||||
|
||||
#### *Server.load_component(config, component_name, default=Sentinel)*
|
||||
|
||||
Attempts to load an uninitialized component and returns the result. It is
|
||||
only valid to call this within a a component's `__init__()` method, and
|
||||
should only be necessary if one optional component relies on another. Core components will always be loaded before optional components, thus an optional
|
||||
component may always call
|
||||
[lookup_component()](#serverlookup_componentcomponent_name-defaultsentinel)
|
||||
when it needs a reference to core component.
|
||||
|
||||
If the component fails to load `default` will be returned. If `default`
|
||||
is not provided a `ServerError` will be raised.
|
||||
|
||||
#### *Server.register_endpoint(uri, request_methods, callback, protocol=["http", "websocket"], wrap_result=True)*
|
||||
|
||||
Registers the supplied `uri` with the server.
|
||||
|
||||
The `request_methods` argument should be a list of strings containing any
|
||||
combination of `GET`, `POST`, and `DELETE`.
|
||||
|
||||
The `callback` is executed when a request matching the `uri` and a
|
||||
`request_method` is received. The callback function will be passed a
|
||||
`WebRequest` object with details about the request. This function
|
||||
should be able of handling each registered `request_method`. The
|
||||
provided callback must be a coroutine.
|
||||
|
||||
The `protocol` is a list containing any combination of `http` and `websocket`.
|
||||
If `websocket` is selected associated JSON-RPC methods will be generated based
|
||||
on what is supplied by the `uri` and `request_methods` argument. A unique
|
||||
JSON_RPC method is generated for each request method. For example:
|
||||
```python
|
||||
self.server.register_endpoint("/server/example", ["POST"], self._handle_request)
|
||||
```
|
||||
would register a JSON-RPC method like:
|
||||
```
|
||||
server.example
|
||||
```
|
||||
|
||||
However, if multiple requests methods are supplied, the generated JSON-RPC
|
||||
methods will differ:
|
||||
```python
|
||||
self.server.register_endpoint("/server/example", ["GET", "POST", "DELETE"],
|
||||
self._handle_request)
|
||||
```
|
||||
would register:
|
||||
```
|
||||
server.get_example
|
||||
server.post_example
|
||||
server.delete_example
|
||||
```
|
||||
|
||||
The `wrap_result` argument applies only to the `http` protocol. In Moonraker
|
||||
all http requests return a result with a JSON body. By default, the value returned
|
||||
by a `callback` is wrapped in a dict:
|
||||
```python
|
||||
{"result": return_value}
|
||||
```
|
||||
It is only necessary to set this to false if you need to return a body that
|
||||
does not match this result. For example, the `[octoprint_compat]` component
|
||||
uses this functionality to return results in a format that match what
|
||||
Octoprint itself would return.
|
||||
|
||||
#### *Server.register_event_handler(event, callback)*
|
||||
|
||||
Registers the provided `callback` method to be executed when the
|
||||
provided `event` is sent. The callback may be a coroutine, however it
|
||||
is not required.
|
||||
|
||||
#### *Server.send_event(event, \*args)*
|
||||
|
||||
Emits the event named `event`, calling all callbacks registered to the
|
||||
event. All positional arguments in `*args` will be passed to each
|
||||
callback. Event names should be in the form of
|
||||
`"module_name:event_description"`.
|
||||
|
||||
#### *Server.register_notification(event_name, notify_name=None)*
|
||||
|
||||
Registers a websocket notification to be pushed when `event_name`
|
||||
is emitted. By default JSON-RPC notifcation sent will be in the form of
|
||||
`notify_{event_description}`. For example, when the server sends the
|
||||
`server:klippy_connected` event, the JSON_RPC notification will be
|
||||
`notify_klippy_connected`.
|
||||
|
||||
If a `notify_name` is provided it will override the `{event_description}`
|
||||
extracted from the `event_name`. For example, if the `notify_name="kconnect`
|
||||
were specfied when registering the `server:klippy_connected` event, the
|
||||
websocket would emit a `notify_kconnect` notification.
|
||||
|
||||
#### *Server.get_host_info()*
|
||||
|
||||
Returns a tuple of the current host name of the PC and the port Moonraker
|
||||
is serving on.
|
||||
|
||||
#### *Server.get_klippy_info()*
|
||||
|
||||
Returns a dict containing the values from the most recent `info` request to
|
||||
Klippy. If Klippy has never connected this will be an empty dict.
|
||||
|
||||
### The WebRequest Object
|
||||
|
||||
All callbacks registered with the
|
||||
[register_endpoint()](#serverregister_endpointuri-request_methods-callback-protocolhttp-websocket-wrap_resulttrue)
|
||||
method are passed a WebRequest object when they are executed. This object
|
||||
contains information about the request including its endpoint name and arguments
|
||||
parsed from the request.
|
||||
|
||||
#### *WebRequest.get_endpoint()*
|
||||
|
||||
Returns the URI registered with this request, ie: `/server/example`.
|
||||
|
||||
#### *WebRequest.get_action()*
|
||||
|
||||
Returns the request action, which is synonomous with its HTTP request
|
||||
method. Will be either `GET`, `POST`, or `DELETE`. This is useful
|
||||
if your endpoint was registered with multiple request methods and
|
||||
needs to handle each differently.
|
||||
|
||||
#### *WebRequest.get_connection()*
|
||||
|
||||
Returns the associated Websocket connection ID. This will be `None`
|
||||
for HTTP requests when no associated websocket is connected to
|
||||
the client.
|
||||
|
||||
#### *WebRequest.get_args()*
|
||||
|
||||
Returns a reference to the entire argument dictionary. Useful if
|
||||
one request handler needs to preprocess the arguments before
|
||||
passing the WebRequest on to another request handler.
|
||||
|
||||
#### *WebRequest.get(key, default=Sentinel)*
|
||||
|
||||
Returns the request argument at the provided `key`. If the key is not
|
||||
present `default` will be returned. If `default` is not provided a
|
||||
`SeverError` will be raised.
|
||||
|
||||
#### *WebRequest.get_str(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a string, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `SeverError` will be raised.
|
||||
|
||||
#### *WebRequest.get_int(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to an integer, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `SeverError` will be raised.
|
||||
|
||||
#### *WebRequest.get_float(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a float, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `SeverError` will be raised.
|
||||
|
||||
#### *WebRequest.get_boolean(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a boolean, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `SeverError` will be raised.
|
||||
+241
-52
@@ -1,24 +1,19 @@
|
||||
This document describes Moonraker's full configuration.
|
||||
#
|
||||
This document describes Moonraker's full configuration. As this file
|
||||
references configuration for both Klipper (`printer.cfg`) and Moonraker
|
||||
(`moonraker.conf`), each example contains a commment indicating which
|
||||
configuration file is being refrenenced. A basic
|
||||
[sample configuration](./moonraker.conf) in the `docs` directory.
|
||||
|
||||
# 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
|
||||
## `[server]`
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
```
|
||||
The `[server]` section provides essential configuration for Moonraker
|
||||
and its core components. This section is requrired.
|
||||
|
||||
## server
|
||||
```ini
|
||||
|
||||
# moonraker.conf
|
||||
|
||||
```
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
# The host address in which to bind the HTTP server. Default is to bind
|
||||
@@ -28,21 +23,40 @@ port: 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
|
||||
max_upload_size: 1024
|
||||
# The maximum size allowed for a file upload (in MiB). Default is 1024 MiB.
|
||||
enable_debug_logging: False
|
||||
# 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.
|
||||
# of development the default is False.
|
||||
config_path:
|
||||
# An optional path where configuration files are located. If specified,
|
||||
# Moonraker will serve this path allowing file and directory manipulation
|
||||
# within it. This path must be located within the user's HOME directory,
|
||||
# by may not be the home directory itself. The default is no path, which
|
||||
# results in no configuration files being served.
|
||||
# The path to a directory where configuration files are located. This
|
||||
# directory may contain Klipper config files (printer.cfg) or Moonraker
|
||||
# config files (moonraker.conf). Clients may also write their own config
|
||||
# files to this directory. Note that this may not be the system root
|
||||
# (ie: "/") and moonraker must have read and write access permissions
|
||||
# for this directory.
|
||||
database_path: ~/.moonraker_database
|
||||
# The path to the folder that stores Moonraker's lmdb database files.
|
||||
# It is NOT recommended to place this file in a location that is served by
|
||||
# Moonraker (such as the "config_path" or the location where gcode
|
||||
# files are stored). If the folder does not exist an attempt will be made
|
||||
# to create it. The default is ~/.moonraker_database.
|
||||
temperature_store_size: 1200
|
||||
# The maximum number of temperature values to store for each sensor. Note
|
||||
# that this value also applies to the "target", "power", and "fan_speed"
|
||||
# if the sensor reports them. The default is 1200, which is enough to
|
||||
# store approximately 20 minutes of data at one value per second.
|
||||
gcode_store_size: 1000
|
||||
# The maximum number "gcode lines" to store. The default is 1000.
|
||||
```
|
||||
## authorization
|
||||
## `[authorization]`
|
||||
|
||||
The `[authorization]` section provides configuration for Moonraker's
|
||||
authorization module. This section is required.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
```
|
||||
[authorization]
|
||||
enabled: True
|
||||
# Enables authorization. When set to true, requests must either contain
|
||||
@@ -65,19 +79,50 @@ 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.
|
||||
# to allow all domains, however this should be an option reserved for
|
||||
# client developers and not used in production. A * can also be used
|
||||
# to specify a wildcard that matches several domains. For example:
|
||||
# *.local
|
||||
# http://*.my-domain.com
|
||||
# *.my-domain.com:*
|
||||
# Are all valid entries. However, a wildcard may not be specified in
|
||||
# the top level domain:
|
||||
# http://my-printer.*
|
||||
# The above example will be rejected.
|
||||
# When CORS is enabled by adding an entry to this option, all origins
|
||||
# matching the "trusted_clients" option will have CORS headers set as
|
||||
# well. If this option is not specified then CORS is disabled.
|
||||
```
|
||||
|
||||
# Plugin Configuration
|
||||
The sections outlined here are optional and enable additional
|
||||
functionality in moonraker.
|
||||
## `[octoprint_compat]`
|
||||
Enables partial support of Octoprint API is implemented with the purpose of
|
||||
allowing uploading of sliced prints to a moonraker instance.
|
||||
Currently we support Slic3r derivatives and Cura with Cura-Octoprint.
|
||||
|
||||
## paneldue
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[octoprint_compat]
|
||||
```
|
||||
|
||||
## `[history]`
|
||||
Enables print history tracking.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[history]
|
||||
```
|
||||
|
||||
## `[paneldue]`
|
||||
Enables PanelDue display support. The PanelDue should be connected to the
|
||||
host machine, either via the machine's UART GPIOs or through a USB-TTL
|
||||
converter.
|
||||
converter. Currently PanelDue Firmware Version 1.24 is supported. Other
|
||||
releases may not behave correctly.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
```
|
||||
[paneldue]
|
||||
serial:
|
||||
# The serial port in which the PanelDue is connected. This parameter
|
||||
@@ -109,7 +154,9 @@ 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`:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
@@ -121,15 +168,33 @@ gcode:
|
||||
duration=DURATION|float)}
|
||||
```
|
||||
|
||||
## power
|
||||
## `[power]`
|
||||
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
|
||||
and Tasmota (via http) devices are supported.
|
||||
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[power device_name]
|
||||
type: gpio
|
||||
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
|
||||
# The type of device. Can be either gpio, tplink_smartplug, tasmota
|
||||
# or homeseer.
|
||||
# This parameter must be provided.
|
||||
off_when_shutdown: False
|
||||
# If set to True the device will be powered off when Klipper enters
|
||||
# the "shutdown" state. This option applies to all device types.
|
||||
# The default is False.
|
||||
locked_while_printing: False
|
||||
# If True, locks the device so that the power cannot be changed while the
|
||||
# printer is printing. This is useful to avert an accidental shutdown to
|
||||
# the printer's power. The default is False.
|
||||
restart_klipper_when_powered: False
|
||||
# If set to True, Moonraker will issue a "FIRMWARE_RESTART" to Klipper
|
||||
# after the device has been powered on. The default is False, thus no
|
||||
# attempt to made to restart Klipper after power on.
|
||||
restart_delay: 1.
|
||||
# If "restart_klipper_when_powered" is set, this option specifies the amount
|
||||
# of time (in seconds) to delay the restart. Default is 1 second.
|
||||
pin: gpiochip0/gpio26
|
||||
# The pin to use for GPIO devices. The chip is optional, if left out
|
||||
# then the module will default to gpiochip0. If one wishes to invert
|
||||
@@ -139,6 +204,10 @@ pin: gpiochip0/gpio26
|
||||
# !gpiochip0/gpio26
|
||||
# !gpio26
|
||||
# This parameter must be provided for "gpio" type devices
|
||||
initial_state: off
|
||||
# The initial state for GPIO type devices. May be on or
|
||||
# off. When moonraker starts the device will be set to this
|
||||
# state. Default is off.
|
||||
address:
|
||||
port:
|
||||
# The above options are used for "tplink_smartplug" devices. The
|
||||
@@ -156,17 +225,50 @@ output_id:
|
||||
# If your single-relay Tasmota device switches on/off successfully,
|
||||
# but fails to report its state, ensure that 'SetOption26' is set in
|
||||
# Tasmota.
|
||||
address:
|
||||
user:
|
||||
password:
|
||||
output_id:
|
||||
# The above options are used for "shelly" devices. The
|
||||
# address should be a valid ip or hostname for the Shelly device.
|
||||
# Provide a user and password if configured in Shelly (default is empty).
|
||||
# If password is set but user is empty the default user "admin" will be used
|
||||
# Provided an output_id (relay id) if the Shelly device supports
|
||||
# more than one (default is 0).
|
||||
address:
|
||||
device:
|
||||
user:
|
||||
password:
|
||||
# The above options are used for "homeseer" devices. The
|
||||
# address should be a valid ip or hostname for the homeseer controller.
|
||||
# "device" should be the ID of the device to control.
|
||||
# To find out the ID, in the HomeSeer UI, click on the device you want to
|
||||
# control (Make sure to click the sub-device that actually has On/Off
|
||||
# buttons). And then go to the "status/graphics" tab and it should list
|
||||
# "ID" in the "advanced information" section.
|
||||
# Provide a user and password with access to "device control"
|
||||
# and at least the specific device you want to control
|
||||
|
||||
```
|
||||
Below are some potential examples:
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[power printer]
|
||||
type: gpio
|
||||
pin: gpio26
|
||||
off_when_shutdown: True
|
||||
initial_state: off
|
||||
|
||||
[power printer_led]
|
||||
type: gpio
|
||||
pin: !gpiochip0/gpio16
|
||||
initial_state: off
|
||||
|
||||
[power light_strip]
|
||||
type: gpio
|
||||
pin: gpiochip0/gpio17
|
||||
initial_state: on
|
||||
|
||||
[power wifi_switch]
|
||||
type: tplink_smartplug
|
||||
@@ -176,11 +278,19 @@ address: 192.168.1.123
|
||||
type: tasmota
|
||||
address: 192.168.1.124
|
||||
password: password1
|
||||
|
||||
[power shelly_plug]
|
||||
type: shelly
|
||||
address: 192.168.1.125
|
||||
user: user2
|
||||
password: password2
|
||||
```
|
||||
|
||||
It is possible to toggle device power from the Klippy host, this can be done
|
||||
with a gcode_macro, such as:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro POWER_OFF_PRINTER]
|
||||
gcode:
|
||||
{action_call_remote_method("set_device_power",
|
||||
@@ -190,7 +300,9 @@ gcode:
|
||||
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:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[delayed_gcode delayed_printer_off]
|
||||
initial_duration: 0.
|
||||
gcode:
|
||||
@@ -205,21 +317,98 @@ gcode:
|
||||
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
|
||||
```
|
||||
|
||||
## update_manager
|
||||
## `[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.
|
||||
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager]
|
||||
client_repo:
|
||||
enable_repo_debug: False
|
||||
# When set to True moonraker will bypass repo validation and allow
|
||||
# updates from unofficial remotes and/or branches. Updates on
|
||||
# detached repos are also allowed. This option is intended for
|
||||
# developers and should not be used on production machines. The
|
||||
# default is False.
|
||||
enable_auto_refresh: False
|
||||
# When set to True Moonraker will attempt to fetch status about
|
||||
# available updates roughly every 24 hours, between 12am-4am.
|
||||
# When set to False Moonraker will only fetch update state on startup
|
||||
# and clients will need to request that Moonraker updates state. The
|
||||
# default is False.
|
||||
distro: debian
|
||||
# The disto in which moonraker has been installed. Currently the
|
||||
# update manager only supports "debian", which encompasses all of
|
||||
# its derivatives. The default is debain.
|
||||
```
|
||||
|
||||
### Client Configuration
|
||||
This allows client programs such as Fluidd, KlipperScreen, and Mainsail to be
|
||||
updated in addition to klipper, moonraker, and the system os. Repos that have
|
||||
been modified or cloned from unofficial sources are not supported.
|
||||
|
||||
There are two types of update manager clients and each will be detailed
|
||||
separately. The first one is targeted towards releases that do not need a
|
||||
service restart such as Fluidd/Mainsail.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager client client_name]
|
||||
type: web
|
||||
repo:
|
||||
# This is the GitHub repo of the client, in the format of user/client.
|
||||
# For example, this could be set to cadriel/fluidd to update Fluidd or
|
||||
# meteyou/mainsail to update Mainsail. 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
|
||||
|
||||
# meteyou/mainsail to update Mainsail. This parameter must be provided.
|
||||
path:
|
||||
# The path to the client's files on disk. This parameter must be provided.
|
||||
persistent_files:
|
||||
# A list of newline separated file names that should persist between
|
||||
# updates. This is useful for static configuration files, or perhaps
|
||||
# themes. The default is no persistent files.
|
||||
```
|
||||
|
||||
This second example is for git repositories that have a service that need
|
||||
updating.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
# service_name must be the name of the systemd service
|
||||
[update_manager client service_name]
|
||||
type: git_repo
|
||||
path:
|
||||
# The absolute path to the client's files on disk. This parameter must be provided.
|
||||
# Example:
|
||||
# path: ~/service_name
|
||||
origin:
|
||||
# The full GitHub URL of the "origin" remote for the repository. This can
|
||||
# be be viewed by navigating to your repository and running:
|
||||
# git remote -v
|
||||
# This parameter must be provided.
|
||||
primary_branch:
|
||||
# The name of the primary branch used for release code on this repo. This
|
||||
# option allows clients to specify 'main', or their own unique name, as
|
||||
# the branch used for repo validity checks. The default is master.
|
||||
env:
|
||||
# The path to the client's virtual environment executable on disk. For
|
||||
# example, Moonraker's venv is located at ~/moonraker-env/bin/python.
|
||||
# The default is no env, which disables updating python packages.
|
||||
requirements:
|
||||
# This is the location in the repository to the client's virtual environment
|
||||
# requirements file. This location is relative to the root of the repository.
|
||||
# This parameter must be provided if the "env" option is set, otherwise it
|
||||
# should be omitted.
|
||||
install_script:
|
||||
# The file location, relative to the repository, for the installation script.
|
||||
# The update manager parses this file for "system" packages that need updating.
|
||||
# The default is no install script, which disables system package updates
|
||||
enable_node_updates:
|
||||
# When set to True, Moonraker will asssume that this repo relies upon node
|
||||
# and will attempt to execute "npm ci --only=prod" when it detects a change
|
||||
# to package-lock.json. Note that if your project does not have a
|
||||
# package-lock.json in its root directory then the plugin will fail to load.
|
||||
# Default is False.
|
||||
```
|
||||
+54
-14
@@ -8,24 +8,64 @@ are near those of Klipper:
|
||||
|
||||
- All source files should begin with a copyright notice in the following
|
||||
format:
|
||||
```
|
||||
# Module name and brief description of module
|
||||
#
|
||||
# Copyright (C) 2020 YOUR NAME <YOUR EMAIL ADDRESS>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
```
|
||||
|
||||
# Module name and brief description of module
|
||||
#
|
||||
# Copyright (C) 2021 YOUR NAME <YOUR EMAIL ADDRESS>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
- No line in the source code or documentation should exceed 80 characters.
|
||||
Be sure there is no trailing whitespace.
|
||||
- Each Commit message should be in the following format:
|
||||
```
|
||||
module name: brief description of commit
|
||||
|
||||
More detailed explanation if necessary.
|
||||
module name: brief description of commit
|
||||
|
||||
More detailed explanation if necessary.
|
||||
|
||||
Signed-off-by: Your Name <your email address>
|
||||
|
||||
Signed-off-by: Your Name <your email address>
|
||||
```
|
||||
- By signing off on commits, you acknowledge that you agree to the
|
||||
[developer certificate of origin](developer-certificate-of-origin).
|
||||
As with Klipper, this must contain your real name and a current
|
||||
[developer certificate of origin](../developer-certificate-of-origin)
|
||||
shown below. Your signature must contain your real name and a current
|
||||
email address.
|
||||
|
||||
```text
|
||||
Developer Certificate of Origin
|
||||
Version 1.1
|
||||
|
||||
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
|
||||
1 Letterman Drive
|
||||
Suite D4700
|
||||
San Francisco, CA, 94129
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Developer's Certificate of Origin 1.1
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
(a) The contribution was created in whole or in part by me and I
|
||||
have the right to submit it under the open source license
|
||||
indicated in the file; or
|
||||
|
||||
(b) The contribution is based upon previous work that, to the best
|
||||
of my knowledge, is covered under an appropriate open source
|
||||
license and I have the right under that license to submit that
|
||||
work with modifications, whether created in whole or in part
|
||||
by me, under the same open source license (unless I am
|
||||
permitted to submit under a different license), as indicated
|
||||
in the file; or
|
||||
|
||||
(c) The contribution was provided directly to me by some other
|
||||
person who certified (a), (b) or (c) and I have not modified
|
||||
it.
|
||||
|
||||
(d) I understand and agree that this project and the contribution
|
||||
are public and that a record of the contribution (including all
|
||||
personal information I submit with it, including my sign-off) is
|
||||
maintained indefinitely and may be redistributed consistent with
|
||||
this project or the open source license(s) involved.
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
mkdocs==1.1.2
|
||||
@@ -0,0 +1,15 @@
|
||||
# Welcome to Moonraker Documentation
|
||||
|
||||
Users should refer to the [Installation](installation.md) and
|
||||
[Configuration](configuration.md) sections for documentation on how
|
||||
to install and configure Moonraker.
|
||||
|
||||
Client developers may refer to the [Client API](web_api.md)
|
||||
documentation.
|
||||
|
||||
Backend developers should refer to the
|
||||
[contibuting](contributing.md) section for basic contribution
|
||||
guidelines prior to creating a pull request. The
|
||||
[components](components.md) document provides a brief overview
|
||||
of how to create a component and interact with Moonraker's
|
||||
primary internal APIs.
|
||||
+119
-60
@@ -6,13 +6,39 @@ may work, however they may need a custom install script. Moonraker
|
||||
requires Python 3.7 or greater, verify that your distribution's
|
||||
Python 3 packages meet this requirement.
|
||||
|
||||
Klipper should be installed prior to installing Moonraker. Please see
|
||||
[Klipper's Documention](https://github.com/KevinOConnor/klipper/blob/master/docs/Installation.md)
|
||||
for instructions on how to do this.
|
||||
### Installing Klipper
|
||||
|
||||
After Klipper is installed, you need to modify its "default" file. This file
|
||||
contains klipper's command line arguments, and you must add an argument that
|
||||
instructs Klippy to create a Unix Domain socket:
|
||||
Klipper should be installed prior to installing Moonraker. Please see
|
||||
[Klipper's Documention](https://klipper3d.com/Overview.html) for details.
|
||||
After installing Klipper you should make sure to add Moonraker's
|
||||
[configuration requirements](#klipper-configuration-requirements).
|
||||
|
||||
### Klipper Configuration Requirements
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
|
||||
- `[virtual_sdcard]`
|
||||
- `[pause_resume]`
|
||||
- `[display_status]`
|
||||
|
||||
If you have a `[filament_switch_sensor]` configured then `[pause_resume]` will
|
||||
automatically be loaded. Likewise, if you have a `[display]` configured then
|
||||
`[display_status]` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to `printer.cfg`:
|
||||
```ini
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
```
|
||||
|
||||
### Enabling the Unix Socket
|
||||
|
||||
After Klipper is installed it may be necessary to modify its `defaults` file in
|
||||
order to enable the Unix Domain Socket. Begin by opening the file in your
|
||||
editor of choice, for example:
|
||||
```
|
||||
sudo nano /etc/default/klipper
|
||||
```
|
||||
@@ -27,7 +53,7 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
|
||||
```
|
||||
|
||||
You need to add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
Add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
@@ -37,51 +63,91 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
|
||||
```
|
||||
You may also want to take this opportunity to change the location of
|
||||
printer.cfg if you enable Moonraker's "config_path" option (see the
|
||||
[configuration section](#moonraker-configuration-moonrakerconf) for more information).
|
||||
|
||||
You can now install the Moonraker application:
|
||||
!!! note
|
||||
Your installation of Klipper may use systemd instead of
|
||||
the default LSB script. In this case, you need to modify the
|
||||
klipper.service file.
|
||||
|
||||
You may also want to take this opportunity to change the location of
|
||||
printer.cfg to match Moonraker's `config_path` option (see the
|
||||
[configuration document](configuration.md#primary-configuration)
|
||||
for more information on the config_path). For example, if the `config_path`
|
||||
is set to `~/printer_config`, your klipper defaults file might look
|
||||
like the following:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
|
||||
```
|
||||
|
||||
If necessary, create the config directory and move printer.cfg to it:
|
||||
```
|
||||
cd ~
|
||||
mkdir printer_config
|
||||
mv printer.cfg printer_config
|
||||
```
|
||||
|
||||
### Installing Moonraker
|
||||
|
||||
Begin by cloning the git respository:
|
||||
|
||||
```
|
||||
cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
Finally, run moonraker's install script:
|
||||
Now is a good time to create [moonraker.conf](configuration.md). If you are
|
||||
using the `config_path`, create it in the specified directory otherwise create
|
||||
it in the HOME directory. The [sample moonraker.conf](./moonraker.conf) in
|
||||
the `docs` directory may be used as a starting point.
|
||||
|
||||
For a default installation run the following commands:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
Or to install with `moonraker.conf` in the `config_path`:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
|
||||
```
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
- -r\
|
||||
This will rebuild the virtual environment for existing installations.
|
||||
|
||||
- `-r`:
|
||||
Rebuilds 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".
|
||||
- `-f`:
|
||||
Force an overwrite of Moonraker's systemd script. By default the
|
||||
the systemd script will not be modified if it exists.
|
||||
- `-c /home/pi/moonraker.conf`:
|
||||
Specifies the path to Moonraker's config file. The default location
|
||||
is `/home/<user>/moonraker.conf`. When using this option to modify
|
||||
an existing installation it is necessary to add `-f` as well.
|
||||
|
||||
When the script completes it should start both Moonraker and Klipper. In
|
||||
`klippy.log` you should find the following entry:\
|
||||
`webhooks: New connection established`
|
||||
`/tmp/klippy.log` you should find the following entry:
|
||||
|
||||
Now you may install a client, such as [Mainsail](
|
||||
https://github.com/meteyou/mainsail).
|
||||
- Note that as of the time of this writing (August 11 2020) the current version
|
||||
of Mainsail (0.1.2) is not compatible with this repo. Please give the
|
||||
developer some time to bring up Mainsail in line with the latest release
|
||||
of Moonraker.
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
|
||||
|
||||
## Command line Usage
|
||||
The configuration and log file paths may be specified via the command
|
||||
line.
|
||||
Now you may install a client, such as
|
||||
[Mainsail](https://github.com/meteyou/mainsail) or
|
||||
[Fluidd](https://github.com/cadriel/fluidd)
|
||||
|
||||
### Command line usage
|
||||
|
||||
This section is intended for users that need to write their own
|
||||
installation script. Detailed are the command line arguments
|
||||
available to Moonraker:
|
||||
```
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>]
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
@@ -91,39 +157,32 @@ optional arguments:
|
||||
Location of moonraker configuration file
|
||||
-l <logfile>, --logfile <logfile>
|
||||
log file name and location
|
||||
-n, --nologfile disable logging to a file
|
||||
```
|
||||
|
||||
The default configuration is:
|
||||
- config file - `~/moonraker.conf`
|
||||
- log file - `/tmp/moonraker.log`
|
||||
- config file path- `~/moonraker.conf`
|
||||
- log file path - `/tmp/moonraker.log`
|
||||
- logging to a file is enabled
|
||||
|
||||
It is recommended to use the defaults, however one may change these
|
||||
arguments by editing `/etc/default/moonraker`.
|
||||
|
||||
## Prerequisites (Klipper Configuration)
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
- [virtual_sdcard]
|
||||
- [pause_resume]
|
||||
- [display_status]
|
||||
|
||||
If you have a `filament_switch_sensor` configured then `pause_resume` will
|
||||
automatically be loaded. Likewise, if you have a `display` configured then
|
||||
`display_status` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to printer.cfg:
|
||||
If one needs to start moonraker without generating a log file, the
|
||||
`-n` option may be used, for example:
|
||||
```
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
|
||||
```
|
||||
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.
|
||||
In general it is not recommended to install moonraker with this option.
|
||||
While moonraker will still log to stdout, all requests for support must
|
||||
be accompanied by moonraker.log.
|
||||
|
||||
These options may be changed by editing
|
||||
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
|
||||
may also be used to modify the config file location.
|
||||
|
||||
### Additional Notes
|
||||
|
||||
- Make sure that Moonraker and Klipper both have read and write access to the
|
||||
directory set in the `path` option for the `[virtual_sdcard]` in
|
||||
`printer.cfg`.
|
||||
- Upon first starting Moonraker is not aware of the gcode file path, thus
|
||||
it cannot serve gcode files, add directories, etc. After Klippy enters
|
||||
the "ready" state it sends Moonraker the gcode file path.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Sample Moonraker Configuration File
|
||||
|
||||
[server]
|
||||
# Bind server defaults of 0.0.0.0, port 7125
|
||||
enable_debug_logging: True
|
||||
config_path: ~/printer_config
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
# Enter your client IP here or range here
|
||||
192.168.1.0/24
|
||||
cors_domains:
|
||||
# Allow CORS requests for Fluidd
|
||||
http://app.fluidd.xyz
|
||||
|
||||
# Enable Octoprint compatibility for Slicer uploads
|
||||
# Supports Cura, Slic3r, and Slic3r dervivatives
|
||||
# (PrusaSlicer, SuperSlicer)
|
||||
[octoprint_compat]
|
||||
@@ -1,3 +0,0 @@
|
||||
## Plugins
|
||||
|
||||
Documentation Forthcoming
|
||||
+135
-99
@@ -1,3 +1,4 @@
|
||||
#
|
||||
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)
|
||||
@@ -17,31 +18,32 @@ that reports state which can be queried.
|
||||
## webhooks
|
||||
```json
|
||||
{
|
||||
state: "startup",
|
||||
state_message: "message"
|
||||
"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`
|
||||
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]
|
||||
"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".
|
||||
@@ -59,24 +61,26 @@ The `gcode_move` object reports the current gcode state:
|
||||
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.
|
||||
!!! Note
|
||||
The printer's actual movement will 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
|
||||
"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
|
||||
@@ -95,23 +99,29 @@ The `toolhead` object reports state of the current tool:
|
||||
- `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`.
|
||||
!!! tip
|
||||
`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
|
||||
"config": {},
|
||||
"settings": {},
|
||||
"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
|
||||
configured options. Values will ALWAYS be reported as
|
||||
strings. Note that default values are not reported, only options
|
||||
configured in printer.cfg are present.
|
||||
- `settings`: Similar to `config`, however this object includes default
|
||||
values that may not have been included in `printer.cfg`. It is possible
|
||||
for a value to be a string, integer, boolean, or float.
|
||||
- `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
|
||||
@@ -119,75 +129,91 @@ The `configfile` object reports printer configuration state:
|
||||
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.
|
||||
*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
|
||||
"temperature": 0.0,
|
||||
"target": 0.0,
|
||||
"power": 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).
|
||||
- `power`: The current pwm value applied to the heater. This value is
|
||||
expressed as a percentage from 0.0 to 1.0.
|
||||
- `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*
|
||||
*Enabled when `[heater_bed]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
"temperature": 0.0,
|
||||
"target": 0.0,
|
||||
"power": 0.0,
|
||||
}
|
||||
```
|
||||
The `heater_bed` object reports state of the heated bed:
|
||||
|
||||
- `temperature`: The bed's current temperature
|
||||
- `target`: The bed's target temperature
|
||||
- `power`: The current pwm value applied to the heater. This value is
|
||||
expressed as a percentage from 0.0 to 1.0.
|
||||
|
||||
## fan
|
||||
*Enabled when [fan] is included in printer.cfg*
|
||||
*Enabled when `[fan]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
speed: 0.0
|
||||
"speed": 0.0,
|
||||
"rpm": 4000
|
||||
}
|
||||
```
|
||||
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.
|
||||
- `rpm`: The fan's revolutions per minute if the tachometer
|
||||
pin has been configured. Will report `null` if no tach
|
||||
has been configured.
|
||||
|
||||
## idle_timeout
|
||||
```json
|
||||
{
|
||||
state: "Idle",
|
||||
printing_time: 0.0
|
||||
"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
|
||||
|
||||
- `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".
|
||||
`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*
|
||||
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
progress: 0.0,
|
||||
is_active: false,
|
||||
file_position: 0
|
||||
"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
|
||||
@@ -196,23 +222,25 @@ The `virtual_sdcard` object reports the state of the virtual sdcard:
|
||||
- `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.
|
||||
!!! 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*
|
||||
*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: ""
|
||||
"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:
|
||||
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
|
||||
@@ -228,52 +256,56 @@ The `print_stats` object reports "virtual_sdcard" print state:
|
||||
- `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.
|
||||
!!! 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*
|
||||
*Enabled when `[display]` or `[display_status]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
message: "",
|
||||
progress: 0.0
|
||||
"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
|
||||
will fallback to the eqivalent of `virtual_sdcard.progress`. 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.*
|
||||
*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
|
||||
"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.*
|
||||
*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
|
||||
"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
|
||||
@@ -281,48 +313,51 @@ A `temperature_fan` reports the following state:
|
||||
- `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.*
|
||||
*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
|
||||
"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.*
|
||||
*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
|
||||
"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.*
|
||||
*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: [[]]
|
||||
"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.
|
||||
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
|
||||
@@ -330,15 +365,16 @@ The `bed_mesh` printer object reports the following state:
|
||||
- `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.
|
||||
!!! tip
|
||||
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.*
|
||||
*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".
|
||||
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.
|
||||
take action based on the variables reported by the macro.
|
||||
+51
-12
@@ -1,6 +1,45 @@
|
||||
##
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
|
||||
### March 10th 2021
|
||||
- The `cors_domain` option in the `[authoriztion]` section is now
|
||||
checked for dangerous entries. If a domain entry contains a
|
||||
wildcard in the top level domain (ie: `http://www.*`) then it
|
||||
will be rejected, as malicious website can easily reproduce
|
||||
this match.
|
||||
|
||||
### March 6th 2021
|
||||
- The `enable_debug_logging` in the `[server]` section now defaults
|
||||
to `False`. This dramatically reduces the amount of logging produced
|
||||
by Moonraker for the typical user.
|
||||
|
||||
### March 4th 2021
|
||||
- To enable Octoprint compatibility with slicer uploads it is now
|
||||
required to add `[octoprint_compat]` to `moonraker.conf`. After
|
||||
making this change it is necessary to restart the Moonraker service
|
||||
so the module is loaded.
|
||||
|
||||
### December 31st 2020
|
||||
- The file manager no longer restricts the `config_path` to a folder
|
||||
within the HOME directory. The path may not be the system root,
|
||||
however it can reside anywhere else on the file system as long as
|
||||
Moonraker has read and write access to the directory. This applies
|
||||
to gcode path received from Klipper via the `virtual_sdcard` section
|
||||
as well.
|
||||
|
||||
### December 6th 2020
|
||||
- Moonraker is now installed as a systemd service. This allows logging
|
||||
to stdout which can be viewed with the `journalctl -u moonraker` command.
|
||||
This changes requires the user to rerun the install script. If
|
||||
`moonraker.conf` is not located in the home directory, the command
|
||||
will looks something like the following:
|
||||
|
||||
cd ~/moonraker
|
||||
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
|
||||
|
||||
Otherwise you can run the install script with no arguments.
|
||||
|
||||
### November 19th 2020
|
||||
- The install script (`install-moonraker.sh`) now has command-line
|
||||
options:\
|
||||
@@ -11,24 +50,24 @@ such as a configuration change or a reinstallation.
|
||||
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
|
||||
```
|
||||
|
||||
~/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
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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.
|
||||
+2514
-998
File diff suppressed because it is too large.
Load diff
+21
@@ -0,0 +1,21 @@
|
||||
site_name: Moonraker
|
||||
repo_url: https://github.com/Arksine/moonraker
|
||||
nav:
|
||||
- 'User Documentation':
|
||||
- Installation: installation.md
|
||||
- Configuration : configuration.md
|
||||
- User Changes: user_changes.md
|
||||
- 'Client Developers':
|
||||
- Client API: web_api.md
|
||||
- Printer Objects: printer_objects.md
|
||||
- API Changes: api_changes.md
|
||||
- 'Backend Developers':
|
||||
- Contributing: contributing.md
|
||||
- Components: components.md
|
||||
theme:
|
||||
name: readthedocs
|
||||
plugins:
|
||||
- search
|
||||
markdown_extensions:
|
||||
- codehilite
|
||||
- admonition
|
||||
+206
-120
@@ -7,14 +7,18 @@
|
||||
import os
|
||||
import mimetypes
|
||||
import logging
|
||||
import json
|
||||
import tornado
|
||||
from inspect import isclass
|
||||
from tornado.escape import url_unescape
|
||||
from tornado.routing import Rule, PathMatches, AnyMatches
|
||||
from tornado.log import access_log
|
||||
from utils import ServerError
|
||||
from websockets import WebRequest, WebsocketManager, WebSocket
|
||||
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
|
||||
from authorization import Authorization
|
||||
from streaming_form_data import StreamingFormDataParser
|
||||
from streaming_form_data.targets import FileTarget, ValueTarget
|
||||
|
||||
# These endpoints are reserved for klippy/server communication only and are
|
||||
# not exposed via http or the websocket
|
||||
@@ -23,34 +27,10 @@ RESERVED_ENDPOINTS = [
|
||||
"register_remote_method"
|
||||
]
|
||||
|
||||
# 50 MiB Max Standard Body Size
|
||||
MAX_BODY_SIZE = 50 * 1024 * 1024
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
|
||||
# Status objects require special parsing
|
||||
def _status_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
val = request_handler.get_argument(key)
|
||||
if not val:
|
||||
args[key] = None
|
||||
else:
|
||||
args[key] = val.split(',')
|
||||
logging.debug(f"Parsed Arguments: {args}")
|
||||
return {'objects': args}
|
||||
|
||||
# Built-in Query String Parser
|
||||
def _default_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
args[key] = request_handler.get_argument(key)
|
||||
return args
|
||||
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
|
||||
|
||||
class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
def __init__(self, application):
|
||||
@@ -86,14 +66,14 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
|
||||
class APIDefinition:
|
||||
def __init__(self, endpoint, http_uri, ws_methods,
|
||||
request_methods, parser):
|
||||
request_methods, need_object_parser):
|
||||
self.endpoint = endpoint
|
||||
self.uri = http_uri
|
||||
self.ws_methods = ws_methods
|
||||
if not isinstance(request_methods, list):
|
||||
request_methods = [request_methods]
|
||||
self.request_methods = request_methods
|
||||
self.parser = parser
|
||||
self.need_object_parser = need_object_parser
|
||||
|
||||
class MoonrakerApp:
|
||||
def __init__(self, config):
|
||||
@@ -101,7 +81,7 @@ 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 = config.getint('max_upload_size', 1024)
|
||||
self.max_upload_size *= 1024 * 1024
|
||||
|
||||
# Set Up Websocket and Authorization Managers
|
||||
@@ -111,33 +91,57 @@ 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)
|
||||
debug = config.getboolean('enable_debug_logging', False)
|
||||
log_level = logging.DEBUG if debug else logging.INFO
|
||||
logging.getLogger().setLevel(log_level)
|
||||
app_args = {
|
||||
'serve_traceback': debug,
|
||||
'websocket_ping_interval': 10,
|
||||
'websocket_ping_timeout': 30,
|
||||
'parent': self,
|
||||
'default_handler_class': AuthorizedErrorHandler,
|
||||
'default_handler_args': {}
|
||||
}
|
||||
if not debug:
|
||||
app_args['log_function'] = self.log_release_mode
|
||||
|
||||
# Set up HTTP only requests
|
||||
self.mutable_router = MutableRouter(self)
|
||||
app_handlers = [
|
||||
(AnyMatches(), self.mutable_router),
|
||||
(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,
|
||||
parent=self)
|
||||
(r"/websocket", WebSocket)]
|
||||
self.app = tornado.web.Application(app_handlers, **app_args)
|
||||
self.get_handler_delegate = self.app.get_handler_delegate
|
||||
|
||||
# Register handlers
|
||||
logfile = config['system_args'].get('logfile')
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
if logfile:
|
||||
self.register_static_file_handler(
|
||||
"moonraker.log", logfile, force=True)
|
||||
self.register_static_file_handler(
|
||||
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
|
||||
self.auth.register_handlers(self)
|
||||
|
||||
def listen(self, host, port):
|
||||
self.tornado_server = self.app.listen(
|
||||
port, address=host, max_body_size=self.max_upload_size,
|
||||
port, address=host, max_body_size=MAX_BODY_SIZE,
|
||||
xheaders=True)
|
||||
|
||||
def log_release_mode(self, handler):
|
||||
status_code = handler.get_status()
|
||||
if status_code in [200, 204]:
|
||||
# don't log OK and No Content
|
||||
return
|
||||
if status_code < 400:
|
||||
log_method = access_log.info
|
||||
elif status_code < 500:
|
||||
log_method = access_log.warning
|
||||
else:
|
||||
log_method = access_log.error
|
||||
request_time = 1000.0 * handler.request.request_time()
|
||||
log_method("%d %s %.2fms", status_code,
|
||||
handler._request_summary(), request_time)
|
||||
|
||||
def get_server(self):
|
||||
return self.server
|
||||
|
||||
@@ -167,14 +171,16 @@ class MoonrakerApp:
|
||||
f"Websocket: {', '.join(api_def.ws_methods)}")
|
||||
self.wsm.register_remote_handler(api_def)
|
||||
params = {}
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['remote_callback'] = api_def.endpoint
|
||||
params['methods'] = api_def.request_methods
|
||||
params['callback'] = api_def.endpoint
|
||||
params['need_object_parser'] = api_def.need_object_parser
|
||||
self.mutable_router.add_handler(
|
||||
api_def.uri, RemoteRequestHandler, params)
|
||||
api_def.uri, DynamicRequestHandler, params)
|
||||
self.registered_base_handlers.append(api_def.uri)
|
||||
|
||||
def register_local_handler(self, uri, request_methods,
|
||||
callback, protocol=["http", "websocket"]):
|
||||
callback, protocol=["http", "websocket"],
|
||||
wrap_result=True):
|
||||
if uri in self.registered_base_handlers:
|
||||
return
|
||||
api_def = self._create_api_definition(
|
||||
@@ -184,19 +190,20 @@ class MoonrakerApp:
|
||||
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)
|
||||
params['wrap_result'] = wrap_result
|
||||
params['is_remote'] = False
|
||||
self.mutable_router.add_handler(uri, DynamicRequestHandler, 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):
|
||||
def register_static_file_handler(self, pattern, file_path, force=False):
|
||||
if pattern[0] != "/":
|
||||
pattern = "/server/files/" + pattern
|
||||
if os.path.isfile(file_path):
|
||||
if os.path.isfile(file_path) or force:
|
||||
pattern += '()'
|
||||
elif os.path.isdir(file_path):
|
||||
if pattern[-1] != "/":
|
||||
@@ -210,7 +217,9 @@ class MoonrakerApp:
|
||||
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
|
||||
|
||||
def register_upload_handler(self, pattern):
|
||||
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
|
||||
self.mutable_router.add_handler(
|
||||
pattern, FileUploadHandler,
|
||||
{'max_upload_size': self.max_upload_size})
|
||||
|
||||
def remove_handler(self, endpoint):
|
||||
api_def = self.api_cache.get(endpoint)
|
||||
@@ -247,76 +256,117 @@ class MoonrakerApp:
|
||||
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
|
||||
|
||||
need_object_parser = endpoint.startswith("objects/")
|
||||
api_def = APIDefinition(endpoint, uri, ws_methods,
|
||||
request_methods, parser)
|
||||
request_methods, need_object_parser)
|
||||
self.api_cache[endpoint] = api_def
|
||||
return api_def
|
||||
|
||||
# ***** Dynamic Handlers*****
|
||||
class RemoteRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, remote_callback, arg_parser):
|
||||
super(RemoteRequestHandler, self).initialize()
|
||||
self.remote_callback = remote_callback
|
||||
self.query_parser = arg_parser
|
||||
|
||||
async def get(self):
|
||||
await self._process_http_request()
|
||||
|
||||
async def post(self):
|
||||
await self._process_http_request()
|
||||
|
||||
async def _process_http_request(self):
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.server.make_request(
|
||||
WebRequest(self.remote_callback, args, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, callback, methods, arg_parser):
|
||||
super(LocalRequestHandler, self).initialize()
|
||||
class DynamicRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, callback, methods, need_object_parser=False,
|
||||
is_remote=True, wrap_result=True):
|
||||
super(DynamicRequestHandler, self).initialize()
|
||||
self.callback = callback
|
||||
self.methods = methods
|
||||
self.query_parser = arg_parser
|
||||
self.wrap_result = wrap_result
|
||||
self._do_request = self._do_remote_request if is_remote \
|
||||
else self._do_local_request
|
||||
self._parse_query = self._object_parser if need_object_parser \
|
||||
else self._default_parser
|
||||
|
||||
async def get(self):
|
||||
if 'GET' in self.methods:
|
||||
await self._process_http_request('GET')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def post(self):
|
||||
if 'POST' in self.methods:
|
||||
await self._process_http_request('POST')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def delete(self):
|
||||
if 'DELETE' in self.methods:
|
||||
await self._process_http_request('DELETE')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def _process_http_request(self, method):
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
# Converts query string values with type hints
|
||||
def _convert_type(self, value, hint):
|
||||
type_funcs = {
|
||||
"int": int, "float": float,
|
||||
"bool": lambda x: x.lower() == "true",
|
||||
"json": json.loads}
|
||||
if hint not in type_funcs:
|
||||
logging.info(f"No conversion method for type hint {hint}")
|
||||
return value
|
||||
func = type_funcs[hint]
|
||||
try:
|
||||
result = await self.callback(
|
||||
WebRequest(self.request.path, args, method, conn=conn))
|
||||
converted = func(value)
|
||||
except Exception:
|
||||
logging.exception("Argument conversion error: Hint: "
|
||||
f"{hint}, Arg: {value}")
|
||||
return value
|
||||
return converted
|
||||
|
||||
def _default_parser(self):
|
||||
args = {}
|
||||
for key in self.request.arguments.keys():
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
key_parts = key.rsplit(":", 1)
|
||||
val = self.get_argument(key)
|
||||
if len(key_parts) == 1:
|
||||
args[key] = val
|
||||
else:
|
||||
args[key_parts[0]] = self._convert_type(val, key_parts[1])
|
||||
return args
|
||||
|
||||
def _object_parser(self):
|
||||
args = {}
|
||||
for key in self.request.arguments.keys():
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
val = self.get_argument(key)
|
||||
if not val:
|
||||
args[key] = None
|
||||
else:
|
||||
args[key] = val.split(',')
|
||||
logging.debug(f"Parsed Arguments: {args}")
|
||||
return {'objects': args}
|
||||
|
||||
def parse_args(self):
|
||||
try:
|
||||
args = self._parse_query()
|
||||
except Exception:
|
||||
raise ServerError(
|
||||
"Error Parsing Request Arguments. "
|
||||
"Is the Content-Type correct?")
|
||||
content_type = self.request.headers.get('Content-Type', "").strip()
|
||||
if content_type.startswith("application/json"):
|
||||
try:
|
||||
args.update(json.loads(self.request.body))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
for key, value in self.path_kwargs.items():
|
||||
if value is not None:
|
||||
args[key] = value
|
||||
return args
|
||||
|
||||
async def get(self, *args, **kwargs):
|
||||
await self._process_http_request()
|
||||
|
||||
async def post(self, *args, **kwargs):
|
||||
await self._process_http_request()
|
||||
|
||||
async def delete(self, *args, **kwargs):
|
||||
await self._process_http_request()
|
||||
|
||||
async def _do_local_request(self, args, conn):
|
||||
return await self.callback(
|
||||
WebRequest(self.request.path, args, self.request.method,
|
||||
conn=conn))
|
||||
|
||||
async def _do_remote_request(self, args, conn):
|
||||
return await self.server.make_request(
|
||||
WebRequest(self.callback, args, conn=conn))
|
||||
|
||||
async def _process_http_request(self):
|
||||
if self.request.method not in self.methods:
|
||||
raise tornado.web.HTTPError(405)
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.parse_args()
|
||||
try:
|
||||
result = await self._do_request(args, conn)
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
if self.wrap_result:
|
||||
result = {'result': result}
|
||||
self.finish(result)
|
||||
|
||||
class FileRequestHandler(AuthorizedFileHandler):
|
||||
def set_extra_headers(self, path):
|
||||
@@ -329,8 +379,8 @@ class FileRequestHandler(AuthorizedFileHandler):
|
||||
|
||||
async def delete(self, path):
|
||||
path = self.request.path.lstrip("/").split("/", 2)[-1]
|
||||
path = url_unescape(path)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
path = url_unescape(path, plus=False)
|
||||
file_manager = self.server.lookup_component('file_manager')
|
||||
try:
|
||||
filename = await file_manager.delete_file(path)
|
||||
except self.server.error as e:
|
||||
@@ -341,20 +391,56 @@ class FileRequestHandler(AuthorizedFileHandler):
|
||||
raise tornado.web.HTTPError(e.status_code, str(e))
|
||||
self.finish({'result': filename})
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class FileUploadHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, max_upload_size):
|
||||
super(FileUploadHandler, self).initialize()
|
||||
self.file_manager = self.server.lookup_component('file_manager')
|
||||
self.max_upload_size = max_upload_size
|
||||
|
||||
def prepare(self):
|
||||
if self.request.method == "POST":
|
||||
self.request.connection.set_max_body_size(self.max_upload_size)
|
||||
tmpname = self.file_manager.gen_temp_upload_path()
|
||||
self._targets = {
|
||||
'root': ValueTarget(),
|
||||
'print': ValueTarget(),
|
||||
'path': ValueTarget(),
|
||||
}
|
||||
self._file = FileTarget(tmpname)
|
||||
self._parser = StreamingFormDataParser(self.request.headers)
|
||||
self._parser.register('file', self._file)
|
||||
for name, target in self._targets.items():
|
||||
self._parser.register(name, target)
|
||||
|
||||
def data_received(self, chunk):
|
||||
if self.request.method == "POST":
|
||||
self._parser.data_received(chunk)
|
||||
|
||||
async def post(self):
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
form_args = {}
|
||||
for name, target in self._targets.items():
|
||||
if target.value:
|
||||
form_args[name] = target.value.decode()
|
||||
form_args['filename'] = self._file.multipart_filename
|
||||
form_args['tmp_file_path'] = self._file.filename
|
||||
debug_msg = "\nFile Upload Arguments:"
|
||||
for name, value in form_args.items():
|
||||
debug_msg += f"\n{name}: {value}"
|
||||
logging.debug(debug_msg)
|
||||
try:
|
||||
result = await file_manager.process_file_upload(self.request)
|
||||
result = await self.file_manager.finalize_upload(form_args)
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e))
|
||||
self.finish(result)
|
||||
|
||||
# Default Handler for unregistered endpoints
|
||||
class AuthorizedErrorHandler(AuthorizedRequestHandler):
|
||||
def prepare(self):
|
||||
super(AuthorizedRequestHandler, self).prepare()
|
||||
self.set_status(404)
|
||||
raise tornado.web.HTTPError(404)
|
||||
|
||||
class EmulateOctoprintHandler(AuthorizedRequestHandler):
|
||||
def get(self):
|
||||
self.finish({
|
||||
'server': "1.1.1",
|
||||
'api': "0.1",
|
||||
'text': "OctoPrint Upload Emulator"})
|
||||
def check_xsrf_cookie(self):
|
||||
pass
|
||||
@@ -28,9 +28,17 @@ class Authorization:
|
||||
self.access_tokens = {}
|
||||
|
||||
# Get allowed cors domains
|
||||
self.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()]
|
||||
cds = [d.strip() for d in cors_cfg.split('\n')if d.strip()]
|
||||
for domain in cds:
|
||||
bad_match = re.search(r"^.+\.[^:]*\*", domain)
|
||||
if bad_match is not None:
|
||||
raise config.error(
|
||||
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
|
||||
" permitted in the top level domain.")
|
||||
self.cors_domains.append(
|
||||
domain.replace(".", "\\.").replace("*", ".*"))
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips = []
|
||||
@@ -185,7 +193,7 @@ class Authorization:
|
||||
return False
|
||||
|
||||
def check_cors(self, origin, request=None):
|
||||
if origin is None:
|
||||
if origin is None or not self.cors_domains:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
@@ -198,6 +206,21 @@ class Authorization:
|
||||
else:
|
||||
logging.debug(f"Partial Cors Match: {match.group()}")
|
||||
else:
|
||||
# Check to see if the origin contains an IP that matches a
|
||||
# current trusted connection
|
||||
match = re.search(r"^https?://([^/:]+)", origin)
|
||||
if match is not None:
|
||||
ip = match.group(1)
|
||||
try:
|
||||
ipaddr = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if self._check_authorized_ip(ipaddr):
|
||||
logging.debug(
|
||||
f"Cors request matched trusted IP: {ip}")
|
||||
self._set_cors_headers(origin, request)
|
||||
return True
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
# Package definition for the plugins directory
|
||||
# Package definition for the components directory
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
@@ -9,17 +9,16 @@ from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
TEMPERATURE_UPDATE_MS = 1000
|
||||
TEMPERATURE_STORE_SIZE = 20 * 60
|
||||
|
||||
MAX_GCODE_LINES = 1000
|
||||
|
||||
class DataStore:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.temp_store_size = config.getint('temperature_store_size', 1200)
|
||||
self.gcode_store_size = config.getint('gcode_store_size', 1000)
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps = {}
|
||||
self.gcode_queue = deque(maxlen=MAX_GCODE_LINES)
|
||||
self.gcode_queue = deque(maxlen=self.gcode_store_size)
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
@@ -41,7 +40,7 @@ class DataStore:
|
||||
self._handle_gcode_store_request)
|
||||
|
||||
async def _init_sensors(self):
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
# Fetch sensors
|
||||
try:
|
||||
result = await klippy_apis.query_objects({'heaters': None})
|
||||
@@ -61,14 +60,18 @@ class DataStore:
|
||||
logging.info(f"Configuring available sensors: {sensors}")
|
||||
new_store = {}
|
||||
for sensor in sensors:
|
||||
fields = list(status.get(sensor, {}).keys())
|
||||
if sensor in self.temperature_store:
|
||||
new_store[sensor] = self.temperature_store[sensor]
|
||||
else:
|
||||
new_store[sensor] = {
|
||||
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
|
||||
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
|
||||
'temperatures': deque(maxlen=self.temp_store_size)}
|
||||
for item in ["target", "power", "speed"]:
|
||||
if item in fields:
|
||||
new_store[sensor][f"{item}s"] = deque(
|
||||
maxlen=self.temp_store_size)
|
||||
if sensor not in self.last_temps:
|
||||
self.last_temps[sensor] = (0., 0.)
|
||||
self.last_temps[sensor] = (0., 0., 0., 0.)
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
@@ -86,17 +89,21 @@ class DataStore:
|
||||
def _set_current_temps(self, data):
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
last_temp, last_target = self.last_temps[sensor]
|
||||
last_val = self.last_temps[sensor]
|
||||
self.last_temps[sensor] = (
|
||||
round(data[sensor].get('temperature', last_temp), 2),
|
||||
data[sensor].get('target', last_target))
|
||||
round(data[sensor].get('temperature', last_val[0]), 2),
|
||||
data[sensor].get('target', last_val[1]),
|
||||
data[sensor].get('power', last_val[2]),
|
||||
data[sensor].get('speed', last_val[3]))
|
||||
|
||||
def _update_temperature_store(self):
|
||||
# XXX - If klippy is not connected, set values to zero
|
||||
# as they are unknown?
|
||||
for sensor, (temp, target) in self.last_temps.items():
|
||||
self.temperature_store[sensor]['temperatures'].append(temp)
|
||||
self.temperature_store[sensor]['targets'].append(target)
|
||||
for sensor, vals in self.last_temps.items():
|
||||
self.temperature_store[sensor]['temperatures'].append(vals[0])
|
||||
for val, item in zip(vals[1:], ["targets", "powers", "speeds"]):
|
||||
if item in self.temperature_store[sensor]:
|
||||
self.temperature_store[sensor][item].append(val)
|
||||
|
||||
async def _handle_temp_store_request(self, web_request):
|
||||
store = {}
|
||||
@@ -109,15 +116,25 @@ class DataStore:
|
||||
|
||||
def _update_gcode_store(self, response):
|
||||
curtime = time.time()
|
||||
self.gcode_queue.append({'message': response, 'time': curtime})
|
||||
self.gcode_queue.append(
|
||||
{'message': response, 'time': curtime, 'type': "response"})
|
||||
|
||||
def store_gcode_command(self, script):
|
||||
curtime = time.time()
|
||||
for cmd in script.split('\n'):
|
||||
cmd = cmd.strip()
|
||||
if not cmd:
|
||||
continue
|
||||
self.gcode_queue.append(
|
||||
{'message': script, 'time': curtime, 'type': "command"})
|
||||
|
||||
async def _handle_gcode_store_request(self, web_request):
|
||||
count = web_request.get_int("count", None)
|
||||
if count is not None:
|
||||
res = list(self.gcode_queue)[-count:]
|
||||
gc_responses = list(self.gcode_queue)[-count:]
|
||||
else:
|
||||
res = list(self.gcode_queue)
|
||||
return {'gcode_store': res}
|
||||
gc_responses = list(self.gcode_queue)
|
||||
return {'gcode_store': gc_responses}
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config):
|
||||
return DataStore(config)
|
||||
@@ -0,0 +1,388 @@
|
||||
# Mimimal database for moonraker storage
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import json
|
||||
import struct
|
||||
import operator
|
||||
import logging
|
||||
from io import BytesIO
|
||||
from functools import reduce
|
||||
import lmdb
|
||||
|
||||
DATABASE_VERSION = 1
|
||||
MAX_NAMESPACES = 50
|
||||
MAX_DB_SIZE = 200 * 2**20
|
||||
|
||||
RECORD_ENCODE_FUNCS = {
|
||||
int: lambda x: b"q" + struct.pack("q", x),
|
||||
float: lambda x: b"d" + struct.pack("d", x),
|
||||
bool: lambda x: b"?" + struct.pack("?", x),
|
||||
str: lambda x: b"s" + x.encode(),
|
||||
list: lambda x: json.dumps(x).encode(),
|
||||
dict: lambda x: json.dumps(x).encode(),
|
||||
}
|
||||
|
||||
RECORD_DECODE_FUNCS = {
|
||||
ord("q"): lambda x: struct.unpack("q", x[1:])[0],
|
||||
ord("d"): lambda x: struct.unpack("d", x[1:])[0],
|
||||
ord("?"): lambda x: struct.unpack("?", x[1:])[0],
|
||||
ord("s"): lambda x: bytes(x[1:]).decode(),
|
||||
ord("["): lambda x: json.load(BytesIO(x)),
|
||||
ord("{"): lambda x: json.load(BytesIO(x)),
|
||||
}
|
||||
|
||||
def getitem_with_default(item, field):
|
||||
if field not in item:
|
||||
item[field] = {}
|
||||
return item[field]
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class MoonrakerDatabase:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.namespaces = {}
|
||||
self.protected_namespaces = {"moonraker"}
|
||||
self.database_path = os.path.expanduser(config.get(
|
||||
'database_path', "~/.moonraker_database"))
|
||||
if not os.path.isdir(self.database_path):
|
||||
os.mkdir(self.database_path)
|
||||
self.lmdb_env = lmdb.open(self.database_path, map_size=MAX_DB_SIZE,
|
||||
max_dbs=MAX_NAMESPACES)
|
||||
with self.lmdb_env.begin(write=True, buffers=True) as txn:
|
||||
# lookup existing namespaces
|
||||
cursor = txn.cursor()
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
key = bytes(cursor.key())
|
||||
self.namespaces[key.decode()] = self.lmdb_env.open_db(key, txn)
|
||||
remaining = cursor.next()
|
||||
cursor.close()
|
||||
if "moonraker" not in self.namespaces:
|
||||
mrdb = self.lmdb_env.open_db(b"moonraker", txn)
|
||||
self.namespaces["moonraker"] = mrdb
|
||||
txn.put(b'database_version',
|
||||
self._encode_value(DATABASE_VERSION),
|
||||
db=mrdb)
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/database/list", ['GET'], self._handle_list_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/database/item", ["GET", "POST", "DELETE"],
|
||||
self._handle_item_request)
|
||||
|
||||
def insert_item(self, namespace, key, value):
|
||||
key_list = self._process_key(key)
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
namespace.encode())
|
||||
record = value
|
||||
if len(key_list) > 1:
|
||||
record = self._get_record(namespace, key_list[0], force=True)
|
||||
if not isinstance(record, dict):
|
||||
record = {}
|
||||
logging.info(
|
||||
f"Warning: Key {key_list[0]} contains a value of type "
|
||||
f"{type(record)}. Overwriting with an object.")
|
||||
item = reduce(getitem_with_default, key_list[1:-1], record)
|
||||
item[key_list[-1]] = value
|
||||
if not self._insert_record(namespace, key_list[0], record):
|
||||
logging.info(
|
||||
f"Error inserting key '{key}' in namespace '{namespace}'")
|
||||
|
||||
def update_item(self, namespace, key, value):
|
||||
key_list = self._process_key(key)
|
||||
record = self._get_record(namespace, key_list[0])
|
||||
if len(key_list) == 1:
|
||||
if isinstance(record, dict) and isinstance(value, dict):
|
||||
record.update(value)
|
||||
else:
|
||||
record = value
|
||||
else:
|
||||
try:
|
||||
item = reduce(operator.getitem, key_list[1:-1], record)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
if isinstance(item[key_list[-1]], dict) \
|
||||
and isinstance(value, dict):
|
||||
item[key_list[-1]].update(value)
|
||||
else:
|
||||
item[key_list[-1]] = value
|
||||
if not self._insert_record(namespace, key_list[0], record):
|
||||
logging.info(
|
||||
f"Error updating key '{key}' in namespace '{namespace}'")
|
||||
|
||||
def delete_item(self, namespace, key, drop_empty_db=False):
|
||||
key_list = self._process_key(key)
|
||||
val = record = self._get_record(namespace, key_list[0])
|
||||
remove_record = True
|
||||
if len(key_list) > 1:
|
||||
try:
|
||||
item = reduce(operator.getitem, key_list[1:-1], record)
|
||||
val = item.pop(key_list[-1])
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
remove_record = False if record else True
|
||||
if remove_record:
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
ret = txn.delete(key_list[0].encode())
|
||||
cursor = txn.cursor()
|
||||
if not cursor.first() and drop_empty_db:
|
||||
txn.drop(db)
|
||||
del self.namespaces[namespace]
|
||||
else:
|
||||
ret = self._insert_record(namespace, key_list[0], record)
|
||||
if not ret:
|
||||
logging.info(
|
||||
f"Error deleting key '{key}' from namespace '{namespace}'")
|
||||
return val
|
||||
|
||||
def get_item(self, namespace, key=None, default=Sentinel):
|
||||
try:
|
||||
if key is None:
|
||||
return self._get_namespace(namespace)
|
||||
key_list = self._process_key(key)
|
||||
ns = self._get_record(namespace, key_list[0])
|
||||
val = reduce(operator.getitem, key_list[1:], ns)
|
||||
except Exception:
|
||||
if default != Sentinel:
|
||||
return default
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
return val
|
||||
|
||||
def ns_length(self, namespace):
|
||||
return len(self.ns_keys(namespace))
|
||||
|
||||
def ns_keys(self, namespace):
|
||||
keys = []
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(db=db) as txn:
|
||||
cursor = txn.cursor()
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
keys.append(cursor.key().decode())
|
||||
remaining = cursor.next()
|
||||
return keys
|
||||
|
||||
def ns_values(self, namespace):
|
||||
ns = self._get_namespace(namespace)
|
||||
return ns.values()
|
||||
|
||||
def ns_items(self, namespace):
|
||||
ns = self._get_namespace(namespace)
|
||||
return ns.items()
|
||||
|
||||
def ns_contains(self, namespace, key):
|
||||
try:
|
||||
key_list = self._process_key(key)
|
||||
if len(key_list) == 1:
|
||||
return key_list[0] in self.ns_keys(namespace)
|
||||
ns = self._get_namespace(namespace)
|
||||
reduce(operator.getitem, key_list[1:], ns)
|
||||
except Exception:
|
||||
return False
|
||||
return True
|
||||
|
||||
def register_local_namespace(self, namespace):
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
namespace.encode())
|
||||
self.protected_namespaces.add(namespace)
|
||||
|
||||
def wrap_namespace(self, namespace, parse_keys=True):
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Namespace '{namespace}' not found", 404)
|
||||
self.protected_namespaces.add(namespace)
|
||||
return NamespaceWrapper(namespace, self, parse_keys)
|
||||
|
||||
def _process_key(self, key):
|
||||
try:
|
||||
key_list = key if isinstance(key, list) else key.split('.')
|
||||
except Exception:
|
||||
key_list = []
|
||||
if not key_list or "" in key_list:
|
||||
raise self.server.error(f"Invalid Key Format: '{key}'")
|
||||
return key_list
|
||||
|
||||
def _insert_record(self, namespace, key, val):
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
ret = txn.put(key.encode(), self._encode_value(val))
|
||||
return ret
|
||||
|
||||
def _get_record(self, namespace, key, force=False):
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Namespace '{namespace}' not found", 404)
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(buffers=True, db=db) as txn:
|
||||
value = txn.get(key.encode())
|
||||
if value is None:
|
||||
if force:
|
||||
return {}
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
return self._decode_value(value)
|
||||
|
||||
def _get_namespace(self, namespace):
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Invalid database namespace '{namespace}'")
|
||||
db = self.namespaces[namespace]
|
||||
result = {}
|
||||
with self.lmdb_env.begin(buffers=True, db=db) as txn:
|
||||
cursor = txn.cursor()
|
||||
cursor.first()
|
||||
for db_key, value in cursor:
|
||||
k = bytes(db_key).decode()
|
||||
result[k] = self._decode_value(value)
|
||||
return result
|
||||
|
||||
def _encode_value(self, value):
|
||||
try:
|
||||
enc_func = RECORD_ENCODE_FUNCS[type(value)]
|
||||
return enc_func(value)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Error encoding val: {value}, type: {type(value)}")
|
||||
|
||||
def _decode_value(self, bvalue):
|
||||
fmt = bvalue[0]
|
||||
try:
|
||||
decode_func = RECORD_DECODE_FUNCS[fmt]
|
||||
return decode_func(bvalue)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Error decoding value {bvalue}, format: {chr(fmt)}")
|
||||
|
||||
async def _handle_list_request(self, web_request):
|
||||
return {'namespaces': list(self.namespaces.keys())}
|
||||
|
||||
async def _handle_item_request(self, web_request):
|
||||
action = web_request.get_action()
|
||||
namespace = web_request.get_str("namespace")
|
||||
if action != "GET":
|
||||
if namespace in self.protected_namespaces:
|
||||
raise self.server.error(
|
||||
f"Namespace '{namespace}' is write protected")
|
||||
key = web_request.get("key")
|
||||
valid_types = (list, str)
|
||||
else:
|
||||
key = web_request.get("key", None)
|
||||
valid_types = (list, str, type(None))
|
||||
if not isinstance(key, valid_types):
|
||||
raise self.server.error(
|
||||
"Value for argument 'key' is an invalid type: "
|
||||
f"{type(key).__name__}")
|
||||
if action == "GET":
|
||||
val = self.get_item(namespace, key)
|
||||
elif action == "POST":
|
||||
val = web_request.get("value")
|
||||
self.insert_item(namespace, key, val)
|
||||
elif action == "DELETE":
|
||||
val = self.delete_item(namespace, key, drop_empty_db=True)
|
||||
return {'namespace': namespace, 'key': key, 'value': val}
|
||||
|
||||
def close(self):
|
||||
# log db stats
|
||||
msg = ""
|
||||
with self.lmdb_env.begin() as txn:
|
||||
for db_name, db in self.namespaces.items():
|
||||
stats = txn.stat(db)
|
||||
msg += f"\n{db_name}:\n"
|
||||
msg += "\n".join([f"{k}: {v}" for k, v in stats.items()])
|
||||
logging.info(f"Database statistics:\n{msg}")
|
||||
self.lmdb_env.sync()
|
||||
self.lmdb_env.close()
|
||||
|
||||
class NamespaceWrapper:
|
||||
def __init__(self, namespace, database, parse_keys):
|
||||
self.namespace = namespace
|
||||
self.db = database
|
||||
# If parse keys is true, keys of a string type
|
||||
# will be passed straight to the DB methods.
|
||||
self.parse_keys = parse_keys
|
||||
|
||||
def insert(self, key, value):
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
self.db.insert_item(self.namespace, key, value)
|
||||
|
||||
def update_child(self, key, value):
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
self.db.update_item(self.namespace, key, value)
|
||||
|
||||
def update(self, value):
|
||||
val_keys = set(value.keys())
|
||||
new_keys = val_keys - set(self.keys())
|
||||
update_keys = val_keys - new_keys
|
||||
for key in update_keys:
|
||||
self.update_child([key], value[key])
|
||||
for key in new_keys:
|
||||
self.insert([key], value[key])
|
||||
|
||||
def get(self, key, default=None):
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.get_item(self.namespace, key, default)
|
||||
|
||||
def delete(self, key):
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.delete_item(self.namespace, key)
|
||||
|
||||
def __len__(self):
|
||||
return self.db.ns_length(self.namespace)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.get(key, default=Sentinel)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self.insert(key, value)
|
||||
|
||||
def __delitem__(self, key):
|
||||
self.delete(key)
|
||||
|
||||
def __contains__(self, key):
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.ns_contains(self.namespace, key)
|
||||
|
||||
def keys(self):
|
||||
return self.db.ns_keys(self.namespace)
|
||||
|
||||
def values(self):
|
||||
return self.db.ns_values(self.namespace)
|
||||
|
||||
def items(self):
|
||||
return self.db.ns_items(self.namespace)
|
||||
|
||||
def pop(self, key, default=Sentinel):
|
||||
try:
|
||||
val = self.delete(key)
|
||||
except Exception:
|
||||
if default == Sentinel:
|
||||
raise
|
||||
val = default
|
||||
return val
|
||||
|
||||
def clear(self):
|
||||
keys = self.keys()
|
||||
for k in keys:
|
||||
try:
|
||||
self.delete([k])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def load_component(config):
|
||||
return MoonrakerDatabase(config)
|
||||
@@ -6,23 +6,29 @@
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import io
|
||||
import zipfile
|
||||
import logging
|
||||
import json
|
||||
import tempfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.locks import Event
|
||||
|
||||
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
|
||||
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco', '.ufp', '.nc']
|
||||
FULL_ACCESS_ROOTS = ["gcodes", "config"]
|
||||
METADATA_SCRIPT = os.path.normpath(os.path.join(
|
||||
METADATA_SCRIPT = os.path.abspath(os.path.join(
|
||||
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
|
||||
|
||||
UFP_MODEL_PATH = "/3D/model.gcode"
|
||||
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
|
||||
|
||||
class FileManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.file_paths = {}
|
||||
self.gcode_metadata = MetadataStorage(self.server)
|
||||
database = self.server.load_component(config, "database")
|
||||
gc_path = database.get_item("moonraker", "file_manager.gcode_path", "")
|
||||
self.gcode_metadata = MetadataStorage(self.server, gc_path, database)
|
||||
self.fixed_path_args = {}
|
||||
|
||||
# Register file management endpoints
|
||||
@@ -40,12 +46,15 @@ class FileManager:
|
||||
self.server.register_endpoint(
|
||||
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
|
||||
protocol=["websocket"])
|
||||
# register client notificaitons
|
||||
self.server.register_notification("file_manager:filelist_changed")
|
||||
self.server.register_notification("file_manager:metadata_update")
|
||||
# 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)
|
||||
"server:klippy_identified", self._update_fixed_paths)
|
||||
|
||||
# Register Klippy Configuration Path
|
||||
config_path = config.get('config_path', None)
|
||||
@@ -55,6 +64,10 @@ class FileManager:
|
||||
raise config.error(
|
||||
"Option 'config_path' is not a valid directory")
|
||||
|
||||
# If gcode path is in the database, register it
|
||||
if gc_path:
|
||||
self.register_directory('gcodes', gc_path)
|
||||
|
||||
def _update_fixed_paths(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
paths = {k: kinfo.get(k) for k in
|
||||
@@ -77,26 +90,38 @@ class FileManager:
|
||||
|
||||
# Register log path
|
||||
log_file = paths.get('log_file')
|
||||
log_path = os.path.normpath(os.path.expanduser(log_file))
|
||||
self.server.register_static_file_handler("klippy.log", log_path)
|
||||
if log_file is not None:
|
||||
log_path = os.path.abspath(os.path.expanduser(log_file))
|
||||
self.server.register_static_file_handler(
|
||||
"klippy.log", log_path, force=True)
|
||||
|
||||
def register_directory(self, root, path):
|
||||
if path is None:
|
||||
return False
|
||||
home = os.path.expanduser('~')
|
||||
path = os.path.normpath(os.path.expanduser(path))
|
||||
if not os.path.isdir(path) or not path.startswith(home) or \
|
||||
path == home:
|
||||
path = os.path.abspath(os.path.expanduser(path))
|
||||
if os.path.islink(path):
|
||||
path = os.path.realpath(path)
|
||||
if not os.path.isdir(path) or path == "/":
|
||||
logging.info(
|
||||
f"\nSupplied path ({path}) for ({root}) not valid. Please\n"
|
||||
"check that the path exists and is a subfolder in the HOME\n"
|
||||
"directory. Note that the path may not BE the home directory.")
|
||||
f"\nSupplied path ({path}) for ({root}) a valid. Make sure\n"
|
||||
"that the path exists and is not the file system root.")
|
||||
return False
|
||||
permissions = os.R_OK
|
||||
if root in FULL_ACCESS_ROOTS:
|
||||
permissions |= os.W_OK
|
||||
if not os.access(path, permissions):
|
||||
logging.info(
|
||||
f"\nMoonraker does not have permission to access path "
|
||||
f"({path}) for ({root}).")
|
||||
return False
|
||||
if path != self.file_paths.get(root, ""):
|
||||
self.file_paths[root] = path
|
||||
self.server.register_static_file_handler(root, path)
|
||||
if root == "gcodes":
|
||||
# scan metadata
|
||||
database = self.server.lookup_component(
|
||||
"database").wrap_namespace("moonraker")
|
||||
database["file_manager.gcode_path"] = path
|
||||
# scan for metadata changes
|
||||
self.gcode_metadata.update_gcode_path(path)
|
||||
try:
|
||||
self.get_file_list("gcodes")
|
||||
@@ -108,9 +133,17 @@ class FileManager:
|
||||
def get_sd_directory(self):
|
||||
return self.file_paths.get('gcodes', "")
|
||||
|
||||
def get_registered_dirs(self):
|
||||
return list(self.file_paths.keys())
|
||||
|
||||
def get_fixed_path_args(self):
|
||||
return dict(self.fixed_path_args)
|
||||
|
||||
def check_file_exists(self, root, filename):
|
||||
root_dir = self.file_paths.get(root, "")
|
||||
file_path = os.path.join(root_dir, filename)
|
||||
return os.path.exists(file_path)
|
||||
|
||||
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)
|
||||
@@ -131,18 +164,7 @@ class FileManager:
|
||||
if action == 'GET':
|
||||
is_extended = web_request.get_boolean('extended', False)
|
||||
# Get list of files and subdirectories for this target
|
||||
dir_info = self._list_directory(dir_path)
|
||||
# Check to see if a filelist update is necessary
|
||||
for f in dir_info['files']:
|
||||
fname = os.path.join(rel_path, f['filename'])
|
||||
ext = os.path.splitext(f['filename'])[-1].lower()
|
||||
if root != 'gcodes' or ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
self.gcode_metadata.parse_metadata(
|
||||
fname, f['size'], f['modified'], notify=True)
|
||||
metadata = self.gcode_metadata.get(fname, None)
|
||||
if metadata is not None and is_extended:
|
||||
f.update(metadata)
|
||||
dir_info = self._list_directory(dir_path, is_extended)
|
||||
return dir_info
|
||||
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
|
||||
# Create a new directory
|
||||
@@ -179,7 +201,7 @@ class FileManager:
|
||||
|
||||
async def _handle_operation_check(self, requested_path):
|
||||
# Get virtual_sdcard status
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
result = await klippy_apis.query_objects({'print_stats': None})
|
||||
pstats = result.get('print_stats', {})
|
||||
loaded_file = pstats.get('filename', "")
|
||||
@@ -264,20 +286,45 @@ class FileManager:
|
||||
{'path': src_rel_path, 'root': source_root})
|
||||
return "ok"
|
||||
|
||||
def _list_directory(self, path):
|
||||
def _list_directory(self, path, is_extended=False):
|
||||
if not os.path.isdir(path):
|
||||
raise self.server.error(
|
||||
f"Directory does not exist ({path})")
|
||||
flist = {'dirs': [], 'files': []}
|
||||
for fname in os.listdir(path):
|
||||
full_path = os.path.join(path, fname)
|
||||
if not os.path.exists(full_path):
|
||||
continue
|
||||
path_info = self._get_path_info(full_path)
|
||||
if os.path.isdir(full_path):
|
||||
path_info['dirname'] = fname
|
||||
flist['dirs'].append(path_info)
|
||||
elif os.path.isfile(full_path):
|
||||
path_info['filename'] = fname
|
||||
# Check to see if a filelist update is necessary
|
||||
ext = os.path.splitext(fname)[-1].lower()
|
||||
gc_path = self.file_paths.get('gcodes', None)
|
||||
if gc_path is not None and full_path.startswith(gc_path) and \
|
||||
ext in VALID_GCODE_EXTS:
|
||||
if ext == ".ufp":
|
||||
try:
|
||||
full_path = self._process_ufp_from_refresh(
|
||||
full_path)
|
||||
except Exception:
|
||||
logging.exception("Error processing ufp file")
|
||||
continue
|
||||
path_info = self._get_path_info(full_path)
|
||||
path_info['filename'] = os.path.split(full_path)[-1]
|
||||
rel_path = os.path.relpath(full_path, start=gc_path)
|
||||
self.gcode_metadata.parse_metadata(
|
||||
rel_path, path_info['size'], path_info['modified'],
|
||||
notify=True)
|
||||
metadata = self.gcode_metadata.get(rel_path, None)
|
||||
if metadata is not None and is_extended:
|
||||
path_info.update(metadata)
|
||||
flist['files'].append(path_info)
|
||||
usage = shutil.disk_usage(path)
|
||||
flist['disk_usage'] = usage._asdict()
|
||||
return flist
|
||||
|
||||
def _get_path_info(self, path):
|
||||
@@ -286,31 +333,76 @@ class FileManager:
|
||||
path_info = {'modified': modified, 'size': size}
|
||||
return path_info
|
||||
|
||||
async def process_file_upload(self, request):
|
||||
def gen_temp_upload_path(self):
|
||||
ioloop = IOLoop.current()
|
||||
return os.path.join(
|
||||
tempfile.gettempdir(),
|
||||
f"moonraker.upload-{int(ioloop.time())}.mru")
|
||||
|
||||
async def finalize_upload(self, form_args):
|
||||
# lookup root file path
|
||||
root = self._get_argument(request, 'root', "gcodes")
|
||||
if root == "gcodes":
|
||||
result = await self._do_gcode_upload(request)
|
||||
elif root in FULL_ACCESS_ROOTS:
|
||||
result = self._do_standard_upload(request, root)
|
||||
else:
|
||||
raise self.server.error(f"Invalid root request: {root}")
|
||||
try:
|
||||
upload_info = self._parse_upload_args(form_args)
|
||||
root = upload_info['root']
|
||||
if root == "gcodes":
|
||||
result = await self._finish_gcode_upload(upload_info)
|
||||
elif root in FULL_ACCESS_ROOTS:
|
||||
result = await self._finish_standard_upload(upload_info)
|
||||
else:
|
||||
raise self.server.error(f"Invalid root request: {root}")
|
||||
except Exception:
|
||||
try:
|
||||
os.remove(form_args['tmp_file_path'])
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return result
|
||||
|
||||
async def _do_gcode_upload(self, request):
|
||||
start_print = print_ongoing = False
|
||||
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, root_path)
|
||||
fparts = os.path.splitext(upload['full_path'])
|
||||
is_ufp = fparts[-1].lower() == ".ufp"
|
||||
def _parse_upload_args(self, upload_args):
|
||||
if 'filename' not in upload_args:
|
||||
raise self.server.error(
|
||||
"No file name specifed in upload form")
|
||||
# check relative path
|
||||
root = upload_args.get('root', "gcodes").lower()
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(f"Root {root} not available")
|
||||
root_path = self.file_paths[root]
|
||||
dir_path = upload_args.get('path', "")
|
||||
if os.path.isfile(root_path):
|
||||
filename = os.path.basename(root_path)
|
||||
dest_path = root_path
|
||||
dir_path = ""
|
||||
else:
|
||||
filename = upload_args['filename'].strip().lstrip("/")
|
||||
if dir_path:
|
||||
filename = os.path.join(dir_path, filename)
|
||||
dest_path = os.path.abspath(os.path.join(root_path, filename))
|
||||
# Validate the path. Don't allow uploads to a parent of the root
|
||||
if not dest_path.startswith(root_path):
|
||||
raise self.server.error(
|
||||
f"Cannot write to path: {dest_path}")
|
||||
start_print = upload_args.get('print', "false") == "true"
|
||||
f_ext = os.path.splitext(dest_path)[-1].lower()
|
||||
unzip_ufp = f_ext == ".ufp" and root == "gcodes"
|
||||
if unzip_ufp:
|
||||
filename = os.path.splitext(filename)[0] + ".gcode"
|
||||
dest_path = os.path.splitext(dest_path)[0] + ".gcode"
|
||||
return {
|
||||
'root': root,
|
||||
'filename': filename,
|
||||
'dir_path': dir_path,
|
||||
'dest_path': dest_path,
|
||||
'tmp_file_path': upload_args['tmp_file_path'],
|
||||
'start_print': start_print,
|
||||
'unzip_ufp': unzip_ufp
|
||||
}
|
||||
|
||||
async def _finish_gcode_upload(self, upload_info):
|
||||
print_ongoing = False
|
||||
start_print = upload_info['start_print']
|
||||
# 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"
|
||||
check_path = upload_info['dest_path']
|
||||
print_ongoing = await self._handle_operation_check(
|
||||
check_path)
|
||||
except self.server.error as e:
|
||||
@@ -323,121 +415,84 @@ 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, is_ufp)
|
||||
ioloop = IOLoop.current()
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
await ioloop.run_in_executor(
|
||||
tpe, self._process_uploaded_file, upload_info)
|
||||
# Fetch Metadata
|
||||
finfo = self._get_path_info(upload['full_path'])
|
||||
finfo = self._get_path_info(upload_info['dest_path'])
|
||||
evt = self.gcode_metadata.parse_metadata(
|
||||
upload['filename'], finfo['size'], finfo['modified'])
|
||||
upload_info['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')
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
try:
|
||||
await klippy_apis.start_print(upload['filename'])
|
||||
await klippy_apis.start_print(upload_info['filename'])
|
||||
except self.server.error:
|
||||
# Attempt to start print failed
|
||||
start_print = False
|
||||
self.notify_filelist_changed(
|
||||
'upload_file', upload['filename'], "gcodes")
|
||||
return {'result': upload['filename'], 'print_started': start_print}
|
||||
|
||||
def _do_standard_upload(self, request, root):
|
||||
path = self.file_paths.get(root, None)
|
||||
if path is None:
|
||||
raise self.server.error(f"Unknown root path: {root}")
|
||||
upload = self._get_upload_info(request, path)
|
||||
self._write_file(upload)
|
||||
self.notify_filelist_changed('upload_file', upload['filename'], root)
|
||||
return {'result': upload['filename']}
|
||||
|
||||
def _get_argument(self, request, name, default=None):
|
||||
args = request.arguments.get(name, None)
|
||||
if args is not None:
|
||||
return args[0].decode().strip()
|
||||
return default
|
||||
|
||||
def _get_upload_info(self, request, root_path):
|
||||
# check relative path
|
||||
dir_path = self._get_argument(request, 'path', "")
|
||||
# fetch the upload from the request
|
||||
if len(request.files) != 1:
|
||||
raise self.server.error(
|
||||
"Bad Request, can only process a single file upload")
|
||||
f_list = list(request.files.values())[0]
|
||||
if len(f_list) != 1:
|
||||
raise self.server.error(
|
||||
"Bad Request, can only process a single file upload")
|
||||
upload = f_list[0]
|
||||
if os.path.isfile(root_path):
|
||||
filename = os.path.basename(root_path)
|
||||
full_path = root_path
|
||||
dir_path = ""
|
||||
else:
|
||||
parts = os.path.split(upload['filename'].strip().lstrip("/"))
|
||||
filename = os.path.join(parts[0], "_".join(parts[1].split()))
|
||||
if dir_path:
|
||||
filename = os.path.join(dir_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(root_path):
|
||||
raise self.server.error(
|
||||
f"Cannot write to path: {full_path}")
|
||||
'upload_file', upload_info['filename'], "gcodes")
|
||||
return {
|
||||
'filename': filename,
|
||||
'body': upload['body'],
|
||||
'dir_path': dir_path,
|
||||
'full_path': full_path}
|
||||
'result': upload_info['filename'],
|
||||
'print_started': start_print
|
||||
}
|
||||
|
||||
def _write_file(self, upload, unzip_ufp=False):
|
||||
async def _finish_standard_upload(self, upload_info):
|
||||
ioloop = IOLoop.current()
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
await ioloop.run_in_executor(
|
||||
tpe, self._process_uploaded_file, upload_info)
|
||||
self.notify_filelist_changed(
|
||||
'upload_file', upload_info['filename'], upload_info['root'])
|
||||
return {'result': upload_info['filename']}
|
||||
|
||||
def _process_uploaded_file(self, upload_info):
|
||||
try:
|
||||
if upload['dir_path']:
|
||||
if upload_info['dir_path']:
|
||||
os.makedirs(os.path.dirname(
|
||||
upload['full_path']), exist_ok=True)
|
||||
if unzip_ufp:
|
||||
self._unzip_ufp(upload)
|
||||
upload_info['dest_path']), exist_ok=True)
|
||||
if upload_info['unzip_ufp']:
|
||||
self._unzip_ufp(upload_info['tmp_file_path'],
|
||||
upload_info['dest_path'])
|
||||
else:
|
||||
with open(upload['full_path'], 'wb') as fh:
|
||||
fh.write(upload['body'])
|
||||
shutil.move(upload_info['tmp_file_path'],
|
||||
upload_info['dest_path'])
|
||||
except Exception:
|
||||
logging.exception("Upload Write Error")
|
||||
raise self.server.error("Unable to save file", 500)
|
||||
|
||||
# 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")
|
||||
# UFP Extraction Implementation inspired by GitHub user @cdkeito
|
||||
def _unzip_ufp(self, ufp_path, dest_path):
|
||||
thumb_name = os.path.splitext(
|
||||
os.path.basename(dest_path))[0] + ".png"
|
||||
dest_thumb_dir = os.path.join(os.path.dirname(dest_path), "thumbs")
|
||||
dest_thumb_path = os.path.join(dest_thumb_dir, thumb_name)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp_dir_name:
|
||||
tmp_thumb_path = ""
|
||||
with zipfile.ZipFile(ufp_path) as zf:
|
||||
tmp_model_path = zf.extract(
|
||||
UFP_MODEL_PATH, path=tmp_dir_name)
|
||||
if UFP_THUMB_PATH in zf.namelist():
|
||||
tmp_thumb_path = zf.extract(
|
||||
UFP_THUMB_PATH, path=tmp_dir_name)
|
||||
shutil.move(tmp_model_path, dest_path)
|
||||
if tmp_thumb_path:
|
||||
if not os.path.exists(dest_thumb_dir):
|
||||
os.mkdir(dest_thumb_dir)
|
||||
shutil.move(tmp_thumb_path, dest_thumb_path)
|
||||
finally:
|
||||
try:
|
||||
img_bytes = zf.read("/Metadata/thumbnail.png")
|
||||
os.remove(ufp_path)
|
||||
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")
|
||||
logging.exception(f"Error removing ufp file: {ufp_path}")
|
||||
|
||||
def _process_ufp_from_refresh(self, ufp_path):
|
||||
dest_path = os.path.splitext(ufp_path)[0] + ".gcode"
|
||||
self._unzip_ufp(ufp_path, dest_path)
|
||||
return dest_path
|
||||
|
||||
def get_file_list(self, root, list_format=False, notify=False):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
@@ -448,12 +503,30 @@ class FileManager:
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info(f"Updating File List <{root}>...")
|
||||
for root_path, dirs, files in os.walk(path, followlinks=True):
|
||||
st = os.stat(path)
|
||||
visited_dirs = {(st.st_dev, st.st_ino)}
|
||||
for dir_path, dir_names, files in os.walk(path, followlinks=True):
|
||||
scan_dirs = []
|
||||
# Filter out directories that have already been visted. This
|
||||
# prevents infinite recrusion "followlinks" is set to True
|
||||
for dname in dir_names:
|
||||
st = os.stat(os.path.join(dir_path, dname))
|
||||
key = (st.st_dev, st.st_ino)
|
||||
if key not in visited_dirs:
|
||||
visited_dirs.add(key)
|
||||
scan_dirs.append(dname)
|
||||
dir_names[:] = scan_dirs
|
||||
for name in files:
|
||||
ext = os.path.splitext(name)[-1].lower()
|
||||
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root_path, name)
|
||||
full_path = os.path.join(dir_path, name)
|
||||
if ext == ".ufp":
|
||||
try:
|
||||
full_path = self._process_ufp_from_refresh(full_path)
|
||||
except Exception:
|
||||
logging.exception("Error processing ufp file")
|
||||
continue
|
||||
fname = full_path[len(path) + 1:]
|
||||
finfo = self._get_path_info(full_path)
|
||||
filelist[fname] = finfo
|
||||
@@ -478,12 +551,10 @@ class FileManager:
|
||||
if filename.startswith('gcodes/'):
|
||||
filename = filename[7:]
|
||||
|
||||
flist = self.get_file_list("gcodes")
|
||||
return self.gcode_metadata.get(filename, flist.get(filename, {}))
|
||||
return self.gcode_metadata.get(filename, {})
|
||||
|
||||
def list_dir(self, directory, simple_format=False):
|
||||
# List a directory relative to its root. Currently the only
|
||||
# Supported root is "gcodes"
|
||||
# List a directory relative to its root.
|
||||
if directory[0] == "/":
|
||||
directory = directory[1:]
|
||||
parts = directory.split("/", 1)
|
||||
@@ -555,23 +626,34 @@ class FileManager:
|
||||
|
||||
|
||||
METADATA_PRUNE_TIME = 600000
|
||||
METADATA_NAMESPACE = "gcode_metadata"
|
||||
METADATA_VERSION = 3
|
||||
|
||||
class MetadataStorage:
|
||||
def __init__(self, server):
|
||||
def __init__(self, server, gc_path, database):
|
||||
self.server = server
|
||||
self.metadata = {}
|
||||
database.register_local_namespace(METADATA_NAMESPACE)
|
||||
self.mddb = database.wrap_namespace(
|
||||
METADATA_NAMESPACE, parse_keys=False)
|
||||
version = database.get_item(
|
||||
"moonraker", "file_manager.metadata_version", 0)
|
||||
if version != METADATA_VERSION:
|
||||
# Clear existing metadata when version is bumped
|
||||
self.mddb.clear()
|
||||
database.insert_item(
|
||||
"moonraker", "file_manager.metadata_version",
|
||||
METADATA_VERSION)
|
||||
self.pending_requests = {}
|
||||
self.events = {}
|
||||
self.script_response = None
|
||||
self.busy = False
|
||||
self.gc_path = os.path.expanduser("~")
|
||||
self.gc_path = gc_path
|
||||
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.mddb.clear()
|
||||
self.gc_path = path
|
||||
if not self.prune_cb.is_running():
|
||||
self.prune_cb.start()
|
||||
@@ -580,40 +662,39 @@ class MetadataStorage:
|
||||
self.prune_cb.stop()
|
||||
|
||||
def get(self, key, default=None):
|
||||
if key not in self.metadata:
|
||||
return default
|
||||
return dict(self.metadata[key])
|
||||
return self.mddb.get(key, default)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return dict(self.metadata[key])
|
||||
|
||||
def _handle_script_response(self, result):
|
||||
try:
|
||||
proc_resp = json.loads(result.strip())
|
||||
except Exception:
|
||||
logging.exception("file_manager: unable to load metadata")
|
||||
logging.debug(result)
|
||||
return
|
||||
proc_log = proc_resp.get('log', [])
|
||||
for log_msg in proc_log:
|
||||
logging.info(log_msg)
|
||||
if 'file' in proc_resp:
|
||||
self.script_response = proc_resp
|
||||
return self.mddb[key]
|
||||
|
||||
def prune_metadata(self):
|
||||
for fname in list(self.metadata.keys()):
|
||||
for fname in list(self.mddb.keys()):
|
||||
fpath = os.path.join(self.gc_path, fname)
|
||||
if not os.path.exists(fpath):
|
||||
del self.metadata[fname]
|
||||
self.remove_file(fname)
|
||||
logging.info(f"Pruned file: {fname}")
|
||||
continue
|
||||
|
||||
def _has_valid_data(self, fname, fsize, modified):
|
||||
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
|
||||
mdata = self.mddb.get(fname, {'size': "", 'modified': 0})
|
||||
return mdata['size'] == fsize and mdata['modified'] == modified
|
||||
|
||||
def remove_file(self, fname):
|
||||
self.metadata.pop(fname)
|
||||
metadata = self.mddb.pop(fname, None)
|
||||
if metadata is None:
|
||||
return
|
||||
# Delete associated thumbnails
|
||||
fdir = os.path.dirname(os.path.join(self.gc_path, fname))
|
||||
if "thumbnails" in metadata:
|
||||
for thumb in metadata["thumbnails"]:
|
||||
path = thumb.get("relative_path", None)
|
||||
if path is None:
|
||||
continue
|
||||
thumb_path = os.path.join(fdir, path)
|
||||
try:
|
||||
os.remove(thumb_path)
|
||||
except Exception:
|
||||
logging.debug(f"Error removing thumb at {thumb_path}")
|
||||
|
||||
def parse_metadata(self, fname, fsize, modified, notify=False):
|
||||
evt = Event()
|
||||
@@ -646,32 +727,42 @@ class MetadataStorage:
|
||||
else:
|
||||
break
|
||||
else:
|
||||
self.metadata[fname] = {'size': fsize, 'modified': modified}
|
||||
self.mddb[fname] = {
|
||||
'size': fsize,
|
||||
'modified': modified,
|
||||
'print_start_time': None,
|
||||
'job_id': None
|
||||
}
|
||||
logging.info(
|
||||
f"Unable to extract medatadata from file: {fname}")
|
||||
evt.set()
|
||||
self.busy = False
|
||||
|
||||
async def _run_extract_metadata(self, filename, notify):
|
||||
# Escape single quotes in the file name so that it may be
|
||||
# properly loaded
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
self.gc_path, "-f", "'" + filename + "'"])
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(
|
||||
cmd, self._handle_script_response)
|
||||
self.script_response = None
|
||||
await scmd.run(timeout=4.)
|
||||
if self.script_response is None:
|
||||
raise self.server.error("Unable to extract metadata")
|
||||
path = self.script_response['file']
|
||||
metadata = self.script_response['metadata']
|
||||
self.gc_path, "-f", f"\"{filename}\""])
|
||||
shell_command = self.server.lookup_component('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, log_stderr=True)
|
||||
result = await scmd.run_with_response(timeout=10.)
|
||||
try:
|
||||
decoded_resp = json.loads(result.strip())
|
||||
except Exception:
|
||||
logging.debug(f"Invalid metadata response:\n{result}")
|
||||
raise
|
||||
path = decoded_resp['file']
|
||||
metadata = decoded_resp['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.update({'print_start_time': None, 'job_id': None})
|
||||
self.mddb[path] = dict(metadata)
|
||||
metadata['filename'] = path
|
||||
if notify:
|
||||
self.server.send_event(
|
||||
"file_manager:metadata_update", metadata)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config):
|
||||
return FileManager(config)
|
||||
@@ -0,0 +1,294 @@
|
||||
# History cache for printer jobs
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
import time
|
||||
|
||||
HIST_NAMESPACE = "history"
|
||||
MAX_JOBS = 10000
|
||||
|
||||
class History:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.file_manager = self.server.lookup_component('file_manager')
|
||||
database = self.server.lookup_component("database")
|
||||
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
|
||||
self.job_totals = database.get_item(
|
||||
"moonraker", "history.job_totals",
|
||||
{
|
||||
'total_jobs': 0,
|
||||
'total_time': 0.,
|
||||
'total_print_time': 0.,
|
||||
'total_filament_used': 0.,
|
||||
'longest_job': 0.,
|
||||
'longest_print': 0.
|
||||
})
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._status_update)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._handle_disconnect)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_shutdown)
|
||||
self.server.register_notification("history:history_changed")
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/history/job", ['GET', 'DELETE'], self._handle_job_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/list", ['GET'], self._handle_jobs_list)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/totals", ['GET'], self._handle_job_totals)
|
||||
|
||||
database.register_local_namespace(HIST_NAMESPACE)
|
||||
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
|
||||
parse_keys=False)
|
||||
|
||||
self.current_job = None
|
||||
self.current_job_id = None
|
||||
self.print_stats = {}
|
||||
self.next_job_id = 0
|
||||
self.cached_job_ids = self.history_ns.keys()
|
||||
if self.cached_job_ids:
|
||||
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
|
||||
|
||||
async def _init_ready(self):
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
sub = {"print_stats": None}
|
||||
try:
|
||||
result = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to print_stats")
|
||||
self.print_stats = result.get("print_stats", {})
|
||||
|
||||
async def _handle_job_request(self, web_request):
|
||||
action = web_request.get_action()
|
||||
if action == "GET":
|
||||
job_id = web_request.get_str("uid")
|
||||
if job_id not in self.cached_job_ids:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
job = self.history_ns[job_id]
|
||||
return {"job": self._prep_requested_job(job, job_id)}
|
||||
if action == "DELETE":
|
||||
all = web_request.get_boolean("all", False)
|
||||
if all:
|
||||
deljobs = self.cached_job_ids
|
||||
self.history_ns.clear()
|
||||
self.cached_job_ids = []
|
||||
self.next_job_id = 0
|
||||
return {'deleted_jobs': deljobs}
|
||||
|
||||
job_id = web_request.get_str("uid")
|
||||
if job_id not in self.cached_job_ids:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
|
||||
self.delete_job(job_id)
|
||||
return {'deleted_jobs': [job_id]}
|
||||
|
||||
async def _handle_jobs_list(self, web_request):
|
||||
i = 0
|
||||
end_num = len(self.history_ns)
|
||||
jobs = []
|
||||
start_num = 0
|
||||
|
||||
before = web_request.get_float("before", -1)
|
||||
since = web_request.get_float("since", -1)
|
||||
limit = web_request.get_int("limit", 50)
|
||||
start = web_request.get_int("start", 0)
|
||||
if start >= end_num or end_num == 0:
|
||||
return {"count": 0, "jobs": []}
|
||||
|
||||
for job_id in self.cached_job_ids:
|
||||
job = self.history_ns[job_id]
|
||||
if since != -1 and since > job.get('start_time'):
|
||||
start_num += 1
|
||||
continue
|
||||
if before != -1 and before < job.get('end_time'):
|
||||
end_num -= 1
|
||||
continue
|
||||
if limit != 0 and i >= limit:
|
||||
continue
|
||||
if start != 0:
|
||||
start -= 1
|
||||
continue
|
||||
jobs.append(self._prep_requested_job(job, job_id))
|
||||
i += 1
|
||||
|
||||
return {"count": end_num - start_num, "jobs": jobs}
|
||||
|
||||
async def _handle_job_totals(self, web_request):
|
||||
return {'job_totals': self.job_totals}
|
||||
|
||||
async def _status_update(self, data):
|
||||
ps = data.get("print_stats", {})
|
||||
if "state" in ps:
|
||||
old_state = self.print_stats['state']
|
||||
new_state = ps['state']
|
||||
new_ps = dict(self.print_stats)
|
||||
new_ps.update(ps)
|
||||
|
||||
if new_state is not old_state:
|
||||
if new_state == "printing" and self.current_job is None:
|
||||
# always add new job if no existing job is present
|
||||
self.add_job(PrinterJob(new_ps))
|
||||
elif self.current_job is not None:
|
||||
if new_state == "complete":
|
||||
self.finish_job("completed", new_ps)
|
||||
if new_state == "standby":
|
||||
self.finish_job("cancelled", self.print_stats)
|
||||
elif new_state == "error":
|
||||
self.finish_job("error", new_ps)
|
||||
elif new_state == "printing" and \
|
||||
self._check_need_cancel(new_ps):
|
||||
# Finish with the previous state
|
||||
self.finish_job("cancelled", self.print_stats)
|
||||
self.add_job(PrinterJob(new_ps))
|
||||
|
||||
self.print_stats.update(ps)
|
||||
|
||||
def _handle_shutdown(self):
|
||||
self.finish_job("klippy_shutdown", self.print_stats)
|
||||
|
||||
def _handle_disconnect(self):
|
||||
self.finish_job("klippy_disconnect", self.print_stats)
|
||||
|
||||
def _check_need_cancel(self, new_stats):
|
||||
# Cancel if the file name has changed, total duration has
|
||||
# decreased, or if job is not resuming from a pause
|
||||
ps = self.print_stats
|
||||
return ps['filename'] != new_stats['filename'] or \
|
||||
ps['total_duration'] > new_stats['total_duration'] or \
|
||||
ps['state'] != "paused"
|
||||
|
||||
def add_job(self, job):
|
||||
if len(self.cached_job_ids) >= MAX_JOBS:
|
||||
self.delete_job(self.cached_job_ids[0])
|
||||
job_id = f"{self.next_job_id:06X}"
|
||||
self.current_job = job
|
||||
self.current_job_id = job_id
|
||||
self.grab_job_metadata()
|
||||
self.history_ns[job_id] = job.get_stats()
|
||||
self.cached_job_ids.append(job_id)
|
||||
self.next_job_id += 1
|
||||
self.send_history_event("added")
|
||||
|
||||
def delete_job(self, job_id):
|
||||
if isinstance(job_id, int):
|
||||
job_id = f"{job_id:06X}"
|
||||
|
||||
if job_id in self.cached_job_ids:
|
||||
del self.history_ns[job_id]
|
||||
self.cached_job_ids.remove(job_id)
|
||||
|
||||
def finish_job(self, status, pstats):
|
||||
if self.current_job is None:
|
||||
return
|
||||
|
||||
self.current_job.finish(status, pstats)
|
||||
# Regrab metadata incase metadata wasn't parsed yet due to file upload
|
||||
self.grab_job_metadata()
|
||||
self.save_current_job()
|
||||
self._update_job_totals()
|
||||
self.send_history_event("finished")
|
||||
self.current_job = None
|
||||
self.current_job_id = None
|
||||
|
||||
def get_job(self, job_id):
|
||||
if isinstance(job_id, int):
|
||||
job_id = f"{job_id:06X}"
|
||||
return self.history_ns.get(job_id, None)
|
||||
|
||||
def grab_job_metadata(self):
|
||||
if self.current_job is None:
|
||||
return
|
||||
filename = self.current_job.get("filename")
|
||||
metadata = self.gcdb.get(filename, {})
|
||||
if metadata:
|
||||
# Add the start time and job id to the
|
||||
# persistent metadata storage
|
||||
metadata.update({
|
||||
'print_start_time': self.current_job.get('start_time'),
|
||||
'job_id': self.current_job_id
|
||||
})
|
||||
self.gcdb[filename] = metadata
|
||||
# We don't need to store these fields in the
|
||||
# job metadata, as they are redundant
|
||||
metadata.pop('print_start_time', None)
|
||||
metadata.pop('job_id', None)
|
||||
if "thumbnails" in metadata:
|
||||
for thumb in metadata['thumbnails']:
|
||||
thumb.pop('data', None)
|
||||
self.current_job.set("metadata", metadata)
|
||||
|
||||
def save_current_job(self):
|
||||
self.history_ns[self.current_job_id] = self.current_job.get_stats()
|
||||
|
||||
def _update_job_totals(self):
|
||||
if self.current_job is None:
|
||||
return
|
||||
job = self.current_job
|
||||
self.job_totals['total_jobs'] += 1
|
||||
self.job_totals['total_time'] += job.get('total_duration')
|
||||
self.job_totals['total_print_time'] += job.get('print_duration')
|
||||
self.job_totals['total_filament_used'] += job.get('filament_used')
|
||||
self.job_totals['longest_job'] = max(
|
||||
self.job_totals['longest_job'], job.get('total_duration'))
|
||||
self.job_totals['longest_print'] = max(
|
||||
self.job_totals['longest_print'], job.get('print_duration'))
|
||||
database = self.server.lookup_component("database")
|
||||
database.insert_item(
|
||||
"moonraker", "history.job_totals", self.job_totals)
|
||||
|
||||
def send_history_event(self, evt_action):
|
||||
job = self._prep_requested_job(
|
||||
self.current_job.get_stats(), self.current_job_id)
|
||||
self.server.send_event("history:history_changed",
|
||||
{'action': evt_action, 'job': job})
|
||||
|
||||
def _prep_requested_job(self, job, job_id):
|
||||
job['job_id'] = job_id
|
||||
job['exists'] = self.file_manager.check_file_exists(
|
||||
"gcodes", job['filename'])
|
||||
return job
|
||||
|
||||
def on_exit(self):
|
||||
self.finish_job("server_exit", self.print_stats)
|
||||
|
||||
class PrinterJob:
|
||||
def __init__(self, data={}):
|
||||
self.end_time = None
|
||||
self.filament_used = 0
|
||||
self.filename = None
|
||||
self.metadata = None
|
||||
self.print_duration = 0
|
||||
self.status = "in_progress"
|
||||
self.start_time = time.time()
|
||||
self.total_duration = 0
|
||||
self.update_from_ps(data)
|
||||
|
||||
def finish(self, status, print_stats={}):
|
||||
self.end_time = time.time()
|
||||
self.status = status
|
||||
self.update_from_ps(print_stats)
|
||||
|
||||
def get(self, name):
|
||||
if not hasattr(self, name):
|
||||
return None
|
||||
return getattr(self, name)
|
||||
|
||||
def get_stats(self):
|
||||
return self.__dict__.copy()
|
||||
|
||||
def set(self, name, val):
|
||||
if not hasattr(self, name):
|
||||
return
|
||||
setattr(self, name, val)
|
||||
|
||||
def update_from_ps(self, data):
|
||||
for i in data:
|
||||
if hasattr(self, i):
|
||||
setattr(self, i, data[i])
|
||||
|
||||
def load_component(config):
|
||||
return History(config)
|
||||
@@ -80,6 +80,8 @@ class KlippyAPI:
|
||||
# XXX - validate that file is on disk
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
|
||||
return await self.run_gcode(script)
|
||||
|
||||
@@ -155,5 +157,5 @@ class KlippyAPI:
|
||||
def send_status(self, status):
|
||||
self.server.send_event("server:status_update", status)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config):
|
||||
return KlippyAPI(config)
|
||||
@@ -6,6 +6,8 @@
|
||||
import logging
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
ALLOWED_SERVICES = ["moonraker", "klipper", "webcamd"]
|
||||
|
||||
class Machine:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
@@ -15,7 +17,13 @@ class Machine:
|
||||
"/machine/shutdown", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/restart", ['POST'],
|
||||
self._handle_service_restart)
|
||||
self._handle_service_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/stop", ['POST'],
|
||||
self._handle_service_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/start", ['POST'],
|
||||
self._handle_service_request)
|
||||
|
||||
# Register remote methods
|
||||
self.server.register_remote_method(
|
||||
@@ -39,20 +47,28 @@ class Machine:
|
||||
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":
|
||||
async def do_service_action(self, action, service_name):
|
||||
await self._execute_cmd(
|
||||
f'sudo systemctl {action} {service_name}')
|
||||
|
||||
async def _handle_service_request(self, web_request):
|
||||
name = web_request.get('service').lower()
|
||||
action = web_request.get_endpoint().split('/')[-1]
|
||||
if name == "moonraker":
|
||||
if action != "restart":
|
||||
raise self.server.error(
|
||||
f"Service action '{action}' not available for moonraker")
|
||||
IOLoop.current().spawn_callback(
|
||||
self._execute_cmd, f'sudo systemctl restart {name}')
|
||||
self.do_service_action, action, name)
|
||||
elif name in ALLOWED_SERVICES:
|
||||
await self.do_service_action(action, name)
|
||||
else:
|
||||
raise self.sever.error(
|
||||
raise self.server.error(
|
||||
f"Invalid argument recevied for 'name': {name}")
|
||||
return "ok"
|
||||
|
||||
async def _execute_cmd(self, cmd):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
shell_command = self.server.lookup_component('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
try:
|
||||
await scmd.run(timeout=2., verbose=False)
|
||||
@@ -60,5 +76,5 @@ class Machine:
|
||||
logging.exception(f"Error running cmd '{cmd}'")
|
||||
raise
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config):
|
||||
return Machine(config)
|
||||
@@ -0,0 +1,281 @@
|
||||
# Octoprint API compatibility
|
||||
#
|
||||
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
|
||||
import utils
|
||||
|
||||
OCTO_VERSION = '1.5.0'
|
||||
|
||||
|
||||
class OctoprintCompat:
|
||||
"""
|
||||
Minimal implementation of the REST API as described here:
|
||||
https://docs.octoprint.org/en/master/api/index.html
|
||||
|
||||
So that Cura Octoprint plugin will function for:
|
||||
* Handshake
|
||||
* Upload gcode/ufp
|
||||
* Webcam config
|
||||
* Manual GCode submission
|
||||
* Heater temperatures
|
||||
"""
|
||||
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.software_version = config['system_args'].get('software_version')
|
||||
|
||||
# Local variables
|
||||
self.klippy_apis = None
|
||||
self.heaters = []
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
'server:klippy_ready', self._init)
|
||||
|
||||
# Version & Server information
|
||||
self.server.register_endpoint(
|
||||
'/api/version', ['GET'], self._get_version, wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/server', ['GET'], self._get_server, wrap_result=False)
|
||||
|
||||
# Login, User & Settings
|
||||
self.server.register_endpoint(
|
||||
'/api/login', ['POST'], self._post_login_user, wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/currentuser', ['GET'], self._post_login_user,
|
||||
wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/settings', ['GET'], self._get_settings, wrap_result=False)
|
||||
|
||||
# File operations
|
||||
# Note that file upload is handled in file_manager.py
|
||||
# TODO: List/info/select/delete files
|
||||
|
||||
# Job operations
|
||||
self.server.register_endpoint(
|
||||
'/api/job', ['GET'], self._get_job, wrap_result=False)
|
||||
# TODO: start/cancel/restart/pause jobs
|
||||
|
||||
# Printer operations
|
||||
self.server.register_endpoint(
|
||||
'/api/printer', ['GET'], self._get_printer, wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/printer/command', ['POST'], self._post_command,
|
||||
wrap_result=False)
|
||||
# TODO: head/tool/bed/chamber specific read/issue
|
||||
|
||||
# Printer profiles
|
||||
self.server.register_endpoint(
|
||||
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
|
||||
wrap_result=False)
|
||||
|
||||
# System
|
||||
# TODO: shutdown/reboot/restart operations
|
||||
|
||||
async def _init(self):
|
||||
self.klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
# Fetch heaters
|
||||
try:
|
||||
result = await self.klippy_apis.query_objects({'heaters': None})
|
||||
except self.server.error as e:
|
||||
logging.info(f'Error Configuring heaters: {e}')
|
||||
return
|
||||
self.heaters = result.get('heaters', {}).get('available_sensors', [])
|
||||
|
||||
async def printer_state(self):
|
||||
if not self.klippy_apis:
|
||||
return 'Offline'
|
||||
if self.server.klippy_state != 'ready':
|
||||
return 'Error'
|
||||
result = await self.klippy_apis.query_objects({'print_stats': None})
|
||||
return {
|
||||
'standby': 'Operational',
|
||||
'printing': 'Printing',
|
||||
'paused': 'Paused',
|
||||
'complete': 'Operational'
|
||||
}.get(result.get('state', 'standby'), 'Error')
|
||||
|
||||
async def printer_temps(self):
|
||||
temps = {}
|
||||
if not self.klippy_apis:
|
||||
return temps
|
||||
if self.heaters:
|
||||
result = await self.klippy_apis.query_objects(
|
||||
{heater: None for heater in self.heaters})
|
||||
for heater in self.heaters:
|
||||
if heater not in result:
|
||||
continue
|
||||
data = result[heater]
|
||||
name = 'bed'
|
||||
if heater.startswith('extruder'):
|
||||
try:
|
||||
tool_no = int(heater[8:])
|
||||
except ValueError:
|
||||
tool_no = 0
|
||||
name = f'tool{tool_no}'
|
||||
elif heater != "heater_bed":
|
||||
continue
|
||||
temps[name] = {
|
||||
'actual': round(data.get('temperature', 0.), 2),
|
||||
'offset': 0,
|
||||
'target': data.get('target', 0.),
|
||||
}
|
||||
return temps
|
||||
|
||||
async def _get_version(self, web_request):
|
||||
"""
|
||||
Version information
|
||||
"""
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'api': '0.1',
|
||||
'text': f'OctoPrint (Moonraker {self.software_version})',
|
||||
}
|
||||
|
||||
async def _get_server(self, web_request):
|
||||
"""
|
||||
Server status
|
||||
"""
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'safemode': (
|
||||
None if self.server.klippy_state == 'ready' else 'settings')
|
||||
}
|
||||
|
||||
async def _post_login_user(self, web_request):
|
||||
"""
|
||||
Confirm session login.
|
||||
|
||||
Since we only support apikey auth, do nothing.
|
||||
Report hardcoded user called _api
|
||||
"""
|
||||
return {
|
||||
'_is_external_client': False,
|
||||
'_login_mechanism': 'apikey',
|
||||
'name': '_api',
|
||||
'active': True,
|
||||
'user': True,
|
||||
'admin': True,
|
||||
'apikey': None,
|
||||
'permissions': [],
|
||||
'groups': ['admins', 'users'],
|
||||
}
|
||||
|
||||
async def _get_settings(self, web_request):
|
||||
"""
|
||||
Used to parse Octoprint capabilities
|
||||
|
||||
Hardcode capabilities to be basically there and use default
|
||||
fluid/mainsail webcam path.
|
||||
"""
|
||||
return {
|
||||
'plugins': {
|
||||
'UltimakerFormatPackage': {
|
||||
'align_inline_thumbnail': False,
|
||||
'inline_thumbnail': False,
|
||||
'inline_thumbnail_align_value': 'left',
|
||||
'inline_thumbnail_scale_value': '50',
|
||||
'installed': True,
|
||||
'installed_version': '0.2.2',
|
||||
'scale_inline_thumbnail': False,
|
||||
'state_panel_thumbnail': True,
|
||||
},
|
||||
},
|
||||
'feature': {
|
||||
'sdSupport': False,
|
||||
'temperatureGraph': False
|
||||
},
|
||||
# TODO: Get webcam settings from config file to allow user
|
||||
# to customise this.
|
||||
'webcam': {
|
||||
'flipH': False,
|
||||
'flipV': False,
|
||||
'rotate90': False,
|
||||
'streamUrl': '/webcam/?action=stream',
|
||||
'webcamEnabled': True,
|
||||
},
|
||||
}
|
||||
|
||||
async def _get_job(self, web_request):
|
||||
"""
|
||||
Get current job status
|
||||
"""
|
||||
return {
|
||||
'job': {
|
||||
'file': {'name': None},
|
||||
'estimatedPrintTime': None,
|
||||
'filament': {'length': None},
|
||||
'user': None,
|
||||
},
|
||||
'progress': {
|
||||
'completion': None,
|
||||
'filepos': None,
|
||||
'printTime': None,
|
||||
'printTimeLeft': None,
|
||||
'printTimeOrigin': None,
|
||||
},
|
||||
'state': await self.printer_state()
|
||||
}
|
||||
|
||||
async def _get_printer(self, web_request):
|
||||
"""
|
||||
Get Printer status
|
||||
"""
|
||||
state = await self.printer_state()
|
||||
return {
|
||||
'temperature': await self.printer_temps(),
|
||||
'state': {
|
||||
'text': state,
|
||||
'flags': {
|
||||
'operational': state not in ['Error', 'Offline'],
|
||||
'paused': state == 'Paused',
|
||||
'printing': state == 'Printing',
|
||||
'cancelling': state == 'Cancelling',
|
||||
'pausing': False,
|
||||
'error': state == 'Error',
|
||||
'ready': state == 'Operational',
|
||||
'closedOrError': state in ['Error', 'Offline'],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
async def _post_command(self, web_request):
|
||||
"""
|
||||
Request to run some gcode command
|
||||
"""
|
||||
commands = web_request.get('commands', [])
|
||||
for command in commands:
|
||||
logging.info(f'Executing GCode: {command}')
|
||||
try:
|
||||
await self.klippy_apis.run_gcode(command)
|
||||
except self.server.error:
|
||||
msg = f"Error executing GCode {command}"
|
||||
logging.exception(msg)
|
||||
|
||||
return {}
|
||||
|
||||
async def _get_printerprofiles(self, web_request):
|
||||
"""
|
||||
Get Printer profiles
|
||||
"""
|
||||
return {
|
||||
'profiles': {
|
||||
'_default': {
|
||||
'id': '_default',
|
||||
'name': 'Default',
|
||||
'color': 'default',
|
||||
'model': 'Default',
|
||||
'default': True,
|
||||
'current': True,
|
||||
'heatedBed': 'heater_bed' in self.heaters,
|
||||
'heatedChamber': 'chamber' in self.heaters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def load_component(config):
|
||||
return OctoprintCompat(config)
|
||||
@@ -9,13 +9,14 @@ import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from utils import ServerError
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.locks import Lock
|
||||
|
||||
MIN_EST_TIME = 10.
|
||||
INITIALIZE_TIMEOUT = 10.
|
||||
|
||||
class PanelDueError(ServerError):
|
||||
pass
|
||||
@@ -29,13 +30,15 @@ class SerialConnection:
|
||||
self.paneldue = paneldue
|
||||
self.port = config.get('serial')
|
||||
self.baud = config.getint('baud', 57600)
|
||||
self.sendlock = Lock()
|
||||
self.partial_input = b""
|
||||
self.ser = self.fd = None
|
||||
self.connected = False
|
||||
self.send_busy = False
|
||||
self.send_buffer = b""
|
||||
self.attempting_connect = True
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
|
||||
def disconnect(self):
|
||||
def disconnect(self, reconnect=False):
|
||||
if self.connected:
|
||||
if self.fd is not None:
|
||||
self.ioloop.remove_handler(self.fd)
|
||||
@@ -43,7 +46,13 @@ class SerialConnection:
|
||||
self.connected = False
|
||||
self.ser.close()
|
||||
self.ser = None
|
||||
self.partial_input = b""
|
||||
self.send_buffer = b""
|
||||
self.paneldue.initialized = False
|
||||
logging.info("PanelDue Disconnected")
|
||||
if reconnect and not self.attempting_connect:
|
||||
self.attempting_connect = True
|
||||
self.ioloop.call_later(1., self._connect)
|
||||
|
||||
async def _connect(self):
|
||||
start_time = connect_time = time.time()
|
||||
@@ -69,11 +78,12 @@ class SerialConnection:
|
||||
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
|
||||
self.connected = True
|
||||
logging.info("PanelDue Connected")
|
||||
self.attempting_connect = False
|
||||
|
||||
def _handle_incoming(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
logging.info("PanelDue Connection Error")
|
||||
self.disconnect()
|
||||
self.disconnect(reconnect=True)
|
||||
return
|
||||
# Process incoming data using same method as gcode.py
|
||||
try:
|
||||
@@ -83,57 +93,60 @@ class SerialConnection:
|
||||
|
||||
if not data:
|
||||
# possibly an error, disconnect
|
||||
self.disconnect()
|
||||
self.disconnect(reconnect=True)
|
||||
logging.info("serial_display: No data received, disconnecting")
|
||||
return
|
||||
self.ioloop.spawn_callback(self._process_data, data)
|
||||
|
||||
async def _process_data(self, data):
|
||||
# Remove null bytes, separate into lines
|
||||
data = data.strip(b'\x00')
|
||||
lines = data.split(b'\n')
|
||||
lines[0] = self.partial_input + lines[0]
|
||||
self.partial_input = lines.pop()
|
||||
for line in lines:
|
||||
line = line.strip().decode()
|
||||
try:
|
||||
await self.paneldue.process_line(line)
|
||||
line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(line)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
"GCode Processing Error: " + line)
|
||||
f"GCode Processing Error: {line}")
|
||||
self.paneldue.handle_gcode_response(
|
||||
"!! GCode Processing Error: " + line)
|
||||
f"!! GCode Processing Error: {line}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
|
||||
async def send(self, data):
|
||||
if self.connected:
|
||||
async with self.sendlock:
|
||||
while data:
|
||||
try:
|
||||
sent = os.write(self.fd, data)
|
||||
except os.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
|
||||
sent = 0
|
||||
else:
|
||||
await gen.sleep(.001)
|
||||
continue
|
||||
if sent:
|
||||
data = data[sent:]
|
||||
else:
|
||||
logging.exception(
|
||||
"Error writing data, closing serial connection")
|
||||
self.disconnect()
|
||||
return
|
||||
def send(self, data):
|
||||
self.send_buffer += data
|
||||
if not self.send_busy:
|
||||
self.send_busy = True
|
||||
self.ioloop.spawn_callback(self._do_send)
|
||||
|
||||
async def _do_send(self):
|
||||
while self.send_buffer:
|
||||
if not self.connected:
|
||||
break
|
||||
try:
|
||||
sent = os.write(self.fd, self.send_buffer)
|
||||
except os.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
|
||||
sent = 0
|
||||
else:
|
||||
await gen.sleep(.001)
|
||||
continue
|
||||
if sent:
|
||||
self.send_buffer = self.send_buffer[sent:]
|
||||
else:
|
||||
logging.exception(
|
||||
"Error writing data, closing serial connection")
|
||||
self.disconnect(reconnect=True)
|
||||
return
|
||||
self.send_busy = False
|
||||
|
||||
class PanelDue:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.ser_conn = SerialConnection(config, self)
|
||||
self.file_manager = self.server.lookup_plugin('file_manager')
|
||||
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
self.file_manager = self.server.lookup_component('file_manager')
|
||||
self.klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
self.kinematics = "none"
|
||||
self.machine_name = config.get('machine_name', "Klipper")
|
||||
self.firmware_name = "Repetier | Klipper"
|
||||
@@ -153,7 +166,12 @@ class PanelDue:
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
self.last_printer_state = 'C'
|
||||
self.initialized = False
|
||||
self.cq_busy = self.gq_busy = False
|
||||
self.command_queue = []
|
||||
self.gc_queue = []
|
||||
self.last_printer_state = 'O'
|
||||
self.last_update_time = 0.
|
||||
|
||||
# Set up macros
|
||||
self.confirmed_gcode = ""
|
||||
@@ -178,6 +196,7 @@ class PanelDue:
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
|
||||
self.ser_conn = SerialConnection(config, self)
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
# Register server events
|
||||
@@ -277,31 +296,32 @@ class PanelDue:
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
async def _process_klippy_shutdown(self):
|
||||
def _process_klippy_shutdown(self):
|
||||
self.is_shutdown = True
|
||||
|
||||
async def _process_klippy_disconnect(self):
|
||||
# Tell the PD that we are shutting down
|
||||
await self.write_response({'status': 'S'})
|
||||
self.is_ready = False
|
||||
def _process_klippy_disconnect(self):
|
||||
# Tell the PD that the printer is "off"
|
||||
self.write_response({'status': 'O'})
|
||||
self.last_printer_state = 'O'
|
||||
self.is_shutdown = self.is_shutdown = False
|
||||
|
||||
async def handle_status_update(self, status):
|
||||
def handle_status_update(self, status):
|
||||
for obj, items in status.items():
|
||||
if obj in self.printer_state:
|
||||
self.printer_state[obj].update(items)
|
||||
else:
|
||||
self.printer_state[obj] = items
|
||||
|
||||
async def paneldue_beep(self, frequency, duration):
|
||||
def paneldue_beep(self, frequency, duration):
|
||||
duration = int(duration * 1000.)
|
||||
await self.write_response(
|
||||
self.write_response(
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
async def process_line(self, line):
|
||||
def process_line(self, line):
|
||||
self.debug_queue.append(line)
|
||||
# If we find M112 in the line then skip verification
|
||||
if "M112" in line.upper():
|
||||
await self.klippy_apis.emergency_stop()
|
||||
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
|
||||
return
|
||||
|
||||
if self.enable_checksum:
|
||||
@@ -337,31 +357,36 @@ class PanelDue:
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
await self._run_gcode(line[line_index+1:cs_index])
|
||||
script = line[line_index+1:cs_index]
|
||||
else:
|
||||
await self._run_gcode(line)
|
||||
|
||||
async def _run_gcode(self, script):
|
||||
script = line
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
# require special handling
|
||||
parts = script.split()
|
||||
cmd = parts[0].strip()
|
||||
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
|
||||
arg = script[len(cmd):].strip()
|
||||
parts = [cmd, arg]
|
||||
|
||||
# Check for commands that query state and require immediate response
|
||||
if cmd in self.direct_gcodes:
|
||||
params = {}
|
||||
for p in parts[1:]:
|
||||
arg = p[0].lower() if p[0].lower() in "psr" else "p"
|
||||
if p[0] not in "PSR":
|
||||
params["arg_p"] = p.strip(" \"\t\n")
|
||||
continue
|
||||
arg = p[0].lower()
|
||||
try:
|
||||
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
|
||||
val = int(p[1:].strip()) if arg in "sr" \
|
||||
else p[1:].strip(" \"\t\n")
|
||||
except Exception:
|
||||
msg = f"paneldue: Error parsing direct gcode {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
return
|
||||
params["arg_" + arg] = val
|
||||
params[f"arg_{arg}"] = val
|
||||
func = self.direct_gcodes[cmd]
|
||||
await func(**params)
|
||||
self.queue_command(func, **params)
|
||||
return
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
@@ -371,18 +396,48 @@ class PanelDue:
|
||||
|
||||
if not script:
|
||||
return
|
||||
elif script in RESTART_GCODES:
|
||||
await self.klippy_apis.do_restart(script)
|
||||
return
|
||||
self.queue_gcode(script)
|
||||
|
||||
try:
|
||||
await self.klippy_apis.run_gcode(script)
|
||||
except self.server.error:
|
||||
msg = f"Error executing script {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
def queue_gcode(self, script):
|
||||
self.gc_queue.append(script)
|
||||
if not self.gq_busy:
|
||||
self.gq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_gcode_queue)
|
||||
|
||||
async def _process_gcode_queue(self):
|
||||
while self.gc_queue:
|
||||
script = self.gc_queue.pop(0)
|
||||
try:
|
||||
if script in RESTART_GCODES:
|
||||
await self.klippy_apis.do_restart(script)
|
||||
else:
|
||||
await self.klippy_apis.run_gcode(script)
|
||||
except self.server.error:
|
||||
msg = f"Error executing script {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
self.gq_busy = False
|
||||
|
||||
def queue_command(self, cmd, *args, **kwargs):
|
||||
self.command_queue.append((cmd, args, kwargs))
|
||||
if not self.cq_busy:
|
||||
self.cq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_command_queue)
|
||||
|
||||
async def _process_command_queue(self):
|
||||
while self.command_queue:
|
||||
cmd, args, kwargs = self.command_queue.pop(0)
|
||||
try:
|
||||
ret = cmd(*args, **kwargs)
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception("Error processing command")
|
||||
self.cq_busy = False
|
||||
|
||||
def _clean_filename(self, filename):
|
||||
# Remove quotes and whitespace
|
||||
filename.strip(" \"\t\n")
|
||||
# Remove drive number
|
||||
if filename.startswith("0:/"):
|
||||
filename = filename[3:]
|
||||
@@ -399,15 +454,17 @@ class PanelDue:
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "M23 " + filename
|
||||
filename = self._clean_filename(args[0])
|
||||
return f"M23 {filename}"
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "SDCARD_PRINT_FILE FILENAME=" + filename
|
||||
filename = self._clean_filename(args[0])
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
|
||||
|
||||
def _prepare_M98(self, args):
|
||||
macro = args[0][1:].strip()
|
||||
macro = args[0][1:].strip(" \"\t\n")
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
cmd = self.available_macros.get(macro)
|
||||
@@ -444,7 +501,8 @@ class PanelDue:
|
||||
mbox['msgBox.title'] = title
|
||||
mbox['msgBox.controls'] = 0
|
||||
mbox['msgBox.timeout'] = 0
|
||||
self.ioloop.spawn_callback(self.write_response, mbox)
|
||||
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
|
||||
self.write_response(mbox)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
@@ -458,9 +516,9 @@ class PanelDue:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
async def write_response(self, response):
|
||||
def write_response(self, response):
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
await self.ser_conn.send(byte_resp.encode())
|
||||
self.ser_conn.send(byte_resp.encode())
|
||||
|
||||
def _get_printer_status(self):
|
||||
# PanelDue States applicable to Klipper:
|
||||
@@ -471,8 +529,6 @@ class PanelDue:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
p_busy = printer_state['idle_timeout'].get(
|
||||
'state', 'Idle') == "Printing"
|
||||
sd_state = printer_state['print_stats'].get('state', "standby")
|
||||
if sd_state == "printing":
|
||||
if self.last_printer_state == 'A':
|
||||
@@ -481,37 +537,41 @@ class PanelDue:
|
||||
# Printing
|
||||
return 'P'
|
||||
elif sd_state == "paused":
|
||||
if p_busy and self.last_printer_state != 'A':
|
||||
p_active = printer_state['idle_timeout'].get(
|
||||
'state', 'Idle') == "Printing"
|
||||
if p_active and self.last_printer_state != 'A':
|
||||
# Pausing
|
||||
return 'D'
|
||||
else:
|
||||
# Paused
|
||||
return 'A'
|
||||
|
||||
if p_busy:
|
||||
# Printer is "busy"
|
||||
return 'B'
|
||||
|
||||
return 'I'
|
||||
|
||||
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
response = {}
|
||||
sequence = arg_r
|
||||
response_type = arg_s
|
||||
|
||||
if not self.is_ready:
|
||||
# Klipper is still starting up, do not query status
|
||||
self.last_printer_state = 'S' if self.is_shutdown else 'C'
|
||||
response['status'] = self.last_printer_state
|
||||
await self.write_response(response)
|
||||
return
|
||||
curtime = self.ioloop.time()
|
||||
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
|
||||
self.initialized = False
|
||||
self.last_update_time = curtime
|
||||
|
||||
# Send gcode responses
|
||||
if not self.initialized:
|
||||
response['dir'] = "/macros"
|
||||
response['files'] = list(self.available_macros.keys())
|
||||
self.initialized = True
|
||||
if not self.is_ready:
|
||||
self.last_printer_state = 'O'
|
||||
response['status'] = self.last_printer_state
|
||||
self.write_response(response)
|
||||
return
|
||||
if sequence is not None and self.last_gcode_response:
|
||||
# Send gcode responses
|
||||
response['seq'] = sequence + 1
|
||||
response['resp'] = self.last_gcode_response
|
||||
self.last_gcode_response = None
|
||||
|
||||
if response_type == 1:
|
||||
# Extended response Request
|
||||
response['myName'] = self.machine_name
|
||||
@@ -611,9 +671,9 @@ class PanelDue:
|
||||
# is strange about this, and displays it as a full screen
|
||||
# notification
|
||||
self.last_message = msg
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
@@ -651,7 +711,7 @@ class PanelDue:
|
||||
flist = self.file_manager.list_dir(path, simple_format=True)
|
||||
if flist:
|
||||
response['files'] = flist
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p=None):
|
||||
# Delete a file. Clean up the file name and make sure
|
||||
@@ -667,7 +727,7 @@ class PanelDue:
|
||||
path = "gcodes/" + path
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
async def _run_paneldue_M36(self, arg_p=None):
|
||||
def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
@@ -682,16 +742,17 @@ class PanelDue:
|
||||
if not filename or not active:
|
||||
# Either no file printing or no virtual_sdcard
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
return
|
||||
else:
|
||||
response['fileName'] = filename.split("/")[-1]
|
||||
|
||||
|
||||
# For consistency make sure that the filename begins with the
|
||||
# "gcodes/" root. The M20 HACK should add this in some cases.
|
||||
# Ideally we would add support to the PanelDue firmware that
|
||||
# indicates Moonraker supports a "gcodes" directory.
|
||||
if filename[0] == "/":
|
||||
filename = filename[1:]
|
||||
if not filename.startswith("gcodes/"):
|
||||
filename = "gcodes/" + filename
|
||||
|
||||
@@ -718,14 +779,14 @@ class PanelDue:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
self.write_response(response)
|
||||
|
||||
async def close(self):
|
||||
def close(self):
|
||||
self.ser_conn.disconnect()
|
||||
msg = "\nPanelDue GCode Dump:"
|
||||
for i, gc in enumerate(self.debug_queue):
|
||||
msg += f"\nSequence {i}: {gc}"
|
||||
logging.debug(msg)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config):
|
||||
return PanelDue(config)
|
||||
@@ -20,6 +20,31 @@ from tornado.escape import json_decode
|
||||
class PrinterPower:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.chip_factory = GpioChipFactory()
|
||||
self.devices = {}
|
||||
prefix_sections = config.get_prefix_sections("power")
|
||||
logging.info(f"Power component loading devices: {prefix_sections}")
|
||||
try:
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
dev_type = cfg.get("type")
|
||||
if dev_type == "gpio":
|
||||
dev = GpioDevice(cfg, self.chip_factory)
|
||||
elif dev_type == "tplink_smartplug":
|
||||
dev = TPLinkSmartPlug(cfg)
|
||||
elif dev_type == "tasmota":
|
||||
dev = Tasmota(cfg)
|
||||
elif dev_type == "shelly":
|
||||
dev = Shelly(cfg)
|
||||
elif dev_type == "homeseer":
|
||||
dev = HomeSeer(cfg)
|
||||
else:
|
||||
raise config.error(f"Unsupported Device Type: {dev_type}")
|
||||
self.devices[dev.get_name()] = dev
|
||||
except Exception:
|
||||
self.chip_factory.close()
|
||||
raise
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/devices", ['GET'],
|
||||
self._handle_list_devices)
|
||||
@@ -34,24 +59,33 @@ class PrinterPower:
|
||||
self._handle_power_request)
|
||||
self.server.register_remote_method(
|
||||
"set_device_power", self.set_device_power)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_klippy_shutdown)
|
||||
self.server.register_notification("power:power_changed")
|
||||
IOLoop.current().spawn_callback(
|
||||
self._initalize_devices, list(self.devices.values()))
|
||||
|
||||
self.chip_factory = GpioChipFactory()
|
||||
self.current_dev = None
|
||||
self.devices = {}
|
||||
prefix_sections = config.get_prefix_sections("power")
|
||||
logging.info(f"Power plugin loading devices: {prefix_sections}")
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
dev_type = cfg.get("type")
|
||||
if dev_type == "gpio":
|
||||
dev = GpioDevice(cfg, self.chip_factory)
|
||||
elif dev_type == "tplink_smartplug":
|
||||
dev = TPLinkSmartPlug(cfg)
|
||||
elif dev_type == "tasmota":
|
||||
dev = Tasmota(cfg)
|
||||
else:
|
||||
raise config.error(f"Unsupported Device Type: {dev_type}")
|
||||
self.devices[dev.get_name()] = dev
|
||||
async def _check_klippy_printing(self):
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
result = await klippy_apis.query_objects(
|
||||
{'print_stats': None}, default={})
|
||||
pstate = result.get('print_stats', {}).get('state', "").lower()
|
||||
return pstate == "printing"
|
||||
|
||||
async def _initalize_devices(self, inital_devs):
|
||||
for dev in inital_devs:
|
||||
ret = dev.initialize()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
|
||||
async def _handle_klippy_shutdown(self):
|
||||
for name, dev in self.devices.items():
|
||||
if hasattr(dev, "off_when_shutdown"):
|
||||
if dev.off_when_shutdown:
|
||||
logging.info(
|
||||
f"Powering off device [{name}] due to"
|
||||
" klippy shutdown")
|
||||
await self._process_request(dev, "off")
|
||||
|
||||
async def _handle_list_devices(self, web_request):
|
||||
dev_list = [d.get_device_info() for d in self.devices.values()]
|
||||
@@ -75,11 +109,21 @@ class PrinterPower:
|
||||
|
||||
async def _process_request(self, device, req):
|
||||
if req in ["on", "off"]:
|
||||
cur_state = device.get_device_info()['status']
|
||||
if req == cur_state:
|
||||
# device is already in requested state, do nothing
|
||||
return cur_state
|
||||
printing = await self._check_klippy_printing()
|
||||
if device.get_locked_while_printing() and printing:
|
||||
raise self.server.error(
|
||||
f"Unable to change power for {device.get_name()} "
|
||||
"while printing")
|
||||
ret = device.set_power(req)
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
dev_info = device.get_device_info()
|
||||
self.server.send_event("gpio_power:power_changed", dev_info)
|
||||
self.server.send_event("power:power_changed", dev_info)
|
||||
device.run_power_changed_action()
|
||||
elif req == "status":
|
||||
ret = device.refresh_status()
|
||||
if asyncio.iscoroutine(ret):
|
||||
@@ -125,6 +169,45 @@ class PrinterPower:
|
||||
self.chip_factory.close()
|
||||
|
||||
|
||||
class PowerDevice:
|
||||
def __init__(self, config):
|
||||
name_parts = config.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise config.error(f"Invalid Section Name: {config.get_name()}")
|
||||
self.server = config.get_server()
|
||||
self.name = name_parts[1]
|
||||
self.state = "init"
|
||||
self.locked_while_printing = config.getboolean(
|
||||
'locked_while_printing', False)
|
||||
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
|
||||
self.restart_delay = 1.
|
||||
self.klipper_restart = config.getboolean(
|
||||
'restart_klipper_when_powered', False)
|
||||
if self.klipper_restart:
|
||||
self.restart_delay = config.getfloat('restart_delay', 1.)
|
||||
if self.restart_delay < .000001:
|
||||
raise config.error("Option 'restart_delay' must be above 0.0")
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'locked_while_printing': self.locked_while_printing
|
||||
}
|
||||
|
||||
def get_locked_while_printing(self):
|
||||
return self.locked_while_printing
|
||||
|
||||
def run_power_changed_action(self):
|
||||
if self.state == "on" and self.klipper_restart:
|
||||
ioloop = IOLoop.current()
|
||||
klippy_apis = self.server.lookup_component("klippy_apis")
|
||||
ioloop.call_later(self.restart_delay, klippy_apis.do_restart,
|
||||
"FIRMWARE_RESTART")
|
||||
|
||||
class GpioChipFactory:
|
||||
def __init__(self):
|
||||
self.chips = {}
|
||||
@@ -140,13 +223,9 @@ class GpioChipFactory:
|
||||
for chip in self.chips.values():
|
||||
chip.close()
|
||||
|
||||
class GpioDevice:
|
||||
class GpioDevice(PowerDevice):
|
||||
def __init__(self, config, chip_factory):
|
||||
name_parts = config.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise config.error(f"Invalid Section Name: {config.get_name()}")
|
||||
self.name = name_parts[1]
|
||||
self.state = "init"
|
||||
super().__init__(config)
|
||||
pin, chip_id, invert = self._parse_pin(config)
|
||||
try:
|
||||
chip = chip_factory.get_gpio_chip(chip_id)
|
||||
@@ -164,7 +243,7 @@ class GpioDevice:
|
||||
f"Unable to init {pin}. Make sure the gpio is not in "
|
||||
"use by another program or exported by sysfs.")
|
||||
raise config.error("Power GPIO Config Error")
|
||||
self.set_power("off")
|
||||
self.initial_state = config.getboolean('initial_state', False)
|
||||
|
||||
def _parse_pin(self, config):
|
||||
pin = cfg_pin = config.get("pin")
|
||||
@@ -189,15 +268,11 @@ class GpioDevice:
|
||||
return pin, chip_id, invert
|
||||
|
||||
def initialize(self):
|
||||
pass
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
self.set_power("on" if self.initial_state else "off")
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
**super().get_device_info(),
|
||||
'type': "gpio"
|
||||
}
|
||||
|
||||
@@ -231,18 +306,13 @@ class GpioDevice:
|
||||
# https://github.com/softScheck/tplink-smartplug
|
||||
#
|
||||
# Copyright 2016 softScheck GmbH
|
||||
class TPLinkSmartPlug:
|
||||
class TPLinkSmartPlug(PowerDevice):
|
||||
START_KEY = 0xAB
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.server = config.get_server()
|
||||
self.addr = config.get("address")
|
||||
self.port = config.getint("port", 9999)
|
||||
name_parts = config.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise config.error(f"Invalid Section Name: {config.get_name()}")
|
||||
self.name = name_parts[1]
|
||||
self.state = "init"
|
||||
IOLoop.current().spawn_callback(self.initialize)
|
||||
|
||||
async def _send_tplink_command(self, command):
|
||||
out_cmd = {}
|
||||
@@ -299,13 +369,9 @@ class TPLinkSmartPlug:
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
**super().get_device_info(),
|
||||
'type': "tplink_smartplug"
|
||||
}
|
||||
|
||||
@@ -334,28 +400,24 @@ class TPLinkSmartPlug:
|
||||
self.state = state
|
||||
|
||||
|
||||
class Tasmota:
|
||||
class Tasmota(PowerDevice):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.server = config.get_server()
|
||||
self.addr = config.get("address")
|
||||
self.output_id = config.getint("output_id", 1)
|
||||
self.password = config.get("password", "")
|
||||
name_parts = config.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise config.error(f"Invalid Section Name: {config.get_name()}")
|
||||
self.name = name_parts[1]
|
||||
self.state = "init"
|
||||
IOLoop.current().spawn_callback(self.initialize)
|
||||
|
||||
async def _send_tasmota_command(self, command, password=None):
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = f"Power{self.output_id}%20{command}"
|
||||
elif command == "info":
|
||||
out_cmd = "Power{self.output_id}"
|
||||
out_cmd = f"Power{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid tasmota command: {command}")
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
|
||||
|
||||
url = f"http://{self.addr}/cm?user=admin&password=" \
|
||||
f"{self.password}&cmnd={out_cmd}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
@@ -370,13 +432,9 @@ class Tasmota:
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
**super().get_device_info(),
|
||||
'type': "tasmota"
|
||||
}
|
||||
|
||||
@@ -402,6 +460,129 @@ class Tasmota:
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
# The power plugin has multiple configuration sections
|
||||
def load_plugin_multi(config):
|
||||
|
||||
class Shelly(PowerDevice):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.server = config.get_server()
|
||||
self.addr = config.get("address")
|
||||
self.output_id = config.getint("output_id", 0)
|
||||
self.user = config.get("user", "admin")
|
||||
self.password = config.get("password", "")
|
||||
|
||||
async def _send_shelly_command(self, command):
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = f"relay/{self.output_id}?turn={command}"
|
||||
elif command == "info":
|
||||
out_cmd = f"relay/{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid shelly command: {command}")
|
||||
if self.password != "":
|
||||
out_pwd = f"{self.user}:{self.password}@"
|
||||
else:
|
||||
out_pwd = f""
|
||||
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
response = await http_client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending shelly command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
**super().get_device_info(),
|
||||
'type': "shelly"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_shelly_command("info")
|
||||
state = res[f"ison"]
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_shelly_command(state)
|
||||
state = res[f"ison"]
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Setting Device Status: {self.name} to {state}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
class HomeSeer(PowerDevice):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.server = config.get_server()
|
||||
self.addr = config.get("address")
|
||||
self.device = config.getint("device")
|
||||
self.user = config.get("user", "admin")
|
||||
self.password = config.get("password", "")
|
||||
|
||||
async def _send_homeseer(self, request, additional=""):
|
||||
url = (f"http://{self.user}:{self.password}@{self.addr}"
|
||||
f"/JSON?user={self.user}&pass={self.password}"
|
||||
f"&request={request}&ref={self.device}&{additional}")
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
response = await http_client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending HomeSeer command: {request}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def initialize(self):
|
||||
await self.refresh_status()
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
**super().get_device_info(),
|
||||
'type': "homeseer"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_homeseer("getstatus")
|
||||
state = res[f"Devices"][0]["status"].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:
|
||||
if state == "on":
|
||||
state_hs = "On"
|
||||
elif state == "off":
|
||||
state_hs = "Off"
|
||||
res = await self._send_homeseer("controldevicebylabel",
|
||||
f"label={state_hs}")
|
||||
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 component has multiple configuration sections
|
||||
def load_component_multi(config):
|
||||
return PrinterPower(config)
|
||||
@@ -0,0 +1,137 @@
|
||||
# Moonraker Process Stat Tracking
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import time
|
||||
import re
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
|
||||
STATM_FILE_PATH = "/proc/self/smaps_rollup"
|
||||
STAT_UPDATE_TIME_MS = 1000
|
||||
REPORT_QUEUE_SIZE = 30
|
||||
THROTTLE_CHECK_INTERVAL = 10
|
||||
|
||||
THROTTLED_FLAGS = {
|
||||
1: "Under-Voltage Detected",
|
||||
1 << 1: "Frequency Capped",
|
||||
1 << 2: "Currently Throttled",
|
||||
1 << 3: "Temperature Limit Active",
|
||||
1 << 16: "Previously Under-Volted",
|
||||
1 << 17: "Previously Frequency Capped",
|
||||
1 << 18: "Previously Throttled",
|
||||
1 << 19: "Previously Temperature Limited"
|
||||
}
|
||||
|
||||
class ProcStats:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.stat_update_cb = PeriodicCallback(
|
||||
self._handle_stat_update, STAT_UPDATE_TIME_MS)
|
||||
self.vcgencmd = None
|
||||
if os.path.exists(VC_GEN_CMD_FILE):
|
||||
logging.info("Detected 'vcgencmd', throttle checking enabled")
|
||||
shell_command = self.server.load_component(config, "shell_command")
|
||||
self.vcgencmd = shell_command.build_shell_command(
|
||||
"vcgencmd get_throttled")
|
||||
self.server.register_notification("proc_stats:cpu_throttled")
|
||||
else:
|
||||
logging.info("Unable to find 'vcgencmd', throttle checking "
|
||||
"disabled")
|
||||
self.smaps = pathlib.Path(STATM_FILE_PATH)
|
||||
self.server.register_endpoint(
|
||||
"/machine/proc_stats", ["GET"], self._handle_stat_request)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_shutdown)
|
||||
self.proc_stat_queue = deque(maxlen=30)
|
||||
self.last_update_time = time.time()
|
||||
self.last_proc_time = time.process_time()
|
||||
self.throttled = False
|
||||
self.update_sequence = 0
|
||||
self.stat_update_cb.start()
|
||||
|
||||
async def _handle_stat_request(self, web_request):
|
||||
ts = None
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
return {
|
||||
'moonraker_stats': list(self.proc_stat_queue),
|
||||
'throttled_state': ts
|
||||
}
|
||||
|
||||
async def _handle_shutdown(self):
|
||||
msg = "\nMoonraker System Usage Statistics:"
|
||||
for stats in self.proc_stat_queue:
|
||||
msg += f"\n{self._format_stats(stats)}"
|
||||
logging.info(msg)
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
logging.info(f"Throttled Flags: {' '.join(ts['flags'])}")
|
||||
|
||||
async def _handle_stat_update(self):
|
||||
update_time = time.time()
|
||||
proc_time = time.process_time()
|
||||
time_diff = update_time - self.last_update_time
|
||||
usage = round((proc_time - self.last_proc_time) / time_diff * 100, 2)
|
||||
mem, mem_units = self._get_memory_usage()
|
||||
self.proc_stat_queue.append({
|
||||
"time": update_time,
|
||||
"cpu_usage": usage,
|
||||
"memory": mem,
|
||||
"mem_units": mem_units
|
||||
})
|
||||
self.last_update_time = update_time
|
||||
self.last_proc_time = proc_time
|
||||
self.update_sequence += 1
|
||||
if self.update_sequence == THROTTLE_CHECK_INTERVAL:
|
||||
self.update_sequence = 0
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
cur_throttled = ts['bits'] & 0xF
|
||||
if cur_throttled and not self.throttled:
|
||||
logging.info(
|
||||
f"CPU Throttled State Detected: {ts['flags']}")
|
||||
self.server.send_event("proc_stats:cpu_throttled", ts)
|
||||
self.throttled = cur_throttled
|
||||
|
||||
async def _check_throttled_state(self):
|
||||
try:
|
||||
resp = await self.vcgencmd.run_with_response(
|
||||
timeout=.5, log_complete=False)
|
||||
ts = int(resp.strip().split("=")[-1], 16)
|
||||
except Exception:
|
||||
return {'bits': 0, 'flags': ["?"]}
|
||||
flags = []
|
||||
for flag, desc in THROTTLED_FLAGS.items():
|
||||
if flag & ts:
|
||||
flags.append(desc)
|
||||
return {'bits': ts, 'flags': flags}
|
||||
|
||||
def _get_memory_usage(self):
|
||||
try:
|
||||
mem_data = self.smaps.read_text()
|
||||
rss_match = re.search(r"Rss:\s+(\d+)\s+(\w+)", mem_data)
|
||||
if rss_match is None:
|
||||
return None, None
|
||||
mem = int(rss_match.group(1))
|
||||
units = rss_match.group(2)
|
||||
except Exception:
|
||||
return None, None
|
||||
return mem, units
|
||||
|
||||
def _format_stats(self, stats):
|
||||
return f"System Time: {stats['time']:2f}, " \
|
||||
f"Usage: {stats['cpu_usage']}%, " \
|
||||
f"Memory: {stats['memory']} {stats['mem_units']}"
|
||||
|
||||
def close(self):
|
||||
self.stat_update_cb.stop()
|
||||
|
||||
def load_component(config):
|
||||
return ProcStats(config)
|
||||
@@ -0,0 +1,227 @@
|
||||
# linux shell command execution utility
|
||||
#
|
||||
# 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 shlex
|
||||
import logging
|
||||
import signal
|
||||
import asyncio
|
||||
from tornado import gen
|
||||
from utils import ServerError
|
||||
|
||||
class ShellCommandError(ServerError):
|
||||
def __init__(self, message, return_code, stdout=b"",
|
||||
stderr=b"", status_code=500):
|
||||
super().__init__(message, status_code=status_code)
|
||||
self.stdout = stdout or b""
|
||||
self.stderr = stderr or b""
|
||||
self.return_code = return_code
|
||||
|
||||
class SCProcess(asyncio.subprocess.Process):
|
||||
def initialize(self, program_name, std_out_cb, std_err_cb, log_stderr):
|
||||
self.program_name = program_name
|
||||
self.std_out_cb = std_out_cb
|
||||
self.std_err_cb = std_err_cb
|
||||
self.log_stderr = log_stderr
|
||||
self.cancel_requested = False
|
||||
|
||||
async def _read_stream_with_cb(self, fd):
|
||||
transport = self._transport.get_pipe_transport(fd)
|
||||
if fd == 2:
|
||||
stream = self.stderr
|
||||
cb = self.std_err_cb
|
||||
else:
|
||||
assert fd == 1
|
||||
stream = self.stdout
|
||||
cb = self.std_out_cb
|
||||
while not stream.at_eof():
|
||||
output = await stream.readline()
|
||||
if not output:
|
||||
break
|
||||
if fd == 2 and self.log_stderr:
|
||||
logging.info(f"{self.program_name}: {output.decode()}")
|
||||
output = output.rstrip(b'\n')
|
||||
if output and cb is not None:
|
||||
cb(output)
|
||||
transport.close()
|
||||
return output
|
||||
|
||||
async def cancel(self, sig_idx=1):
|
||||
if self.cancel_requested:
|
||||
return
|
||||
self.cancel_requested = True
|
||||
exit_success = False
|
||||
sig_idx = min(2, max(0, sig_idx))
|
||||
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
|
||||
for sig in sigs:
|
||||
self.send_signal(sig)
|
||||
try:
|
||||
ret = self.wait()
|
||||
await asyncio.wait_for(ret, timeout=2.)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
logging.debug(f"Command '{self.program_name}' exited with "
|
||||
f"signal: {sig.name}")
|
||||
exit_success = True
|
||||
break
|
||||
if not exit_success:
|
||||
logging.info(f"WARNING: {self.program_name} did not cleanly exit")
|
||||
if self.stdout is not None:
|
||||
self.stdout.feed_eof()
|
||||
if self.stderr is not None:
|
||||
self.stderr.feed_eof()
|
||||
|
||||
async def communicate_with_cb(self, input=None):
|
||||
if input is not None:
|
||||
stdin = self._feed_stdin(input)
|
||||
else:
|
||||
stdin = self._noop()
|
||||
if self.stdout is not None and self.std_out_cb is not None:
|
||||
stdout = self._read_stream_with_cb(1)
|
||||
else:
|
||||
stdout = self._noop()
|
||||
has_err_output = self.std_err_cb is not None or self.log_stderr
|
||||
if self.stderr is not None and has_err_output:
|
||||
stderr = self._read_stream_with_cb(2)
|
||||
else:
|
||||
stderr = self._noop()
|
||||
stdin, stdout, stderr = await asyncio.tasks.gather(
|
||||
stdin, stdout, stderr, loop=self._loop)
|
||||
await self.wait()
|
||||
|
||||
class ShellCommand:
|
||||
IDX_SIGINT = 0
|
||||
IDX_SIGTERM = 1
|
||||
IDX_SIGKILL_= 2
|
||||
def __init__(self, cmd, std_out_callback, std_err_callback,
|
||||
env=None, log_stderr=False, cwd=None):
|
||||
self.name = cmd
|
||||
self.std_out_cb = std_out_callback
|
||||
self.std_err_cb = std_err_callback
|
||||
cmd = os.path.expanduser(cmd)
|
||||
self.command = shlex.split(cmd)
|
||||
self.log_stderr = log_stderr
|
||||
self.env = env
|
||||
self.cwd = cwd
|
||||
self.proc = None
|
||||
self.cancelled = False
|
||||
self.return_code = None
|
||||
|
||||
async def cancel(self, sig_idx=1):
|
||||
self.cancelled = True
|
||||
if self.proc is not None:
|
||||
await self.proc.cancel(sig_idx)
|
||||
|
||||
def get_return_code(self):
|
||||
return self.return_code
|
||||
|
||||
def _reset_command_data(self):
|
||||
self.return_code = self.proc = None
|
||||
self.cancelled = False
|
||||
|
||||
async def run(self, timeout=2., verbose=True, log_complete=True,
|
||||
sig_idx=1):
|
||||
self._reset_command_data()
|
||||
if not timeout:
|
||||
# Never timeout
|
||||
timeout = 9999999999999999.
|
||||
if self.std_out_cb is None and self.std_err_cb is None and \
|
||||
not self.log_stderr:
|
||||
# No callbacks set so output cannot be verbose
|
||||
verbose = False
|
||||
if not await self._create_subprocess():
|
||||
return False
|
||||
try:
|
||||
if verbose:
|
||||
ret = self.proc.communicate_with_cb()
|
||||
else:
|
||||
ret = self.proc.wait()
|
||||
await asyncio.wait_for(ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
await self.proc.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
return self._check_proc_success(complete, log_complete)
|
||||
|
||||
async def run_with_response(self, timeout=2., retries=1,
|
||||
log_complete=True, sig_idx=1):
|
||||
self._reset_command_data()
|
||||
retries = max(1, retries)
|
||||
while retries > 0:
|
||||
stdout = stderr = b""
|
||||
if await self._create_subprocess():
|
||||
try:
|
||||
ret = self.proc.communicate()
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
await self.proc.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
if self.log_stderr and stderr:
|
||||
logging.info(f"{self.command[0]}: {stderr.decode()}")
|
||||
if self._check_proc_success(complete, log_complete):
|
||||
return stdout.decode().rstrip("\n")
|
||||
elif stdout:
|
||||
logging.debug(
|
||||
f"Shell command '{self.name}' output:"
|
||||
f"\n{stdout.decode()}")
|
||||
retries -= 1
|
||||
await gen.sleep(.5)
|
||||
raise ShellCommandError(
|
||||
f"Error running shell command: '{self.command}'",
|
||||
self.return_code, stdout, stderr)
|
||||
|
||||
async def _create_subprocess(self):
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def protocol_factory():
|
||||
return asyncio.subprocess.SubprocessStreamProtocol(
|
||||
limit=2**20, loop=loop)
|
||||
try:
|
||||
if self.std_err_cb is not None or self.log_stderr:
|
||||
errpipe = asyncio.subprocess.PIPE
|
||||
else:
|
||||
errpipe = asyncio.subprocess.STDOUT
|
||||
transport, protocol = await loop.subprocess_exec(
|
||||
protocol_factory, *self.command,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=errpipe, env=self.env, cwd=self.cwd)
|
||||
self.proc = SCProcess(transport, protocol, loop)
|
||||
self.proc.initialize(self.command[0], self.std_out_cb,
|
||||
self.std_err_cb, self.log_stderr)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _check_proc_success(self, complete, log_complete):
|
||||
self.return_code = self.proc.returncode
|
||||
success = self.return_code == 0 and complete
|
||||
if success:
|
||||
msg = f"Command ({self.name}) successfully finished"
|
||||
elif self.cancelled:
|
||||
msg = f"Command ({self.name}) cancelled"
|
||||
elif not complete:
|
||||
msg = f"Command ({self.name}) timed out"
|
||||
else:
|
||||
msg = f"Command ({self.name}) exited with return code" \
|
||||
f" {self.return_code}"
|
||||
if log_complete:
|
||||
logging.info(msg)
|
||||
return success
|
||||
|
||||
class ShellCommandFactory:
|
||||
error = ShellCommandError
|
||||
def build_shell_command(self, cmd, callback=None, std_err_callback=None,
|
||||
env=None, log_stderr=False, cwd=None):
|
||||
return ShellCommand(cmd, callback, std_err_callback, env,
|
||||
log_stderr, cwd)
|
||||
|
||||
def load_component(config):
|
||||
return ShellCommandFactory()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,10 +15,14 @@ class Sentinel:
|
||||
|
||||
class ConfigHelper:
|
||||
error = ConfigError
|
||||
def __init__(self, server, config, section):
|
||||
def __init__(self, server, config, section, orig_sects, parsed={}):
|
||||
self.server = server
|
||||
self.config = config
|
||||
self.section = section
|
||||
self.orig_sections = orig_sects
|
||||
self.parsed = parsed
|
||||
if self.section not in self.parsed:
|
||||
self.parsed[self.section] = {}
|
||||
self.sections = config.sections
|
||||
self.has_section = config.has_section
|
||||
|
||||
@@ -34,13 +38,17 @@ class ConfigHelper:
|
||||
def get_name(self):
|
||||
return self.section
|
||||
|
||||
def get_options(self):
|
||||
return dict(self.config[self.section])
|
||||
|
||||
def get_prefix_sections(self, prefix):
|
||||
return [s for s in self.sections() if s.startswith(prefix)]
|
||||
|
||||
def getsection(self, section):
|
||||
if section not in self.config:
|
||||
raise ConfigError(f"No section [{section}] in config")
|
||||
return ConfigHelper(self.server, self.config, section)
|
||||
return ConfigHelper(self.server, self.config, section,
|
||||
self.orig_sections, self.parsed)
|
||||
|
||||
def _get_option(self, func, option, default):
|
||||
try:
|
||||
@@ -52,6 +60,9 @@ class ConfigHelper:
|
||||
if val == Sentinel:
|
||||
raise ConfigError(
|
||||
f"No option found ({option}) in section [{self.section}]")
|
||||
if self.section in self.orig_sections:
|
||||
# Only track sections included in the original config
|
||||
self.parsed[self.section][option] = val
|
||||
return val
|
||||
|
||||
def get(self, option, default=Sentinel):
|
||||
@@ -67,9 +78,40 @@ class ConfigHelper:
|
||||
self.config[self.section].getboolean, option, default)
|
||||
|
||||
def getfloat(self, option, default=Sentinel):
|
||||
return self._get_item(
|
||||
return self._get_option(
|
||||
self.config[self.section].getfloat, option, default)
|
||||
|
||||
def read_supplemental_config(self, file_name):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
|
||||
if not os.path.isfile(cfg_file_path):
|
||||
raise ConfigError(
|
||||
f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
try:
|
||||
self.config.read(cfg_file_path)
|
||||
except Exception:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
|
||||
|
||||
def write_config(self, file_obj):
|
||||
self.config.write(file_obj)
|
||||
|
||||
def get_parsed_config(self):
|
||||
return dict(self.parsed)
|
||||
|
||||
def validate_config(self):
|
||||
for sect in self.orig_sections:
|
||||
if sect not in self.parsed:
|
||||
logging.warn(
|
||||
f"Invalid config section [{sect}] detected. In "
|
||||
"the future this will result in a startup error")
|
||||
continue
|
||||
parsed_opts = self.parsed[sect]
|
||||
for opt, val in self.config.items(sect):
|
||||
if opt not in parsed_opts:
|
||||
logging.warn(
|
||||
f"Invalid option '{opt}' detected in section "
|
||||
f"[{sect}]. In the future this will result in a "
|
||||
"startup error.")
|
||||
|
||||
def get_configuration(server, system_args):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(
|
||||
system_args.configfile))
|
||||
@@ -86,10 +128,14 @@ def get_configuration(server, system_args):
|
||||
except KeyError:
|
||||
raise ConfigError("No section [server] in config")
|
||||
|
||||
if server_cfg.get('enable_debug_logging', True):
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
orig_sections = config.sections()
|
||||
try:
|
||||
orig_sections.remove("DEFAULT")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
config['system_args'] = {
|
||||
'configfile': system_args.configfile,
|
||||
'logfile': system_args.logfile,
|
||||
'software_version': system_args.software_version}
|
||||
return ConfigHelper(server, config, 'server')
|
||||
return ConfigHelper(server, config, 'server', orig_sections)
|
||||
Regular → Executable
+153
-55
@@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
@@ -7,10 +8,12 @@ import argparse
|
||||
import sys
|
||||
import importlib
|
||||
import os
|
||||
import io
|
||||
import time
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
import signal
|
||||
import confighelper
|
||||
import utils
|
||||
import asyncio
|
||||
@@ -25,19 +28,29 @@ INIT_TIME = .25
|
||||
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
|
||||
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
|
||||
CORE_PLUGINS = [
|
||||
'file_manager', 'klippy_apis', 'machine',
|
||||
'data_store', 'shell_command']
|
||||
CORE_COMPONENTS = [
|
||||
'database', 'file_manager', 'klippy_apis', 'machine',
|
||||
'data_store', 'shell_command', 'proc_stats']
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class Server:
|
||||
error = ServerError
|
||||
def __init__(self, args):
|
||||
config = confighelper.get_configuration(self, args)
|
||||
def __init__(self, args, file_logger):
|
||||
self.file_logger = file_logger
|
||||
self.config = config = confighelper.get_configuration(self, args)
|
||||
# log config file
|
||||
strio = io.StringIO()
|
||||
config.write_config(strio)
|
||||
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
|
||||
cfg_item += strio.getvalue()
|
||||
cfg_item += "#"*65
|
||||
strio.close()
|
||||
self.add_log_rollover_item('config', cfg_item)
|
||||
self.host = config.get('host', "0.0.0.0")
|
||||
self.port = config.getint('port', 7125)
|
||||
self.exit_reason = ""
|
||||
|
||||
# Event initialization
|
||||
self.events = {}
|
||||
@@ -52,7 +65,9 @@ class Server:
|
||||
self.init_handle = None
|
||||
self.init_attempts = 0
|
||||
self.klippy_state = "disconnected"
|
||||
self.klippy_disconnect_evt = None
|
||||
self.subscriptions = {}
|
||||
self.failed_components = []
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
@@ -64,9 +79,17 @@ class Server:
|
||||
|
||||
self.register_endpoint(
|
||||
"/server/info", ['GET'], self._handle_info_request)
|
||||
self.register_endpoint(
|
||||
"/server/config", ['GET'], self._handle_config_request)
|
||||
self.register_endpoint(
|
||||
"/server/restart", ['POST'], self._handle_server_restart)
|
||||
|
||||
self.register_notification("server:klippy_ready")
|
||||
self.register_notification("server:klippy_shutdown")
|
||||
self.register_notification("server:klippy_disconnect",
|
||||
"klippy_disconnected")
|
||||
self.register_notification("server:gcode_response")
|
||||
|
||||
# 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
|
||||
@@ -80,10 +103,11 @@ class Server:
|
||||
'process_status_update', self._process_status_update,
|
||||
need_klippy_reg=False)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
|
||||
self._load_plugins(config)
|
||||
# Component initialization
|
||||
self.components = {}
|
||||
self._load_components(config)
|
||||
self.klippy_apis = self.lookup_component('klippy_apis')
|
||||
config.validate_config()
|
||||
|
||||
def start(self):
|
||||
hostname, hostport = self.get_host_info()
|
||||
@@ -92,56 +116,75 @@ class Server:
|
||||
f"Hostname: {hostname}")
|
||||
self.moonraker_app.listen(self.host, self.port)
|
||||
self.server_running = True
|
||||
self.ioloop.spawn_callback(self._init_signals)
|
||||
self.ioloop.spawn_callback(self._connect_klippy)
|
||||
|
||||
# ***** Plugin Management *****
|
||||
def _load_plugins(self, config):
|
||||
# load core plugins
|
||||
for plugin in CORE_PLUGINS:
|
||||
self.load_plugin(config, plugin)
|
||||
def _init_signals(self):
|
||||
aioloop = asyncio.get_event_loop()
|
||||
aioloop.add_signal_handler(
|
||||
signal.SIGTERM, self._handle_term_signal)
|
||||
|
||||
# check for optional plugins
|
||||
def add_log_rollover_item(self, name, item, log=True):
|
||||
if self.file_logger is not None:
|
||||
self.file_logger.set_rollover_info(name, item)
|
||||
if log and item is not None:
|
||||
logging.info(item)
|
||||
|
||||
# ***** Component Management *****
|
||||
def _load_components(self, config):
|
||||
# load core components
|
||||
for component in CORE_COMPONENTS:
|
||||
self.load_component(config, component)
|
||||
|
||||
# check for optional components
|
||||
opt_sections = set([s.split()[0] for s in config.sections()]) - \
|
||||
set(['server', 'authorization', 'system_args'])
|
||||
for section in opt_sections:
|
||||
self.load_plugin(config, section, None)
|
||||
self.load_component(config, section, None)
|
||||
|
||||
def load_plugin(self, config, plugin_name, default=Sentinel):
|
||||
if plugin_name in self.plugins:
|
||||
return self.plugins[plugin_name]
|
||||
# Make sure plugin exists
|
||||
def load_component(self, config, component_name, default=Sentinel):
|
||||
if component_name in self.components:
|
||||
return self.components[component_name]
|
||||
# Make sure component exists
|
||||
mod_path = os.path.join(
|
||||
os.path.dirname(__file__), 'plugins', plugin_name + '.py')
|
||||
os.path.dirname(__file__), 'components', component_name + '.py')
|
||||
if not os.path.exists(mod_path):
|
||||
msg = f"Plugin ({plugin_name}) does not exist"
|
||||
msg = f"Component ({component_name}) does not exist"
|
||||
logging.info(msg)
|
||||
self.failed_components.append(component_name)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
module = importlib.import_module("plugins." + plugin_name)
|
||||
try:
|
||||
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]
|
||||
module = importlib.import_module("components." + component_name)
|
||||
func_name = "load_component"
|
||||
if hasattr(module, "load_component_multi"):
|
||||
func_name = "load_component_multi"
|
||||
if component_name not in CORE_COMPONENTS and \
|
||||
func_name == "load_component":
|
||||
config = config[component_name]
|
||||
load_func = getattr(module, func_name)
|
||||
plugin = load_func(config)
|
||||
component = load_func(config)
|
||||
except Exception:
|
||||
msg = f"Unable to load plugin ({plugin_name})"
|
||||
msg = f"Unable to load component: ({component_name})"
|
||||
logging.exception(msg)
|
||||
self.failed_components.append(component_name)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
self.plugins[plugin_name] = plugin
|
||||
logging.info(f"Plugin ({plugin_name}) loaded")
|
||||
return plugin
|
||||
self.components[component_name] = component
|
||||
logging.info(f"Component ({component_name}) loaded")
|
||||
return component
|
||||
|
||||
def lookup_plugin(self, plugin_name, default=Sentinel):
|
||||
plugin = self.plugins.get(plugin_name, default)
|
||||
if plugin == Sentinel:
|
||||
raise ServerError(f"Plugin ({plugin_name}) not found")
|
||||
return plugin
|
||||
def lookup_component(self, component_name, default=Sentinel):
|
||||
component = self.components.get(component_name, default)
|
||||
if component == Sentinel:
|
||||
raise ServerError(f"Component ({component_name}) not found")
|
||||
return component
|
||||
|
||||
def register_notification(self, event_name, notify_name=None):
|
||||
wsm = self.moonraker_app.get_websocket_manager()
|
||||
wsm.register_notification(event_name, notify_name)
|
||||
|
||||
def register_event_handler(self, event, callback):
|
||||
self.events.setdefault(event, []).append(callback)
|
||||
@@ -228,6 +271,8 @@ class Server:
|
||||
self.ioloop.remove_timeout(self.init_handle)
|
||||
if self.server_running:
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
if self.klippy_disconnect_evt is not None:
|
||||
self.klippy_disconnect_evt.set()
|
||||
|
||||
async def _initialize(self):
|
||||
if not self.server_running:
|
||||
@@ -285,10 +330,11 @@ class Server:
|
||||
f"Klippy may have experienced an error during startup.\n"
|
||||
f"Please check klippy.log for more information")
|
||||
return
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
self.klippy_info = dict(result)
|
||||
self.klippy_state = result.get('state', "unknown")
|
||||
if send_id:
|
||||
self.init_list.append("identified")
|
||||
self.send_event("server:klippy_identified")
|
||||
if self.klippy_state == "ready":
|
||||
await self._verify_klippy_requirements()
|
||||
logging.info("Klippy ready")
|
||||
@@ -330,7 +376,7 @@ class Server:
|
||||
vsd_config = config.get('virtual_sdcard', {})
|
||||
vsd_path = vsd_config.get('path', None)
|
||||
if vsd_path is not None:
|
||||
file_manager = self.lookup_plugin('file_manager')
|
||||
file_manager = self.lookup_component('file_manager')
|
||||
file_manager.register_directory('gcodes', vsd_path)
|
||||
else:
|
||||
logging.info(
|
||||
@@ -366,6 +412,10 @@ class Server:
|
||||
if rpc_method == "objects/subscribe":
|
||||
return await self._request_subscripton(web_request)
|
||||
else:
|
||||
if rpc_method == "gcode/script":
|
||||
script = web_request.get_str('script', "")
|
||||
data_store = self.lookup_component('data_store')
|
||||
data_store.store_gcode_command(script)
|
||||
return await self._request_standard(web_request)
|
||||
|
||||
async def _request_subscripton(self, web_request):
|
||||
@@ -425,17 +475,43 @@ class Server:
|
||||
def remove_subscription(self, conn):
|
||||
self.subscriptions.pop(conn, None)
|
||||
|
||||
async def _stop_server(self):
|
||||
def _handle_term_signal(self):
|
||||
logging.info(f"Exiting with signal SIGTERM")
|
||||
self.ioloop.spawn_callback(self._stop_server, "terminate")
|
||||
|
||||
async def _stop_server(self, exit_reason="restart"):
|
||||
self.server_running = False
|
||||
for name, plugin in self.plugins.items():
|
||||
if hasattr(plugin, "close"):
|
||||
ret = plugin.close()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.klippy_connection.close()
|
||||
while self.klippy_state != "disconnected":
|
||||
await gen.sleep(.1)
|
||||
await self.moonraker_app.close()
|
||||
for method in ["on_exit", "close"]:
|
||||
for name, component in self.components.items():
|
||||
if not hasattr(component, method):
|
||||
continue
|
||||
func = getattr(component, method)
|
||||
try:
|
||||
ret = func()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error executing '{method}()' for component: {name}")
|
||||
try:
|
||||
if self.klippy_connection.is_connected():
|
||||
self.klippy_disconnect_evt = Event()
|
||||
self.klippy_connection.close()
|
||||
timeout = time.time() + 2.
|
||||
await self.klippy_disconnect_evt.wait(timeout)
|
||||
self.klippy_disconnect_evt = None
|
||||
except Exception:
|
||||
logging.exception("Klippy Disconnect Error")
|
||||
# Sleep for 100ms to allow connected websockets
|
||||
# to write out remaining data
|
||||
await gen.sleep(.1)
|
||||
try:
|
||||
await self.moonraker_app.close()
|
||||
except Exception:
|
||||
logging.exception("Error Closing App")
|
||||
self.exit_reason = exit_reason
|
||||
aioloop = asyncio.get_event_loop()
|
||||
aioloop.remove_signal_handler(signal.SIGTERM)
|
||||
self.ioloop.stop()
|
||||
|
||||
async def _handle_server_restart(self, web_request):
|
||||
@@ -443,10 +519,23 @@ class Server:
|
||||
return "ok"
|
||||
|
||||
async def _handle_info_request(self, web_request):
|
||||
file_manager = self.lookup_component('file_manager', None)
|
||||
reg_dirs = []
|
||||
if file_manager is not None:
|
||||
reg_dirs = file_manager.get_registered_dirs()
|
||||
return {
|
||||
'klippy_connected': self.klippy_connection.is_connected(),
|
||||
'klippy_state': self.klippy_state,
|
||||
'plugins': list(self.plugins.keys())}
|
||||
'components': list(self.components.keys()),
|
||||
'failed_components': self.failed_components,
|
||||
'plugins': list(self.components.keys()),
|
||||
'failed_plugins': self.failed_components,
|
||||
'registered_directories': reg_dirs}
|
||||
|
||||
async def _handle_config_request(self, web_request):
|
||||
return {
|
||||
'config': self.config.get_parsed_config()
|
||||
}
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, on_recd, on_close):
|
||||
@@ -549,14 +638,21 @@ def main():
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
parser.add_argument(
|
||||
"-n", "--nologfile", action='store_true',
|
||||
help="disable logging to a file")
|
||||
system_args = parser.parse_args()
|
||||
|
||||
# Setup Logging
|
||||
version = utils.get_software_version()
|
||||
log_file = os.path.normpath(os.path.expanduser(system_args.logfile))
|
||||
if system_args.nologfile:
|
||||
log_file = ""
|
||||
else:
|
||||
log_file = os.path.normpath(os.path.expanduser(
|
||||
system_args.logfile))
|
||||
system_args.logfile = log_file
|
||||
system_args.software_version = version
|
||||
ql = utils.setup_logging(log_file, version)
|
||||
ql, file_logger = utils.setup_logging(log_file, version)
|
||||
|
||||
if sys.version_info < (3, 7):
|
||||
msg = f"Moonraker requires Python 3.7 or above. " \
|
||||
@@ -571,7 +667,7 @@ def main():
|
||||
estatus = 0
|
||||
while True:
|
||||
try:
|
||||
server = Server(system_args)
|
||||
server = Server(system_args, file_logger)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
estatus = 1
|
||||
@@ -583,6 +679,8 @@ def main():
|
||||
logging.exception("Server Running Error")
|
||||
estatus = 1
|
||||
break
|
||||
if server.exit_reason == "terminate":
|
||||
break
|
||||
# Since we are running outside of the the server
|
||||
# it is ok to use a blocking sleep here
|
||||
time.sleep(.5)
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
# linux shell command execution utility
|
||||
#
|
||||
# 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 shlex
|
||||
import subprocess
|
||||
import logging
|
||||
import tornado
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
class ShellCommand:
|
||||
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:
|
||||
return
|
||||
try:
|
||||
data = os.read(fd, 4096)
|
||||
except Exception:
|
||||
return
|
||||
data = self.partial_output + data
|
||||
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
|
||||
verbose = False
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
return False
|
||||
if verbose:
|
||||
fd = proc.stdout.fileno()
|
||||
self.io_loop.add_handler(
|
||||
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
|
||||
elif not timeout:
|
||||
# fire and forget, return from execution
|
||||
return True
|
||||
sleeptime = 0
|
||||
complete = False
|
||||
while sleeptime < timeout:
|
||||
await gen.sleep(.05)
|
||||
sleeptime += .05
|
||||
if proc.poll() is not None:
|
||||
complete = True
|
||||
break
|
||||
if self.cancelled:
|
||||
break
|
||||
if not complete:
|
||||
proc.terminate()
|
||||
if verbose:
|
||||
if self.partial_output:
|
||||
self.output_cb(self.partial_output)
|
||||
self.partial_output = b""
|
||||
if complete:
|
||||
msg = f"Command ({self.name}) finished"
|
||||
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=None):
|
||||
return ShellCommand(cmd, callback)
|
||||
|
||||
def load_plugin(config):
|
||||
return ShellCommandFactory()
|
||||
@@ -1,482 +0,0 @@
|
||||
# Provides updates for Klipper and Moonraker
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
import json
|
||||
import sys
|
||||
import shutil
|
||||
import zipfile
|
||||
import io
|
||||
import tornado.gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
|
||||
|
||||
MOONRAKER_PATH = os.path.normpath(os.path.join(
|
||||
os.path.dirname(__file__), "../.."))
|
||||
|
||||
# TODO: May want to attempt to look up the disto for the correct
|
||||
# klippy install script or have the user configure it
|
||||
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
|
||||
REPO_PREFIX = "https://api.github.com/repos"
|
||||
REPO_DATA = {
|
||||
'moonraker': {
|
||||
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
|
||||
'origin': "https://github.com/Arksine/moonraker.git",
|
||||
'install_script': "scripts/install-moonraker.sh",
|
||||
'requirements': "scripts/moonraker-requirements.txt",
|
||||
'venv_args': "-p python3 --system-site-packages"
|
||||
},
|
||||
'klipper': {
|
||||
'repo_url': f"{REPO_PREFIX}/kevinoconnor/klipper/branches/master",
|
||||
'origin': "https://github.com/KevinOConnor/klipper.git",
|
||||
'install_script': "scripts/install-octopi.sh",
|
||||
'requirements': "scripts/klippy-requirements.txt",
|
||||
'venv_args': "-p python2"
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
|
||||
self.http_client = AsyncHTTPClient()
|
||||
sw_version = config['system_args'].get('software_version')
|
||||
self.updaters = {
|
||||
"system": PackageUpdater(self),
|
||||
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH,
|
||||
sw_version, sys.executable)
|
||||
}
|
||||
self.current_update = None
|
||||
client_repo = config.get("client_repo", None)
|
||||
if client_repo is not None:
|
||||
client_path = os.path.expanduser(config.get("client_path"))
|
||||
if os.path.islink(client_path):
|
||||
raise config.error(
|
||||
"Option 'client_path' cannot be set to a symbolic link")
|
||||
self.updaters['client'] = ClientUpdater(
|
||||
self, client_repo, client_path)
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/moonraker", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/klipper", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/system", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/client", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/status", ["GET"],
|
||||
self._handle_status_request)
|
||||
|
||||
# Register Ready Event
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._set_klipper_repo)
|
||||
|
||||
async def _set_klipper_repo(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
if not kinfo:
|
||||
logging.info("No valid klippy info received")
|
||||
return
|
||||
kpath = kinfo['klipper_path']
|
||||
kversion = kinfo['software_version']
|
||||
env = kinfo['python_path']
|
||||
self.updaters['klipper'] = GitUpdater(
|
||||
self, "klipper", kpath, kversion, env)
|
||||
|
||||
async def _check_versions(self):
|
||||
for updater in self.updaters.values():
|
||||
await updater.check_remote_version()
|
||||
|
||||
async def _handle_update_request(self, web_request):
|
||||
app = web_request.get_endpoint().split("/")[-1]
|
||||
inc_deps = web_request.get_boolean('include_deps', False)
|
||||
if self.current_update:
|
||||
raise self.server.error("A current update is in progress")
|
||||
updater = self.updaters.get(app, None)
|
||||
if updater is None:
|
||||
raise self.server.error(f"Updater {app} not available")
|
||||
self.current_update = (app, id(web_request))
|
||||
try:
|
||||
await updater.update(inc_deps)
|
||||
except Exception:
|
||||
self.current_update = None
|
||||
raise
|
||||
self.current_update = None
|
||||
return "ok"
|
||||
|
||||
async def _handle_status_request(self, web_request):
|
||||
if web_request.get_boolean('refresh', False):
|
||||
await self._check_versions()
|
||||
vinfo = {}
|
||||
for name, updater in self.updaters.items():
|
||||
if hasattr(updater, "get_update_status"):
|
||||
vinfo[name] = updater.get_update_status()
|
||||
return {
|
||||
'version_info': vinfo,
|
||||
'busy': self.current_update is not None}
|
||||
|
||||
async def execute_cmd(self, cmd, timeout=10., notify=False, retries=1):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
cb = self.notify_update_response if notify else None
|
||||
scmd = shell_command.build_shell_command(cmd, callback=cb)
|
||||
while retries:
|
||||
if await scmd.run(timeout=timeout, verbose=notify):
|
||||
break
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Shell Command Error")
|
||||
|
||||
async def execute_cmd_with_response(self, cmd, timeout=10.):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
return await scmd.run_with_response(timeout)
|
||||
|
||||
async def github_request(self, url, is_download=False):
|
||||
cto = rto = 5.
|
||||
content_type = "application/vnd.github.v3+json"
|
||||
if is_download:
|
||||
content_type = "application/zip"
|
||||
rto = 120.
|
||||
timeout = cto + rto + 2.
|
||||
request = HTTPRequest(url, headers={"Accept": content_type},
|
||||
connect_timeout=cto, request_timeout=rto)
|
||||
retries = 5
|
||||
while True:
|
||||
to = IOLoop.current().time() + timeout
|
||||
try:
|
||||
fut = self.http_client.fetch(request)
|
||||
resp = await tornado.gen.with_timeout(to, fut)
|
||||
except Exception as e:
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise
|
||||
logging.info(f"Github request error, retrying: {e}")
|
||||
continue
|
||||
if is_download:
|
||||
return resp.body
|
||||
decoded = json.loads(resp.body)
|
||||
return decoded
|
||||
|
||||
def notify_update_response(self, resp):
|
||||
resp = resp.strip()
|
||||
if isinstance(resp, bytes):
|
||||
resp = resp.decode()
|
||||
notification = {
|
||||
'message': resp,
|
||||
'application': None,
|
||||
'proc_id': None}
|
||||
if self.current_update is not None:
|
||||
notification['application'] = self.current_update[0]
|
||||
notification['proc_id'] = self.current_update[1]
|
||||
self.server.send_event(
|
||||
"update_manager:update_response", notification)
|
||||
|
||||
def close(self):
|
||||
self.http_client.close()
|
||||
|
||||
|
||||
class GitUpdater:
|
||||
def __init__(self, umgr, name, path, ver, env):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.execute_cmd_with_response = umgr.execute_cmd_with_response
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
self.github_request = umgr.github_request
|
||||
self.name = name
|
||||
self.repo_path = path
|
||||
self.env = env
|
||||
self.version = self.cur_hash = self.remote_hash = "?"
|
||||
self.is_valid = False
|
||||
self.is_dirty = ver.endswith("dirty")
|
||||
tag_version = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
self.version = tag_version
|
||||
IOLoop.current().spawn_callback(self._init_repo)
|
||||
|
||||
def _get_version_info(self):
|
||||
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
|
||||
vinfo = {}
|
||||
if os.path.isfile(ver_path):
|
||||
data = ""
|
||||
with open(ver_path, 'r') as f:
|
||||
data = f.read()
|
||||
try:
|
||||
entries = [e.strip() for e in data.split('\n') if e.strip()]
|
||||
vinfo = dict([i.split('=') for i in entries])
|
||||
vinfo = {k: tuple(re.findall(r"\d+", v)) for k, v in
|
||||
vinfo.items()}
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
self._log_info(f"Version Info Found: {vinfo}")
|
||||
vinfo['version'] = tuple(re.findall(r"\d+", self.version))
|
||||
return vinfo
|
||||
|
||||
def _log_exc(self, msg, traceback=True):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
if traceback:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return self.server.error(msg)
|
||||
|
||||
def _log_info(self, msg):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.info(log_msg)
|
||||
|
||||
def _notify_status(self, msg):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.debug(log_msg)
|
||||
self.notify_update_response(log_msg)
|
||||
|
||||
async def _init_repo(self):
|
||||
self.is_valid = False
|
||||
self.cur_hash = "?"
|
||||
try:
|
||||
branch = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse --abbrev-ref HEAD")
|
||||
origin = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} remote get-url origin")
|
||||
hash = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} rev-parse HEAD")
|
||||
except Exception:
|
||||
self._log_exc("Error retreiving git info")
|
||||
return
|
||||
|
||||
if not branch.startswith("fatal:"):
|
||||
self.cur_hash = hash
|
||||
if branch == "master":
|
||||
if origin == REPO_DATA[self.name]['origin']:
|
||||
self.is_valid = True
|
||||
self._log_info("Validity check for git repo passed")
|
||||
else:
|
||||
self._log_info(f"Invalid git origin '{origin}''")
|
||||
else:
|
||||
self._log_info("Git repo not on master branch")
|
||||
else:
|
||||
self._log_info(f"Invalid git repo at path '{self.repo_path}''")
|
||||
try:
|
||||
await self.check_remote_version()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def check_remote_version(self):
|
||||
repo_url = REPO_DATA[self.name]['repo_url']
|
||||
try:
|
||||
branch_info = await self.github_request(repo_url)
|
||||
except Exception:
|
||||
raise self._log_exc(f"Error retreiving github info")
|
||||
commit_hash = branch_info.get('commit', {}).get('sha', None)
|
||||
if commit_hash is None:
|
||||
self.is_valid = False
|
||||
self.upstream_version = "?"
|
||||
raise self._log_exc(f"Invalid github response", False)
|
||||
self._log_info(f"Received latest commit hash: {commit_hash}")
|
||||
self.remote_hash = commit_hash
|
||||
|
||||
async def update(self, update_deps=False):
|
||||
if not self.is_valid:
|
||||
raise self._log_exc("Update aborted, repo is not valid", False)
|
||||
if self.is_dirty:
|
||||
raise self._log_exc(
|
||||
"Update aborted, repo is has been modified", False)
|
||||
if self.remote_hash == "?":
|
||||
await self.check_remote_version()
|
||||
if self.remote_hash == self.cur_hash:
|
||||
# No need to update
|
||||
return
|
||||
self._notify_status("Updating Repo...")
|
||||
try:
|
||||
await self.execute_cmd(f"git -C {self.repo_path} pull -q")
|
||||
except Exception:
|
||||
raise self._log_exc("Error running 'git pull'")
|
||||
# Check Semantic Versions
|
||||
vinfo = self._get_version_info()
|
||||
cur_version = vinfo.get('version', ())
|
||||
update_deps |= cur_version < vinfo.get('deps_version', ())
|
||||
need_env_rebuild = cur_version < vinfo.get('env_version', ())
|
||||
if update_deps:
|
||||
await self._install_packages()
|
||||
await self._update_virtualenv(need_env_rebuild)
|
||||
if self.name == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
IOLoop.current().spawn_callback(self.restart_service)
|
||||
else:
|
||||
await self.restart_service()
|
||||
|
||||
async def _install_packages(self):
|
||||
# Open install file file and read
|
||||
inst_script = REPO_DATA[self.name]['install_script']
|
||||
inst_path = os.path.join(self.repo_path, inst_script)
|
||||
if not os.path.isfile(inst_path):
|
||||
self._log_info(f"Unable to open install script: {inst_path}")
|
||||
return
|
||||
with open(inst_path, 'r') as f:
|
||||
data = f.read()
|
||||
packages = re.findall(r'PKGLIST="(.*)"', data)
|
||||
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
|
||||
if not packages:
|
||||
self._log_info(f"No packages found in script: {inst_path}")
|
||||
return
|
||||
# TODO: Log and notify that packages will be installed
|
||||
pkgs = " ".join(packages)
|
||||
logging.debug(f"Repo {self.name}: Detected Packages: {pkgs}")
|
||||
self._notify_status("Installing system dependencies...")
|
||||
# Install packages with apt-get
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} install --yes {pkgs}", timeout=3600.,
|
||||
notify=True)
|
||||
except Exception:
|
||||
self._log_exc("Error updating packages via apt-get")
|
||||
return
|
||||
|
||||
async def _update_virtualenv(self, rebuild_env=False):
|
||||
# Update python dependencies
|
||||
bin_dir = os.path.dirname(self.env)
|
||||
if rebuild_env:
|
||||
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
|
||||
env_args = REPO_DATA[self.name]['venv_args']
|
||||
self._notify_status(f"Creating virtualenv at: {env_path}...")
|
||||
if os.path.exists(env_path):
|
||||
shutil.rmtree(env_path)
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"virtualenv {env_args} {env_path}")
|
||||
except Exception:
|
||||
self._log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
await tornado.gen.sleep(.5)
|
||||
if not os.path.expanduser(self.env):
|
||||
raise self._log_exc("Failed to create new virtualenv", False)
|
||||
reqs = os.path.join(
|
||||
self.repo_path, REPO_DATA[self.name]['requirements'])
|
||||
if not os.path.isfile(reqs):
|
||||
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
|
||||
return
|
||||
pip = os.path.join(bin_dir, "pip")
|
||||
self._notify_status("Updating python packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{pip} install -r {reqs}", timeout=1200., notify=True,
|
||||
retries=3)
|
||||
except Exception:
|
||||
self._log_exc("Error updating python requirements")
|
||||
|
||||
async def restart_service(self):
|
||||
self._notify_status("Restarting Service...")
|
||||
try:
|
||||
await self.execute_cmd(f"sudo systemctl restart {self.name}")
|
||||
except Exception:
|
||||
raise self._log_exc("Error restarting service")
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'version': self.version,
|
||||
'current_hash': self.cur_hash,
|
||||
'remote_hash': self.remote_hash,
|
||||
'is_dirty': self.is_dirty,
|
||||
'is_valid': self.is_valid}
|
||||
|
||||
|
||||
class PackageUpdater:
|
||||
def __init__(self, umgr):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
|
||||
async def check_remote_version(self):
|
||||
pass
|
||||
|
||||
async def update(self, *args):
|
||||
self.notify_update_response("Updating packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
|
||||
except Exception:
|
||||
raise self.server.error("Error updating system packages")
|
||||
|
||||
class ClientUpdater:
|
||||
def __init__(self, umgr, repo, path):
|
||||
self.server = umgr.server
|
||||
self.github_request = umgr.github_request
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
self.repo = repo.strip().strip("/")
|
||||
self.name = self.repo.split("/")[-1]
|
||||
self.path = path
|
||||
self.version = self.remote_version = self.dl_url = "?"
|
||||
version_path = os.path.join(self.path, ".version")
|
||||
if os.path.isfile(os.path.join(self.path, ".version")):
|
||||
with open(version_path, "r") as f:
|
||||
v = f.read()
|
||||
self.version = v.strip()
|
||||
logging.info(f"\nInitializing repo '{self.name}',"
|
||||
f"\nversion: {self.version}"
|
||||
f"\npath: {self.path}")
|
||||
IOLoop.current().spawn_callback(self.check_remote_version)
|
||||
|
||||
async def check_remote_version(self):
|
||||
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
|
||||
try:
|
||||
result = await self.github_request(url)
|
||||
except Exception:
|
||||
logging.exception(f"Client {self.repo}: Github Request Error")
|
||||
result = {}
|
||||
self.remote_version = result.get('name', "?")
|
||||
release_assets = result.get('assets', [{}])[0]
|
||||
self.dl_url = release_assets.get('browser_download_url', "?")
|
||||
logging.info(
|
||||
f"Github client Info Received: {self.name}, "
|
||||
f"version: {self.remote_version} "
|
||||
f"url: {self.dl_url}")
|
||||
|
||||
async def update(self, *args):
|
||||
if self.remote_version == "?":
|
||||
await self.check_remote_version()
|
||||
if self.remote_version == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Unable to locate update")
|
||||
if self.dl_url == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Invalid download url")
|
||||
if self.version == self.remote_version:
|
||||
# Already up to date
|
||||
return
|
||||
if os.path.isdir(self.path):
|
||||
shutil.rmtree(self.path)
|
||||
os.mkdir(self.path)
|
||||
self.notify_update_response(f"Downloading Client: {self.name}")
|
||||
archive = await self.github_request(self.dl_url, is_download=True)
|
||||
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
|
||||
zf.extractall(self.path)
|
||||
self.version = self.remote_version
|
||||
version_path = os.path.join(self.path, ".version")
|
||||
if not os.path.exists(version_path):
|
||||
with open(version_path, "w") as f:
|
||||
f.write(self.version)
|
||||
self.notify_update_response(f"Client Updated: {self.name}")
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'version': self.version,
|
||||
'remote_version': self.remote_version
|
||||
}
|
||||
|
||||
def load_plugin(config):
|
||||
return UpdateManager(config)
|
||||
+30
-12
@@ -6,6 +6,7 @@
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
from queue import SimpleQueue as Queue
|
||||
@@ -27,19 +28,26 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
# Timed Rotating File Handler, based on Klipper's implementation
|
||||
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
def __init__(self, software_version, filename, **kwargs):
|
||||
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
|
||||
self.header = "Moonraker Log Start...\n"
|
||||
self.header += f"Git Version: {software_version}\n"
|
||||
self.header += "="*80 + "\n"
|
||||
self.rollover_info = {
|
||||
'header': f"{'-'*20}Moonraker Log Start{'-'*20}",
|
||||
'version': f"Git Version: {software_version}",
|
||||
}
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
def set_rollover_info(self, name, item):
|
||||
self.rollover_info[name] = item
|
||||
|
||||
def doRollover(self):
|
||||
super(MoonrakerLoggingHandler, self).doRollover()
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
# Parse the git version from the command line. This code
|
||||
# is borrowed from Klipper.
|
||||
@@ -73,11 +81,21 @@ def setup_logging(log_file, software_version):
|
||||
queue_handler = LocalQueueHandler(queue)
|
||||
root_logger.addHandler(queue_handler)
|
||||
root_logger.setLevel(logging.INFO)
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
software_version, log_file, when='midnight', backupCount=2)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
listener = logging.handlers.QueueListener(queue, file_hdlr)
|
||||
stdout_hdlr = logging.StreamHandler(sys.stdout)
|
||||
stdout_fmt = logging.Formatter(
|
||||
'[%(filename)s:%(funcName)s()] - %(message)s')
|
||||
stdout_hdlr.setFormatter(stdout_fmt)
|
||||
file_hdlr = None
|
||||
if log_file:
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
software_version, log_file, when='midnight', backupCount=2)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
listener = logging.handlers.QueueListener(
|
||||
queue, file_hdlr, stdout_hdlr)
|
||||
else:
|
||||
listener = logging.handlers.QueueListener(
|
||||
queue, stdout_hdlr)
|
||||
listener.start()
|
||||
return listener
|
||||
return listener, file_hdlr
|
||||
+25
-43
@@ -135,11 +135,12 @@ class JsonRPC:
|
||||
try:
|
||||
result = await method(ws, *args, **kwargs)
|
||||
except TypeError as e:
|
||||
return self.build_error(-32603, f"Invalid params:\n{e}", req_id)
|
||||
return self.build_error(
|
||||
-32603, f"Invalid params:\n{e}", req_id, True)
|
||||
except ServerError as e:
|
||||
return self.build_error(e.status_code, str(e), req_id)
|
||||
return self.build_error(e.status_code, str(e), req_id, True)
|
||||
except Exception as e:
|
||||
return self.build_error(-31000, str(e), req_id)
|
||||
return self.build_error(-31000, str(e), req_id, True)
|
||||
|
||||
if req_id is None:
|
||||
return None
|
||||
@@ -153,7 +154,12 @@ class JsonRPC:
|
||||
'id': req_id
|
||||
}
|
||||
|
||||
def build_error(self, code, msg, req_id=None):
|
||||
def build_error(self, code, msg, req_id=None, is_exc=False):
|
||||
log_msg = f"JSON-RPC Request Error: {code}\n{msg}"
|
||||
if is_exc:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return {
|
||||
'jsonrpc': "2.0",
|
||||
'error': {'code': code, 'message': msg},
|
||||
@@ -169,42 +175,14 @@ class WebsocketManager:
|
||||
|
||||
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(
|
||||
"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)
|
||||
def register_notification(self, event_name, notify_name=None):
|
||||
if notify_name is None:
|
||||
notify_name = event_name.split(':')[-1]
|
||||
|
||||
async def _handle_klippy_ready(self):
|
||||
await self.notify_websockets("klippy_ready")
|
||||
|
||||
async def _handle_klippy_disconnect(self):
|
||||
await self.notify_websockets("klippy_disconnected")
|
||||
|
||||
async def _handle_gcode_response(self, response):
|
||||
await self.notify_websockets("gcode_response", response)
|
||||
|
||||
async def _handle_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)
|
||||
|
||||
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)
|
||||
async def notify_handler(*args):
|
||||
await self.notify_websockets(notify_name, *args)
|
||||
self.server.register_event_handler(
|
||||
event_name, notify_handler)
|
||||
|
||||
def register_local_handler(self, api_def, callback):
|
||||
for ws_method, req_method in \
|
||||
@@ -266,6 +244,7 @@ class WebsocketManager:
|
||||
ws.write_message(msg)
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(ws.uid, None)
|
||||
self.server.remove_subscription(ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
@@ -273,7 +252,7 @@ class WebsocketManager:
|
||||
|
||||
async def close(self):
|
||||
async with self.ws_lock:
|
||||
for ws in self.websockets.values():
|
||||
for ws in list(self.websockets.values()):
|
||||
ws.close()
|
||||
self.websockets = {}
|
||||
|
||||
@@ -284,6 +263,7 @@ class WebSocket(WebSocketHandler):
|
||||
self.wsm = app.get_websocket_manager()
|
||||
self.rpc = self.wsm.rpc
|
||||
self.uid = id(self)
|
||||
self.is_closed = False
|
||||
|
||||
async def open(self):
|
||||
await self.wsm.add_websocket(self)
|
||||
@@ -301,7 +281,7 @@ class WebSocket(WebSocketHandler):
|
||||
logging.exception("Websocket Command Error")
|
||||
|
||||
def send_status(self, status):
|
||||
if not status:
|
||||
if not status or self.is_closed:
|
||||
return
|
||||
try:
|
||||
self.write_message({
|
||||
@@ -309,13 +289,15 @@ class WebSocket(WebSocketHandler):
|
||||
'method': "notify_status_update",
|
||||
'params': [status]})
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(self.uid, None)
|
||||
logging.info(f"Websocket Removed: {self.uid}")
|
||||
self.is_closed = True
|
||||
logging.info(
|
||||
f"Websocket Closed During Status Update: {self.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {self.uid}")
|
||||
|
||||
def on_close(self):
|
||||
self.is_closed = True
|
||||
io_loop = IOLoop.current()
|
||||
io_loop.spawn_callback(self.wsm.remove_websocket, self)
|
||||
|
||||
|
||||
+84
-40
@@ -1,3 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# GCode metadata extraction utility
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
@@ -14,6 +15,10 @@ import traceback
|
||||
import io
|
||||
from PIL import Image
|
||||
|
||||
def log_to_stderr(msg):
|
||||
sys.stderr.write(f"{msg}\n")
|
||||
sys.stderr.flush()
|
||||
|
||||
# regex helpers
|
||||
def _regex_find_floats(pattern, data, strict=False):
|
||||
# If strict is enabled, pattern requires a floating point
|
||||
@@ -54,13 +59,13 @@ def _regex_find_first(pattern, data, cast=float):
|
||||
class BaseSlicer(object):
|
||||
def __init__(self, file_path):
|
||||
self.path = file_path
|
||||
self.header_data = self.footer_data = self.log = None
|
||||
self.header_data = self.footer_data = None
|
||||
self.layer_height = None
|
||||
|
||||
def set_data(self, header_data, footer_data, fsize, log):
|
||||
def set_data(self, header_data, footer_data, fsize):
|
||||
self.header_data = header_data
|
||||
self.footer_data = footer_data
|
||||
self.size = fsize
|
||||
self.log = log
|
||||
|
||||
def _parse_min_float(self, pattern, data, strict=False):
|
||||
result = _regex_find_floats(pattern, data, strict)
|
||||
@@ -145,12 +150,22 @@ class PrusaSlicer(BaseSlicer):
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
# Check percentage
|
||||
pct = _regex_find_first(
|
||||
r"; first_layer_height = (\d+)%", self.footer_data)
|
||||
if pct is not None:
|
||||
if self.layer_height is None:
|
||||
# Failed to parse the original layer height, so it is not
|
||||
# possible to calculate a percentage
|
||||
return None
|
||||
return round(pct / 100. * self.layer_height, 6)
|
||||
return _regex_find_first(
|
||||
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
self.layer_height = _regex_find_first(
|
||||
r"; layer_height = (\d+\.?\d*)", self.footer_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
matches = re.findall(
|
||||
@@ -191,24 +206,38 @@ class PrusaSlicer(BaseSlicer):
|
||||
r"; thumbnail begin[;/\+=\w\s]+?; thumbnail end", self.header_data)
|
||||
if not thumb_matches:
|
||||
return None
|
||||
thumb_dir = os.path.join(os.path.dirname(self.path), "thumbs")
|
||||
if not os.path.exists(thumb_dir):
|
||||
try:
|
||||
os.mkdir(thumb_dir)
|
||||
except Exception:
|
||||
log_to_stderr(f"Unable to create thumb dir: {thumb_dir}")
|
||||
return
|
||||
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
|
||||
parsed_matches = []
|
||||
for match in thumb_matches:
|
||||
lines = re.split(r"\r?\n", match.replace('; ', ''))
|
||||
info = _regex_find_ints(r".*", lines[0])
|
||||
data = "".join(lines[1:-1])
|
||||
if len(info) != 3:
|
||||
self.log.append(
|
||||
log_to_stderr(
|
||||
f"MetadataError: Error parsing thumbnail"
|
||||
f" header: {lines[0]}")
|
||||
continue
|
||||
if len(data) != info[2]:
|
||||
self.log.append(
|
||||
log_to_stderr(
|
||||
f"MetadataError: Thumbnail Size Mismatch: "
|
||||
f"detected {info[2]}, actual {len(data)}")
|
||||
continue
|
||||
thumb_name = f"{thumb_base}-{info[0]}x{info[1]}.png"
|
||||
thumb_path = os.path.join(thumb_dir, thumb_name)
|
||||
rel_thumb_path = os.path.join("thumbs", thumb_name)
|
||||
with open(thumb_path, "wb") as f:
|
||||
f.write(base64.b64decode(data.encode()))
|
||||
parsed_matches.append({
|
||||
'width': info[0], 'height': info[1],
|
||||
'size': info[2], 'data': data})
|
||||
'size': info[2], 'data': data,
|
||||
'relative_path': rel_thumb_path})
|
||||
return parsed_matches
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
@@ -259,7 +288,7 @@ class SuperSlicer(PrusaSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
class Cura(BaseSlicer):
|
||||
class Cura(PrusaSlicer):
|
||||
def check_identity(self, data):
|
||||
match = re.search(r"Cura_SteamEngine\s(.*)", data)
|
||||
if match:
|
||||
@@ -273,8 +302,9 @@ class Cura(BaseSlicer):
|
||||
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
self.layer_height = _regex_find_first(
|
||||
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
|
||||
@@ -298,36 +328,46 @@ class Cura(BaseSlicer):
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
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):
|
||||
# Attempt to parse thumbnails from file metadata
|
||||
thumbs = super().parse_thumbnails()
|
||||
if thumbs is not None:
|
||||
return thumbs
|
||||
# Check for thumbnails extracted from the ufp
|
||||
thumb_dir = os.path.join(os.path.dirname(self.path), "thumbs")
|
||||
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
|
||||
thumb_path = os.path.join(thumb_dir, f"{thumb_base}.png")
|
||||
rel_path_full = os.path.join("thumbs", f"{thumb_base}.png")
|
||||
rel_path_small = os.path.join("thumbs", f"{thumb_base}-32x32.png")
|
||||
thumb_path_small = os.path.join(thumb_dir, f"{thumb_base}-32x32.png")
|
||||
if not os.path.isfile(thumb_path):
|
||||
return None
|
||||
# read file
|
||||
thumbs = []
|
||||
try:
|
||||
with open(thumbPath, 'rb') as thumbFile:
|
||||
fbytes = thumbFile.read()
|
||||
with open(thumb_path, 'rb') as thumb_file:
|
||||
fbytes = thumb_file.read()
|
||||
with Image.open(io.BytesIO(fbytes)) as im:
|
||||
thumbFull = base64.b64encode(fbytes).decode()
|
||||
thumb_full_b64 = base64.b64encode(fbytes).decode()
|
||||
thumbs.append({
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbFull), 'data': thumbFull
|
||||
'size': len(thumb_full_b64), 'data': thumb_full_b64,
|
||||
'relative_path': rel_path_full
|
||||
})
|
||||
# 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()
|
||||
tmp_thumb = io.BytesIO()
|
||||
im.save(tmp_thumb, format="PNG")
|
||||
im.save(thumb_path_small, format="PNG")
|
||||
thumb_small_b64 = base64.b64encode(
|
||||
tmp_thumb.getbuffer()).decode()
|
||||
tmp_thumb.close()
|
||||
thumbs.insert(0, {
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbSmall), 'data': thumbSmall
|
||||
'size': len(thumb_small_b64), 'data': thumb_small_b64,
|
||||
'relative_path': rel_path_small
|
||||
})
|
||||
except Exception as e:
|
||||
self.log.append(str(e))
|
||||
log_to_stderr(str(e))
|
||||
return None
|
||||
return thumbs
|
||||
|
||||
@@ -345,8 +385,9 @@ class Simplify3D(BaseSlicer):
|
||||
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
self.layer_height = _regex_find_first(
|
||||
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
|
||||
@@ -413,8 +454,9 @@ class KISSlicer(BaseSlicer):
|
||||
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
self.layer_height = _regex_find_first(
|
||||
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(
|
||||
@@ -466,7 +508,8 @@ class IdeaMaker(BaseSlicer):
|
||||
layer_info = _regex_find_floats(
|
||||
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
|
||||
if len(layer_info) >= 3:
|
||||
return layer_info[2]
|
||||
self.layer_height = layer_info[2]
|
||||
return self.layer_height
|
||||
return None
|
||||
|
||||
def parse_object_height(self):
|
||||
@@ -508,9 +551,10 @@ class IceSL(BaseSlicer):
|
||||
self.header_data, float)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
self.layer_height = _regex_find_first(
|
||||
r"; z_layer_height_mm :\s+(\d+\.\d+)",
|
||||
self.header_data, float)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
return self._parse_max_float(
|
||||
@@ -530,12 +574,12 @@ SUPPORTED_SLICERS = [
|
||||
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
|
||||
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
|
||||
SUPPORTED_DATA = [
|
||||
'first_layer_height', 'layer_height', 'object_height',
|
||||
'layer_height', 'first_layer_height', 'object_height',
|
||||
'filament_total', 'estimated_time', 'thumbnails',
|
||||
'first_layer_bed_temp', 'first_layer_extr_temp',
|
||||
'gcode_start_byte', 'gcode_end_byte']
|
||||
|
||||
def extract_metadata(file_path, log):
|
||||
def extract_metadata(file_path):
|
||||
metadata = {}
|
||||
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
|
||||
header_data = footer_data = slicer = None
|
||||
@@ -563,7 +607,7 @@ def extract_metadata(file_path, log):
|
||||
footer_data = header_data[remaining - READ_SIZE:] + f.read()
|
||||
else:
|
||||
footer_data = header_data
|
||||
slicer.set_data(header_data, footer_data, size, log)
|
||||
slicer.set_data(header_data, footer_data, size)
|
||||
for key in SUPPORTED_DATA:
|
||||
func = getattr(slicer, "parse_" + key)
|
||||
result = func()
|
||||
@@ -573,18 +617,18 @@ def extract_metadata(file_path, log):
|
||||
|
||||
def main(path, filename):
|
||||
file_path = os.path.join(path, filename)
|
||||
log = []
|
||||
metadata = {}
|
||||
if not os.path.isfile(file_path):
|
||||
log.append(f"File Not Found: {file_path}")
|
||||
else:
|
||||
try:
|
||||
metadata = extract_metadata(file_path, log)
|
||||
except Exception:
|
||||
log.append(traceback.format_exc())
|
||||
log_to_stderr(f"File Not Found: {file_path}")
|
||||
sys.exit(-1)
|
||||
try:
|
||||
metadata = extract_metadata(file_path)
|
||||
except Exception:
|
||||
log_to_stderr(traceback.format_exc())
|
||||
sys.exit(-1)
|
||||
fd = sys.stdout.fileno()
|
||||
data = json.dumps(
|
||||
{'file': filename, 'log': log, 'metadata': metadata}).encode()
|
||||
{'file': filename, 'metadata': metadata}).encode()
|
||||
while data:
|
||||
try:
|
||||
ret = os.write(fd, data)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# Raspbian/Raspberry Pi OS based distributions.
|
||||
|
||||
PYTHONDIR="${HOME}/moonraker-env"
|
||||
SYSTEMDDIR="/etc/systemd/system"
|
||||
REBUILD_ENV="n"
|
||||
FORCE_DEFAULTS="n"
|
||||
CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
@@ -10,7 +11,7 @@ CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
# Step 1: Verify Klipper has been installed
|
||||
check_klipper()
|
||||
{
|
||||
if [ "$(systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
|
||||
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
|
||||
echo "Klipper service found!"
|
||||
else
|
||||
echo "Klipper service not found, please install Klipper first"
|
||||
@@ -19,10 +20,23 @@ check_klipper()
|
||||
|
||||
}
|
||||
|
||||
# Step 2: Install packages
|
||||
# Step 2: Clean up legacy installation
|
||||
cleanup_legacy() {
|
||||
if [ -f "/etc/init.d/moonraker" ]; then
|
||||
# Stop Moonraker Service
|
||||
echo "#### Cleanup legacy install script"
|
||||
sudo systemctl stop moonraker
|
||||
sudo update-rc.d -f moonraker remove
|
||||
sudo rm -f /etc/init.d/moonraker
|
||||
sudo rm -f /etc/default/moonraker
|
||||
fi
|
||||
}
|
||||
|
||||
# Step 3: Install packages
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
|
||||
PKGLIST="${PKGLIST} liblmdb0 rsync zlib1g-dev"
|
||||
|
||||
# Update system package info
|
||||
report_status "Running apt-get update..."
|
||||
@@ -33,7 +47,7 @@ install_packages()
|
||||
sudo apt-get install --yes ${PKGLIST}
|
||||
}
|
||||
|
||||
# Step 3: Create python virtual environment
|
||||
# Step 4: Create python virtual environment
|
||||
create_virtualenv()
|
||||
{
|
||||
report_status "Installing python virtual environment..."
|
||||
@@ -44,45 +58,50 @@ create_virtualenv()
|
||||
rm -rf ${PYTHONDIR}
|
||||
fi
|
||||
|
||||
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
|
||||
if [ ! -d ${PYTHONDIR} ]; then
|
||||
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
|
||||
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
|
||||
fi
|
||||
|
||||
# Install/update dependencies
|
||||
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
|
||||
}
|
||||
|
||||
# Step 4: Install startup script
|
||||
# Step 5: Install startup script
|
||||
install_script()
|
||||
{
|
||||
# Create systemd service file
|
||||
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
|
||||
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
report_status "Installing system start script..."
|
||||
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
|
||||
sudo update-rc.d moonraker defaults
|
||||
}
|
||||
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
|
||||
#Systemd service file for moonraker
|
||||
[Unit]
|
||||
Description=Starts Moonraker on startup
|
||||
After=network.target
|
||||
|
||||
# Step 5: Install startup script config
|
||||
install_config()
|
||||
{
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
|
||||
|
||||
report_status "Installing system start configuration..."
|
||||
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
|
||||
# Configuration for /etc/init.d/moonraker
|
||||
|
||||
MOONRAKER_USER=$USER
|
||||
|
||||
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
|
||||
|
||||
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=$USER
|
||||
RemainAfterExit=yes
|
||||
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
EOF
|
||||
# Use systemctl to enable the klipper systemd service script
|
||||
sudo systemctl enable moonraker.service
|
||||
}
|
||||
|
||||
|
||||
# Step 6: Start server
|
||||
start_software()
|
||||
{
|
||||
report_status "Launching Moonraker API Server..."
|
||||
sudo systemctl stop klipper
|
||||
sudo /etc/init.d/moonraker restart
|
||||
sudo systemctl restart moonraker
|
||||
sudo systemctl start klipper
|
||||
}
|
||||
|
||||
@@ -118,8 +137,8 @@ done
|
||||
# Run installation steps defined above
|
||||
verify_ready
|
||||
check_klipper
|
||||
cleanup_legacy
|
||||
install_packages
|
||||
create_virtualenv
|
||||
install_script
|
||||
install_config
|
||||
start_software
|
||||
@@ -1,4 +1,6 @@
|
||||
# Python dependencies for Moonraker
|
||||
tornado==6.1.0
|
||||
pyserial==3.4
|
||||
pillow==8.0.1
|
||||
pillow==8.1.2
|
||||
lmdb==1.1.1
|
||||
streaming-form-data==1.8.1
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/bin/sh
|
||||
# System startup script for Moonraker, Klipper's API Server
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: moonraker
|
||||
# Required-Start: $local_fs
|
||||
# Required-Stop:
|
||||
# X-Start-Before: $klipper
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: moonraker daemon
|
||||
# Description: Starts the Moonraker daemon
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
DESC="moonraker daemon"
|
||||
NAME="moonraker"
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
PIDFILE=/var/run/moonraker.pid
|
||||
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
# Read defaults file
|
||||
[ -r $DEFAULTS_FILE ] && . $DEFAULTS_FILE
|
||||
|
||||
case "$1" in
|
||||
start) log_daemon_msg "Starting moonraker" $NAME
|
||||
start-stop-daemon --start --quiet --exec $MOONRAKER_EXEC \
|
||||
--background --pidfile $PIDFILE --make-pidfile \
|
||||
--chuid $MOONRAKER_USER --user $MOONRAKER_USER \
|
||||
-- $MOONRAKER_ARGS
|
||||
log_end_msg $?
|
||||
;;
|
||||
stop) log_daemon_msg "Stopping moonraker" $NAME
|
||||
killproc -p $PIDFILE $MOONRAKER_EXEC
|
||||
RETVAL=$?
|
||||
[ $RETVAL -eq 0 ] && [ -e "$PIDFILE" ] && rm -f $PIDFILE
|
||||
log_end_msg $RETVAL
|
||||
;;
|
||||
restart) log_daemon_msg "Restarting moonraker" $NAME
|
||||
$0 stop
|
||||
$0 start
|
||||
;;
|
||||
reload|force-reload)
|
||||
log_daemon_msg "Reloading configuration not supported" $NAME
|
||||
log_end_msg 1
|
||||
;;
|
||||
status)
|
||||
status_of_proc -p $PIDFILE $MOONRAKER_EXEC $NAME && exit 0 || exit $?
|
||||
;;
|
||||
*) log_action_msg "Usage: /etc/init.d/moonraker {start|stop|status|restart|reload|force-reload}"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
#!/bin/bash
|
||||
|
||||
# moonraker-sudo (mnrkrsudo)
|
||||
# Provides a specified Group that is intended to elevate user privileges
|
||||
# to help moonraker with sudo actions, if in CustomPIOS Images with
|
||||
# Module "password-for-sudo".
|
||||
#
|
||||
# Partially used functions from Arcsine
|
||||
#
|
||||
# Copyright (C) 2020 Stephan Wendel <me@stephanwe.de>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
### Exit on Errors
|
||||
set -e
|
||||
|
||||
### Configuration
|
||||
|
||||
SUDOERS_DIR='/etc/sudoers.d'
|
||||
SUDOERS_FILE='020-sudo-for-moonraker'
|
||||
NEW_GROUP='mnrkrsudo'
|
||||
|
||||
|
||||
### Functions
|
||||
|
||||
verify_ready()
|
||||
{
|
||||
if [ "$EUID" -eq 0 ]; then
|
||||
echo "This script must not run as root"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
create_sudoers_file()
|
||||
{
|
||||
|
||||
SCRIPT_TEMP_PATH=/tmp
|
||||
|
||||
report_status "Creating ${SUDOERS_FILE} ..."
|
||||
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
sudo sed "s/GROUPNAME/$NEW_GROUP/g" > $SCRIPT_TEMP_PATH/$SUDOERS_FILE << '#EOF'
|
||||
|
||||
### Elevate moonraker API rights
|
||||
### Do NOT allow Command Parts only Full Commands
|
||||
### for example
|
||||
###
|
||||
### /sbin/systemctl "reboot", /sbin/apt "update", .....
|
||||
|
||||
Defaults!/usr/bin/apt-get env_keep +="DEBIAN_FRONTEND"
|
||||
|
||||
Cmnd_Alias REBOOT = /sbin/shutdown -r now, /bin/systemctl "reboot"
|
||||
Cmnd_Alias SHUTDOWN = /sbin/shutdown now, /sbin/shutdown -h now, /bin/systemctl "poweroff"
|
||||
Cmnd_Alias APT = /usr/bin/apt-get
|
||||
Cmnd_Alias SYSTEMCTL = /bin/systemctl
|
||||
|
||||
|
||||
|
||||
%GROUPNAME ALL=(ALL) NOPASSWD: REBOOT, SHUTDOWN, APT, SYSTEMCTL
|
||||
|
||||
#EOF
|
||||
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
update_env()
|
||||
{
|
||||
report_status "Export System Variable: DEBIAN_FRONTEND=noninteractive"
|
||||
sudo /bin/sh -c 'echo "DEBIAN_FRONTEND=noninteractive" >> /etc/environment'
|
||||
}
|
||||
|
||||
verify_syntax()
|
||||
{
|
||||
report_status "\e[1;33mVerifying Syntax of ${SUDOERS_FILE}\e[0m\n"
|
||||
|
||||
if [ $(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE | grep -c "OK" ) -eq 1 ];
|
||||
then
|
||||
VERIFY_STATUS=0
|
||||
report_status "\e[1;32m$(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE)\e[0m"
|
||||
else
|
||||
report_status "\e[1;31mSyntax Error:\e[0m Check File: $SCRIPT_TEMP_PATH/$SUDOERS_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
}
|
||||
|
||||
install_sudoers_file()
|
||||
{
|
||||
verify_syntax
|
||||
if [ $VERIFY_STATUS -eq 0 ];
|
||||
then
|
||||
report_status "Copying $SCRIPT_TEMP_PATH/$SUDOERS_FILE to $SUDOERS_DIR/$SUDOERS_FILE"
|
||||
sudo chmod 0440 $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
sudo cp --preserve=mode $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
check_update_sudoers_file()
|
||||
{
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
|
||||
then
|
||||
create_sudoers_file
|
||||
if [ -z $(sudo diff $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE) ]
|
||||
then
|
||||
report_status "No need to update $SUDOERS_DIR/$SUDOERS_FILE"
|
||||
else
|
||||
report_status "$SUDOERS_DIR/$SUDOERS_FILE needs to be updated."
|
||||
install_sudoers_file
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
add_new_group()
|
||||
{
|
||||
sudo addgroup --system $NEW_GROUP &> /dev/null
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
add_user_to_group()
|
||||
{
|
||||
sudo usermod -aG $NEW_GROUP $USER &> /dev/null
|
||||
report_status "\e[1;32m...done\e[0m"
|
||||
}
|
||||
|
||||
adduser_hint()
|
||||
{
|
||||
report_status "\e[1;31mYou have to REBOOT to take changes effect!\e[0m"
|
||||
}
|
||||
|
||||
# Helper functions
|
||||
report_status()
|
||||
{
|
||||
echo -e "\n\n###### $1"
|
||||
}
|
||||
|
||||
clean_temp()
|
||||
{
|
||||
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
|
||||
}
|
||||
### Main
|
||||
|
||||
verify_ready
|
||||
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ] && [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ] && [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
|
||||
then
|
||||
check_update_sudoers_file
|
||||
report_status "\e[1;32mEverything is setup, nothing to do...\e[0m\n"
|
||||
exit 0
|
||||
|
||||
else
|
||||
|
||||
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
|
||||
then
|
||||
report_status "\e[1;32mFile exists:\e[0m ${SUDOERS_FILE}"
|
||||
check_update_sudoers_file
|
||||
else
|
||||
report_status "\e[1;31mFile not found:\e[0m ${SUDOERS_FILE}\n"
|
||||
create_sudoers_file
|
||||
install_sudoers_file
|
||||
fi
|
||||
|
||||
if [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ];
|
||||
then
|
||||
report_status "Group ${NEW_GROUP} already exists..."
|
||||
else
|
||||
report_status "Group ${NEW_GROUP} will be added..."
|
||||
add_new_group
|
||||
fi
|
||||
|
||||
if [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
|
||||
then
|
||||
report_status "User ${USER} is already in $NEW_GROUP..."
|
||||
else
|
||||
report_status "Adding User ${USER} to Group $NEW_GROUP..."
|
||||
add_user_to_group
|
||||
adduser_hint
|
||||
fi
|
||||
fi
|
||||
|
||||
update_env
|
||||
clean_temp
|
||||
exit 0
|
||||
@@ -4,20 +4,25 @@
|
||||
stop_service() {
|
||||
# Stop Moonraker Service
|
||||
echo "#### Stopping Moonraker Service.."
|
||||
sudo service moonraker stop
|
||||
sudo systemctl stop moonraker
|
||||
}
|
||||
|
||||
remove_service() {
|
||||
# Remove Moonraker from Startup
|
||||
echo
|
||||
echo "#### Removing Moonraker from Startup.."
|
||||
sudo update-rc.d -f moonraker remove
|
||||
|
||||
# Remove Moonraker from Services
|
||||
# Remove Moonraker LSB/systemd service
|
||||
echo
|
||||
echo "#### Removing Moonraker Service.."
|
||||
sudo rm -f /etc/init.d/moonraker /etc/default/moonraker
|
||||
|
||||
if [ -f "/etc/init.d/moonraker" ]; then
|
||||
# legacy installation, remove the LSB service
|
||||
sudo update-rc.d -f moonraker remove
|
||||
sudo rm -f /etc/init.d/moonraker
|
||||
sudo rm -f /etc/default/moonraker
|
||||
else
|
||||
# Remove systemd installation
|
||||
sudo systemctl disable moonraker
|
||||
sudo rm -f /etc/systemd/system/moonraker.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl reset-failed
|
||||
fi
|
||||
}
|
||||
|
||||
remove_files() {
|
||||
@@ -47,6 +52,9 @@ remove_files() {
|
||||
echo
|
||||
echo "The following command is typically used to remove source files:"
|
||||
echo " rm -rf ~/moonraker"
|
||||
echo
|
||||
echo "You may also wish to uninstall nginx:"
|
||||
echo " sudo apt-get remove nginx"
|
||||
}
|
||||
|
||||
verify_ready()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Supplemental configuration for Moonraker's Update Manager
|
||||
# component. This file should not be modified.
|
||||
|
||||
[update_manager static debian moonraker]
|
||||
origin: https://github.com/arksine/moonraker.git
|
||||
requirements: scripts/moonraker-requirements.txt
|
||||
venv_args: -p python3
|
||||
install_script: scripts/install-moonraker.sh
|
||||
python_dist_path: /usr/lib/python3/dist-packages
|
||||
env_package_path: lib/python*/site-packages
|
||||
python_dist_packages:
|
||||
gpiod
|
||||
|
||||
[update_manager static debian klipper]
|
||||
origin: https://github.com/kevinoconnor/klipper.git
|
||||
requirements: scripts/klippy-requirements.txt
|
||||
venv_args: -p python2
|
||||
install_script: scripts/install-octopi.sh
|
||||
python_dist_path: /usr/lib/python2.7/dist-packages
|
||||
env_package_path: lib/python*/site-packages
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
env_version=0.2.1
|
||||
deps_version=0.2.1
|
||||
env_version=0.2.6
|
||||
deps_version=0.4.1
|
||||
@@ -738,6 +738,10 @@ function handle_power_changed(power_status) {
|
||||
json_rpc.register_method("notify_power_changed", handle_power_changed);
|
||||
|
||||
function handle_update_response(response) {
|
||||
if (response.complete === true) {
|
||||
console.log("Update complete");
|
||||
console.log(response);
|
||||
}
|
||||
update_term(response.message)
|
||||
}
|
||||
json_rpc.register_method("notify_update_response", handle_update_response);
|
||||
|
||||
Reference in new issue
Block a user