Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d549af915f | ||
|
|
672c223cc6 | ||
|
|
68c5fb6f6b | ||
|
|
fce056e481 | ||
|
|
a02209443e | ||
|
|
2cda75ff2c | ||
|
|
0e80e301f0 | ||
|
|
e32fd688e4 | ||
|
|
5a504243df | ||
|
|
7520d0e7b1 | ||
|
|
5ffd18d132 | ||
|
|
79467e6484 | ||
|
|
277aecd305 | ||
|
|
f48c18bfda | ||
|
|
a3121775fc | ||
|
|
a5790d4b84 | ||
|
|
b50057c3ba | ||
|
|
15f37827a1 | ||
|
|
0f8638fec7 | ||
|
|
b9a17e07e9 | ||
|
|
a5d63db9a6 | ||
|
|
1e7be4598c | ||
|
|
833519ecc3 | ||
|
|
dce3b9eaf5 | ||
|
|
9178b3833c | ||
|
|
522fdab63d | ||
|
|
7845390dd1 | ||
|
|
0f7b781f57 | ||
|
|
347c9f4d2b | ||
|
|
2fd668bf0d | ||
|
|
1e97571aa8 | ||
|
|
7330c2c123 | ||
|
|
51e307dbd6 | ||
|
|
45506647a7 | ||
|
|
3917c9cd56 | ||
|
|
b2ba52ce3d | ||
|
|
0a811b9e44 | ||
|
|
36de982692 | ||
|
|
a8c82b4560 | ||
|
|
7dac9c3961 | ||
|
|
d39792b84e | ||
|
|
9f08aad6f6 | ||
|
|
87dba2f2e2 | ||
|
|
a40dae2bc8 | ||
|
|
bec9a66411 | ||
|
|
dbd1b4ac1b | ||
|
|
9b9a6d0646 | ||
|
|
0b4e604c95 | ||
|
|
5661b0216c | ||
|
|
55ebe120c5 | ||
|
|
0de712e822 | ||
|
|
5325693ed6 | ||
|
|
8c7b93c6dd | ||
|
|
25d2ad4af6 | ||
|
|
3710d49f46 | ||
|
|
c5c6366a84 | ||
|
|
ea4ec1f424 | ||
|
|
8010f1dda2 | ||
|
|
f0b82afde4 | ||
|
|
645f0c9acf | ||
|
|
d70dfaeebd | ||
|
|
b02224485e | ||
|
|
d9579c9374 | ||
|
|
c69441955a | ||
|
|
5aa645f974 | ||
|
|
2fb136449a | ||
|
|
8335906443 | ||
|
|
5807757efa | ||
|
|
0db655b9d6 | ||
|
|
385b9a1b7a | ||
|
|
d75831f10a | ||
|
|
c331c5a7d7 | ||
|
|
4ff7a50821 | ||
|
|
90c7b80f37 | ||
|
|
83e0947d31 | ||
|
|
4af483c786 | ||
|
|
559df5aea1 | ||
|
|
f9086181b8 | ||
|
|
198bff6aba | ||
|
|
01977c8775 | ||
|
|
c8ad69b902 | ||
|
|
f50fa3c5e7 | ||
|
|
21a7928ea2 | ||
|
|
76500fe9f9 | ||
|
|
a413f4e4cd | ||
|
|
1be19be747 | ||
|
|
babf97be3b | ||
|
|
61d3182bea | ||
|
|
c1e4142a40 | ||
|
|
b02e766a4d | ||
|
|
fb618a46fd | ||
|
|
55e852cd87 | ||
|
|
1bad68cb66 | ||
|
|
6c4c7a00cf | ||
|
|
50d22a2dff | ||
|
|
46a92e1900 | ||
|
|
2392ccd719 | ||
|
|
12b1befcbc | ||
|
|
3dbc99fd84 | ||
|
|
d8941b3fb2 | ||
|
|
a5161816a7 | ||
|
|
80862799ed | ||
|
|
06ec5541e3 | ||
|
|
eca4c7e438 | ||
|
|
9d6719ed31 | ||
|
|
5a22b21a40 | ||
|
|
4ca39bec0a | ||
|
|
c83714bfe8 | ||
|
|
d4378eb051 | ||
|
|
c964e68bc8 | ||
|
|
2ad7a6a087 | ||
|
|
db81607370 | ||
|
|
a154c5fa51 | ||
|
|
c9a1d0f3bb | ||
|
|
bf63798bb1 | ||
|
|
3400094881 | ||
|
|
486f659d20 | ||
|
|
a4b496d135 | ||
|
|
fe9a9899e3 | ||
|
|
6021b39234 | ||
|
|
53eda78b11 | ||
|
|
24dc8914d0 | ||
|
|
ecf7fb9267 | ||
|
|
019c5fc416 | ||
|
|
225ec588eb | ||
|
|
690f841768 | ||
|
|
b3a9447392 | ||
|
|
e3bcfb5ea0 | ||
|
|
358aee956b | ||
|
|
1999b82a86 | ||
|
|
d6b1a724a8 | ||
|
|
3d3911d4fd | ||
|
|
aeea9a2efd | ||
|
|
a6b8a8a3e9 | ||
|
|
51fee3e7a1 | ||
|
|
f7d8af6e12 | ||
|
|
129b0feb81 | ||
|
|
f296c6fadd | ||
|
|
dde9bcc752 | ||
|
|
1cb46a8f8f | ||
|
|
f3f39b7ab0 | ||
|
|
f3e13faf19 | ||
|
|
7b8c2c3409 | ||
|
|
b67a08a65b | ||
|
|
c61ff8b252 | ||
|
|
362bc1a3d3 | ||
|
|
48f3bb2189 | ||
|
|
e628b243c2 | ||
|
|
88ebc21318 | ||
|
|
68f5de6d2d | ||
|
|
bfe20433f9 | ||
|
|
bd1fd63b14 | ||
|
|
7afd556c21 | ||
|
|
8b2e8c2a4e | ||
|
|
490d27b7de | ||
|
|
0c6e860534 | ||
|
|
7f58f2274e | ||
|
|
b2d109a840 | ||
|
|
53129bef7e | ||
|
|
f089794adc | ||
|
|
5a3b1b6e5c | ||
|
|
ddf3325dae | ||
|
|
bb7cd27be5 | ||
|
|
a8018afd46 | ||
|
|
d490796da9 | ||
|
|
36536535bc | ||
|
|
b291d94596 | ||
|
|
484950cb40 | ||
|
|
e8dad1c8c0 | ||
|
|
130c2a48f0 | ||
|
|
6f43940270 | ||
|
|
779997c2b8 | ||
|
|
1a3689cb7d | ||
|
|
1ef34b8b60 | ||
|
|
80a7d461ed | ||
|
|
4c963de0fc | ||
|
|
6afa664ac9 | ||
|
|
379bcb10f9 | ||
|
|
8540f5a794 | ||
|
|
1f86943cbb | ||
|
|
4df0b4d532 | ||
|
|
1190aba4b7 | ||
|
|
25adba0bf6 | ||
|
|
974b37dad8 | ||
|
|
8f444a908e | ||
|
|
59cc8c6c7b | ||
|
|
e4a670a380 | ||
|
|
74f43cad6e | ||
|
|
c7e290a3cd | ||
|
|
38b035389d | ||
|
|
1f1c590409 | ||
|
|
6131c7afc1 | ||
|
|
4954cc74cd | ||
|
|
f745c2ce17 | ||
|
|
d6bdad3a9d | ||
|
|
9a466f3b22 | ||
|
|
a8cbfe6345 | ||
|
|
6b3c78da71 | ||
|
|
b981dc109d | ||
|
|
f1c4d6b143 | ||
|
|
7552631b65 | ||
|
|
06279d0e10 | ||
|
|
7e35e54a71 | ||
|
|
05ca71f5a8 | ||
|
|
3ad7d0668a | ||
|
|
b9cac62db8 | ||
|
|
65e24a14dc | ||
|
|
53fcc7386f | ||
|
|
00c4846d11 | ||
|
|
f0e4678fab | ||
|
|
fb327a6ca9 | ||
|
|
500e8f3b68 | ||
|
|
fb679aa056 | ||
|
|
2603cc2e8f | ||
|
|
485b29490a | ||
|
|
1e8c7f0915 | ||
|
|
30e2ec04b7 | ||
|
|
86fc1057f7 | ||
|
|
d2cbd1d0a0 | ||
|
|
485c723a3c | ||
|
|
9021fbea48 | ||
|
|
be9aff8b5e | ||
|
|
f22b859a0f | ||
|
|
26088cdfff | ||
|
|
41ea45a486 | ||
|
|
c3cd24b3bf | ||
|
|
266c5b53d1 | ||
|
|
d3484e8c13 | ||
|
|
59471a7959 | ||
|
|
dd7e480cdd | ||
|
|
577f55306e | ||
|
|
636aca6cbd | ||
|
|
5259a6fd0a | ||
|
|
6e56815b42 | ||
|
|
7004722499 | ||
|
|
7217b36f9b | ||
|
|
069a655df8 | ||
|
|
4df6aba6c0 | ||
|
|
1327602ec3 | ||
|
|
524552eb84 | ||
|
|
480ebfac8e | ||
|
|
b78cdf9660 | ||
|
|
edaeb17f38 | ||
|
|
91e48200d6 | ||
|
|
c48fe7307a | ||
|
|
48674a46e1 | ||
|
|
785213b2b3 | ||
|
|
6e121c2221 | ||
|
|
d5fa40df87 | ||
|
|
f8d15d3baa | ||
|
|
2e3188a48b | ||
|
|
cd19b51117 | ||
|
|
60b871adbe | ||
|
|
df24e3ea77 | ||
|
|
07f4643070 | ||
|
|
621739bb2b | ||
|
|
4806ffd2ae | ||
|
|
21bb17743f | ||
|
|
5d856b9c49 | ||
|
|
f047167b3b | ||
|
|
d04e99a8ec | ||
|
|
7f2d43de3d | ||
|
|
3a03f48e0f | ||
|
|
25e79c78b2 | ||
|
|
b52b0bd98a | ||
|
|
e8999363ed | ||
|
|
78605db001 | ||
|
|
e3cafb58bc | ||
|
|
db7474aa88 | ||
|
|
272f7b946d | ||
|
|
59403e226b | ||
|
|
25d99207f0 | ||
|
|
fd5053ecac | ||
|
|
2314ea74c2 | ||
|
|
942d595bc2 | ||
|
|
e82fe46c11 | ||
|
|
0d936d5af0 | ||
|
|
0dd8eee034 | ||
|
|
a4f9fbe298 | ||
|
|
a776f1f6dc | ||
|
|
4b25b04c4f | ||
|
|
b5e7a5ba5a | ||
|
|
c24fd7d11c | ||
|
|
b7768671aa | ||
|
|
12161d12f5 | ||
|
|
4efb6575b7 | ||
|
|
c154d92499 | ||
|
|
a7b50a8068 | ||
|
|
cd24b116c6 | ||
|
|
66f9184c74 | ||
|
|
49b3f78f20 | ||
|
|
97c8b05eee | ||
|
|
853de9e8cb | ||
|
|
413e3b2f4f | ||
|
|
3424f1b3e2 | ||
|
|
c4e370fcff | ||
|
|
8bbd269084 | ||
|
|
a9345d19fa | ||
|
|
71e9085778 | ||
|
|
39f26dc31a | ||
|
|
6e253b0d42 | ||
|
|
0188b81d4a | ||
|
|
e0cf635d34 | ||
|
|
ea29788ab1 | ||
|
|
c251a9d7ed | ||
|
|
cd8954e36c | ||
|
|
5d4db16fd6 | ||
|
|
e264fa82b2 | ||
|
|
a178a6cd01 | ||
|
|
bdd0222a1c | ||
|
|
d713076947 | ||
|
|
6b4020a6e9 | ||
|
|
a3cae26e33 | ||
|
|
cd6db1ee75 | ||
|
|
16327ff551 | ||
|
|
7cd29c068d | ||
|
|
9fea1634b1 | ||
|
|
bcb7a55996 | ||
|
|
4d803ec9e5 | ||
|
|
3080885257 | ||
|
|
53a3c64186 | ||
|
|
d37f91c9c8 | ||
|
|
31d4335e3e | ||
|
|
835e49c10e | ||
|
|
0a0993f9e0 | ||
|
|
09550af466 | ||
|
|
0b31d7d0b2 | ||
|
|
371840a988 | ||
|
|
1eaead1073 | ||
|
|
4bed314b0a | ||
|
|
8266376f46 | ||
|
|
58fa361c8c | ||
|
|
a8b9fc0017 | ||
|
|
d19471fd4d | ||
|
|
14ec8472ef | ||
|
|
a492ae983c | ||
|
|
65d532a6cf | ||
|
|
7780a8a09e | ||
|
|
f52df8c7ed | ||
|
|
5081321a32 | ||
|
|
d0cdd76bed | ||
|
|
250b93e89c | ||
|
|
3b76d81155 | ||
|
|
a86cbc77f6 | ||
|
|
7af8a03129 | ||
|
|
74d6e35166 | ||
|
|
d53cf27264 | ||
|
|
f15ec23c3a | ||
|
|
0164bb239e | ||
|
|
babfba1686 | ||
|
|
09ac00ce2e | ||
|
|
3d9f5dc6d9 | ||
|
|
56097a35ad | ||
|
|
fcfa563d02 | ||
|
|
59f2736bb6 | ||
|
|
2f09b74dc1 | ||
|
|
cd520ba917 | ||
|
|
94a11ff291 | ||
|
|
11beaa7076 | ||
|
|
6f2ce72b4c | ||
|
|
c1eda1ef3d | ||
|
|
f8a38abc89 | ||
|
|
985760c584 | ||
|
|
d84f93d381 | ||
|
|
3ddbb9553d | ||
|
|
b06f782665 | ||
|
|
4be8e2e72f | ||
|
|
65946ef857 | ||
|
|
bbd5d8a1a1 | ||
|
|
430c2550c5 | ||
|
|
fe84226908 | ||
|
|
d3003a1584 | ||
|
|
47c6245c3f | ||
|
|
e0eded70e8 | ||
|
|
4666458793 | ||
|
|
da864ab391 | ||
|
|
cbc02d625c | ||
|
|
a79e0eeef2 | ||
|
|
236a7a7736 | ||
|
|
1133c296b1 | ||
|
|
d5a55047ab | ||
|
|
f6876c15e4 | ||
|
|
3a21e9d6f0 | ||
|
|
b296444091 | ||
|
|
7631999c8f | ||
|
|
b21f909705 | ||
|
|
eb6aeddf78 | ||
|
|
2096c380c4 | ||
|
|
0f70037ffc | ||
|
|
536871ad18 | ||
|
|
77027d252e | ||
|
|
bf19bcecae | ||
|
|
fc6714b30d | ||
|
|
ad00e08d11 | ||
|
|
2e4814978f | ||
|
|
fb2eacf702 | ||
|
|
ea25cce38f | ||
|
|
f27daac4f4 | ||
|
|
5f5f40293e | ||
|
|
ac6cf0fac7 | ||
|
|
7692197678 | ||
|
|
a706d23cfa | ||
|
|
82a22b287f | ||
|
|
366e68c8f4 | ||
|
|
fe3b7456f6 | ||
|
|
e05aeac884 | ||
|
|
071a430159 | ||
|
|
7c1d6a8f24 | ||
|
|
18169f279e | ||
|
|
393cfa2a0e | ||
|
|
9c33eb225c | ||
|
|
d61540cad5 | ||
|
|
58228ec161 | ||
|
|
5c9409c28d | ||
|
|
72a85e08d4 | ||
|
|
238b08ea1f | ||
|
|
6afc70a9f5 | ||
|
|
03934d8d81 | ||
|
|
58ea3cfdc7 | ||
|
|
f965ce8fd8 | ||
|
|
e9e86c3042 | ||
|
|
54081612ca | ||
|
|
93b62236de | ||
|
|
c8042a5700 | ||
|
|
16737d086d | ||
|
|
a4019bce8e | ||
|
|
f3b0fbaa34 | ||
|
|
5643c0ffbe | ||
|
|
13bb624bd7 | ||
|
|
156e9652e1 | ||
|
|
2edbba3b53 | ||
|
|
8d49a5d5ee | ||
|
|
9b5b3cc506 | ||
|
|
1968beaa0d | ||
|
|
d11357e5f2 | ||
|
|
8bb020edc6 | ||
|
|
b85f3081ab | ||
|
|
8c7247acbb | ||
|
|
be2e8623b9 | ||
|
|
060ca56fae | ||
|
|
384ab71d72 | ||
|
|
242fabe7ad | ||
|
|
d74d1e7612 | ||
|
|
829b3b5c98 | ||
|
|
5757347994 | ||
|
|
81a482f83d | ||
|
|
64b6029559 | ||
|
|
cd03b91f87 | ||
|
|
88b0282900 | ||
|
|
561f5f4230 | ||
|
|
4b0685852e | ||
|
|
1bdedd009f | ||
|
|
ac8c44095a | ||
|
|
209ace4728 | ||
|
|
3b208c6889 | ||
|
|
b1cc766576 | ||
|
|
4a6732f13a | ||
|
|
790d77756e | ||
|
|
27466984df | ||
|
|
faf956c65d | ||
|
|
5bf112bcbc | ||
|
|
0abb831ea0 | ||
|
|
43b19d8a83 | ||
|
|
4b27e5e41d | ||
|
|
d20d2fd07e | ||
|
|
ee312ee9c6 | ||
|
|
a700725681 | ||
|
|
efeea0d8e1 | ||
|
|
052dd5e338 | ||
|
|
3667e0d41f | ||
|
|
b86e86aff2 | ||
|
|
221df0937d | ||
|
|
26d6ca009a | ||
|
|
94c51c9412 | ||
|
|
9d49659884 | ||
|
|
553f8862b5 | ||
|
|
b6fc692500 | ||
|
|
6065e9a0fe | ||
|
|
c87d8d2e51 | ||
|
|
f93fed62ae | ||
|
|
c165c40146 | ||
|
|
970c8a4181 | ||
|
|
0d93cf2c39 | ||
|
|
8f7f824a47 | ||
|
|
65e76aeec8 | ||
|
|
ab09364a98 | ||
|
|
2bc43ec3df | ||
|
|
fd8bde7185 | ||
|
|
a32bf4a47a | ||
|
|
3a384e62dd | ||
|
|
ed20223614 | ||
|
|
79f867ba83 | ||
|
|
0a2c1904c0 | ||
|
|
71de8def8e | ||
|
|
501af62018 | ||
|
|
1fbfb90500 | ||
|
|
54f2ee61d0 | ||
|
|
7679f8063f | ||
|
|
f83f476f81 | ||
|
|
8b8cb66481 | ||
|
|
8ff54e2372 | ||
|
|
7ab1dda772 | ||
|
|
2b1a3e5603 | ||
|
|
86469903f3 | ||
|
|
3edb4b1bad | ||
|
|
f2f1d413d4 | ||
|
|
55baad1ad0 | ||
|
|
81f2418d78 | ||
|
|
348d45e87c | ||
|
|
e6b4e54bea | ||
|
|
6946f67dbf | ||
|
|
f7f487ac18 | ||
|
|
888fb58c4f | ||
|
|
2b7a5ff035 | ||
|
|
d630b79e8b | ||
|
|
5f96822c90 | ||
|
|
2d28a3eeff | ||
|
|
96b00549cf | ||
|
|
0bd12c8dec | ||
|
|
f3cd177a02 | ||
|
|
11e299558d | ||
|
|
bb39a3c1b2 | ||
|
|
89e78b9a00 | ||
|
|
c1104617b6 | ||
|
|
3c92f42d49 | ||
|
|
9ab6d0e83d | ||
|
|
c081fa49a1 | ||
|
|
9e57db0611 | ||
|
|
0dd10ce116 | ||
|
|
b43f4623fc | ||
|
|
46f74329d3 | ||
|
|
e2a62f80d4 | ||
|
|
e029b6c582 | ||
|
|
65d1f23352 | ||
|
|
781e3e6250 | ||
|
|
4d0a43cb25 | ||
|
|
e754d123dd | ||
|
|
43c1b998b0 | ||
|
|
e895b10ac3 | ||
|
|
1be639b99a | ||
|
|
ac55b95c1d | ||
|
|
5f9706f6be | ||
|
|
34f607c061 | ||
|
|
11f4ae75cc | ||
|
|
f79439aedd | ||
|
|
c2861a1391 | ||
|
|
e2d92b5575 | ||
|
|
0e27a949af | ||
|
|
10703321b0 | ||
|
|
0dc05eac76 | ||
|
|
d01b8a9763 | ||
|
|
b60153c919 | ||
|
|
ee11ed2a15 | ||
|
|
9be93ff445 | ||
|
|
ecfad5cff1 | ||
|
|
92eda982ce | ||
|
|
cb5ac86af7 | ||
|
|
94a2949c00 | ||
|
|
b4ddffd5d1 | ||
|
|
737cf8a2cb | ||
|
|
6efcffa028 | ||
|
|
a04e91c046 | ||
|
|
9e9f9ee0fd | ||
|
|
1072958534 | ||
|
|
a5eff12131 | ||
|
|
0f7af929f1 | ||
|
|
47f0437973 | ||
|
|
a5c49e8742 | ||
|
|
35d8d88855 | ||
|
|
f6d8de2cee | ||
|
|
6749d3836e | ||
|
|
509759ba0d | ||
|
|
5a966836b5 | ||
|
|
4ec781d66b | ||
|
|
ae8cab356b | ||
|
|
305e002f8c | ||
|
|
0b13e2da44 | ||
|
|
aca7cb78b9 | ||
|
|
10ac044485 | ||
|
|
f616c83ebc | ||
|
|
5ec98cf0ba | ||
|
|
de796a9ec7 | ||
|
|
13591d0a5b | ||
|
|
b4ad6692e3 | ||
|
|
287982acdd | ||
|
|
7c8c0e715f | ||
|
|
468ea36bba | ||
|
|
d396dbd2cb | ||
|
|
471885c3a2 | ||
|
|
7401192478 | ||
|
|
ede671f0df | ||
|
|
14f1b6f936 | ||
|
|
6aecd7b26d | ||
|
|
b1a232efce | ||
|
|
4d473969db | ||
|
|
a92847771d | ||
|
|
0e6fbb12b0 | ||
|
|
744f14d6f9 | ||
|
|
0dbb6d51a8 | ||
|
|
4ddd77430a | ||
|
|
3b27ab49f1 | ||
|
|
be338ad039 | ||
|
|
73f0d5503d | ||
|
|
0d6791a320 | ||
|
|
9b6161a6b0 | ||
|
|
f4c5e808c3 | ||
|
|
89d0bbdb63 | ||
|
|
8546cd6ac5 | ||
|
|
9911b5c7dd | ||
|
|
41c19e4b9a | ||
|
|
0c5a0fd979 | ||
|
|
209bdc18da | ||
|
|
04477705b0 | ||
|
|
7fcd84bbe4 | ||
|
|
1cac7399f9 | ||
|
|
f5ceefbb8d | ||
|
|
e103accdfb | ||
|
|
09689143b5 | ||
|
|
5f54a23f3e | ||
|
|
60f2e3e1c7 | ||
|
|
dd6a06e9de | ||
|
|
4c99f99cf0 | ||
|
|
693a34d562 | ||
|
|
3cbc2c2ca8 | ||
|
|
cfd3d63a0d | ||
|
|
59fd35827e | ||
|
|
4c087612d8 | ||
|
|
2025332e6f | ||
|
|
a652845843 | ||
|
|
27c65e0a64 | ||
|
|
3bd5f7edbd | ||
|
|
fc5e34096a | ||
|
|
9346186337 | ||
|
|
505c1bfdba | ||
|
|
6c8e3690a7 | ||
|
|
2c732b7afa | ||
|
|
d145442d4b | ||
|
|
20d3c9961d | ||
|
|
9d7baa1eb6 | ||
|
|
d997fd637a | ||
|
|
05af4babb9 | ||
|
|
7c5d840c1b | ||
|
|
5f20dafadb | ||
|
|
1d1ce0671d | ||
|
|
adfe8a67b6 | ||
|
|
0a541bbea1 | ||
|
|
1e440741da | ||
|
|
c5fd863bb7 | ||
|
|
a269de5dc0 | ||
|
|
a4f960d40c | ||
|
|
9dadf50ac6 | ||
|
|
d498eefd13 | ||
|
|
f4e3803647 | ||
|
|
51ca383591 | ||
|
|
01245ea8a1 | ||
|
|
92954245fa | ||
|
|
57b00cb33a | ||
|
|
5f7c6d623c | ||
|
|
cc1a55a871 | ||
|
|
5766d16edc | ||
|
|
ec43f5e9b6 | ||
|
|
e2fb1cc931 | ||
|
|
e46b4994d4 | ||
|
|
b369173f94 | ||
|
|
ac9eaa7681 | ||
|
|
3e70e4b4ce | ||
|
|
1333413db7 | ||
|
|
7d1cf435f7 | ||
|
|
828be30466 | ||
|
|
d7bfb7744a | ||
|
|
d0b1621bd5 | ||
|
|
f57bddfe4a | ||
|
|
3ac8f8cd81 | ||
|
|
e2b821e90c | ||
|
|
2142d344dd | ||
|
|
3f7cc53baa | ||
|
|
31dd758d52 | ||
|
|
a4abec43d5 | ||
|
|
c6cddf4b05 | ||
|
|
c69ded21b0 | ||
|
|
08111415be | ||
|
|
56a98aa8ed | ||
|
|
511c91829a | ||
|
|
ae4c4ad678 | ||
|
|
df674ae476 | ||
|
|
5dadc2067d | ||
|
|
4e625aef37 | ||
|
|
69a06dd12a | ||
|
|
2216e85fef | ||
|
|
54abd27486 | ||
|
|
f5f87bf08c | ||
|
|
18b84b8d9f | ||
|
|
ec29787edd | ||
|
|
1ad83cec97 | ||
|
|
ac73036857 | ||
|
|
c0c34ea045 | ||
|
|
7b9c6c5e77 | ||
|
|
6a90bfa480 | ||
|
|
8c12c137d0 | ||
|
|
f22e16d8cc | ||
|
|
6852982406 | ||
|
|
d884e5288c | ||
|
|
b1c9a96040 | ||
|
|
cfa5f4a432 | ||
|
|
b3d2307d36 | ||
|
|
9dd0797f49 | ||
|
|
ea6c78773e | ||
|
|
b7c64443db | ||
|
|
88137d5898 | ||
|
|
6bd46a4433 | ||
|
|
f00263b782 | ||
|
|
13bc4c5b9b | ||
|
|
e8c1798a13 | ||
|
|
3203950ca9 | ||
|
|
4c68086798 | ||
|
|
bb87917c97 | ||
|
|
74a03fca59 | ||
|
|
eb8f1e2526 | ||
|
|
3a547fb530 | ||
|
|
d23f72d232 | ||
|
|
c4fa76f217 | ||
|
|
d8a31fc249 | ||
|
|
7f0712183d | ||
|
|
f7bdfb4d6b | ||
|
|
eda5623b2e | ||
|
|
3df0f3ffe4 | ||
|
|
269897bef7 | ||
|
|
4837ea56cb | ||
|
|
e9b3d8e7ae | ||
|
|
28e88b1363 | ||
|
|
784b8b9b18 | ||
|
|
f09c313c5b | ||
|
|
d25c3c1d49 | ||
|
|
0f428acd07 | ||
|
|
e8cdd8a928 | ||
|
|
0b9fa7d87e | ||
|
|
c89a9152b5 | ||
|
|
b70254feed | ||
|
|
513a122290 | ||
|
|
6258082d70 | ||
|
|
76e431330c | ||
|
|
685bd72274 | ||
|
|
d020dc81db | ||
|
|
f0831cbe3c | ||
|
|
2a0be55a8d | ||
|
|
ccb86ea039 | ||
|
|
b33183f60f | ||
|
|
7a99f83396 | ||
|
|
16c8063900 | ||
|
|
50fd8c9cc4 | ||
|
|
0a1367744f | ||
|
|
4e8e4f7d14 | ||
|
|
44abc64533 | ||
|
|
97e27661d7 | ||
|
|
0e4e3383e3 | ||
|
|
fd6d318f0a | ||
|
|
69e2fb810f | ||
|
|
4572bd955e | ||
|
|
9ebae5fd5a | ||
|
|
22807ee393 | ||
|
|
845689fde1 | ||
|
|
0b25350ebc | ||
|
|
c0ae10bef6 | ||
|
|
5b4de64709 | ||
|
|
d51d65ef30 | ||
|
|
93299658fb | ||
|
|
df1892801f | ||
|
|
1caaebe03f | ||
|
|
c3400bd237 | ||
|
|
18c6ff5a99 | ||
|
|
83901b1896 | ||
|
|
dfa11f0f3e | ||
|
|
adb88fd8cf | ||
|
|
389e9c7e62 | ||
|
|
79b1c071ad | ||
|
|
bed239c90a | ||
|
|
ca27c2cf10 | ||
|
|
9789b3d999 | ||
|
|
a9e865eb54 | ||
|
|
6d458125a1 | ||
|
|
7f11214609 | ||
|
|
739af51904 | ||
|
|
484c4aea59 | ||
|
|
ac23f00d1f | ||
|
|
2d5914b358 | ||
|
|
c718e9d1c3 | ||
|
|
76731b673b | ||
|
|
c2bf9bf551 | ||
|
|
9854fd36cf | ||
|
|
e6bedd1ffe | ||
|
|
799e763050 | ||
|
|
fd59ace4f8 | ||
|
|
15d99be9f0 | ||
|
|
cbdbe83bbd | ||
|
|
7a8aeae673 | ||
|
|
b135f48867 | ||
|
|
0f1aea8df8 | ||
|
|
ec12a187fc | ||
|
|
358fe9733f | ||
|
|
21ee446509 | ||
|
|
d0c104aceb | ||
|
|
53291f6887 | ||
|
|
a3ba4b4169 | ||
|
|
7ff126a56e | ||
|
|
4e567d72a9 | ||
|
|
78af774413 | ||
|
|
800816055e | ||
|
|
61fab42281 | ||
|
|
780279d261 | ||
|
|
105858b0c7 | ||
|
|
6a39bbd0c3 | ||
|
|
eec60a760b | ||
|
|
9f89b03aa3 | ||
|
|
86ac019572 | ||
|
|
4f43cf3a9f | ||
|
|
e71e723f89 | ||
|
|
8e33698e23 | ||
|
|
2addf845d3 | ||
|
|
f9372f3638 | ||
|
|
21305853ce | ||
|
|
504d87831d | ||
|
|
b55b21921a | ||
|
|
e9b06472c1 | ||
|
|
aa608b4c29 | ||
|
|
4e262dfa14 | ||
|
|
538c68fc8b | ||
|
|
28c8bf61da | ||
|
|
179e9428c5 | ||
|
|
f35bceb309 | ||
|
|
7890753d9f | ||
|
|
de8c0fc871 | ||
|
|
e33962fdd4 | ||
|
|
734f295822 | ||
|
|
4c42b8d072 | ||
|
|
1dd89bac4b | ||
|
|
f086f75c07 | ||
|
|
47999e24c4 | ||
|
|
12e035b6eb | ||
|
|
9d7dac3425 | ||
|
|
a0b5275cc9 | ||
|
|
97522947ec | ||
|
|
8126a73663 | ||
|
|
6a6422c16e | ||
|
|
8b510d9b03 | ||
|
|
838b25d288 | ||
|
|
2836600857 | ||
|
|
562f971c3d | ||
|
|
25f9800f77 | ||
|
|
0ed367d734 | ||
|
|
070e03d741 | ||
|
|
7f1c327f02 | ||
|
|
c631bff0c9 | ||
|
|
0c311aeef4 | ||
|
|
b1f122beec | ||
|
|
c3f1b290f8 | ||
|
|
86764657cf | ||
|
|
4df93481ec | ||
|
|
4e2bbde829 | ||
|
|
fdfab66951 | ||
|
|
81b0c0a581 | ||
|
|
00c6072274 | ||
|
|
9c09ca2ed5 | ||
|
|
2447ccab62 | ||
|
|
d6fafef902 | ||
|
|
46a8723566 | ||
|
|
233be2e889 | ||
|
|
83eddf5e7d | ||
|
|
b1d739e032 | ||
|
|
e76e83d8c1 | ||
|
|
73d3eae8ae | ||
|
|
e92da4c82c | ||
|
|
776e0d6c90 | ||
|
|
8ca953f55c | ||
|
|
db3f69e0dd | ||
|
|
183f4a75e5 | ||
|
|
628c7e2e4d | ||
|
|
81176a6d31 | ||
|
|
245053434f | ||
|
|
dfb8da6e3e | ||
|
|
b040640813 | ||
|
|
a1cf02231a | ||
|
|
8a7b348899 | ||
|
|
f1523ef5f8 | ||
|
|
5204fe3e08 | ||
|
|
5522e150b7 | ||
|
|
86e0ef0d5e | ||
|
|
42f61ceafa | ||
|
|
2f95b0f426 | ||
|
|
c684b063b2 | ||
|
|
8f8d780c72 | ||
|
|
91f264bdaf | ||
|
|
1fdfb5299e | ||
|
|
0d1431395e | ||
|
|
7f740ccb5a | ||
|
|
f94a27c8e4 | ||
|
|
cb8d5ecb35 | ||
|
|
a921b4269e | ||
|
|
87444f5bcb | ||
|
|
2ceafb0ff5 | ||
|
|
912840bbcd | ||
|
|
d52554231a | ||
|
|
c4796ee321 | ||
|
|
13a85fe9e0 | ||
|
|
e4ecc1febe | ||
|
|
646e97ad55 | ||
|
|
05e2389dc1 | ||
|
|
8382b90682 | ||
|
|
c61cfa325f | ||
|
|
78e10cf7f8 | ||
|
|
85d12da18d | ||
|
|
4430d564fe | ||
|
|
8a3ff7a54a | ||
|
|
d224536552 | ||
|
|
07cb64a191 | ||
|
|
1ce8af18ec | ||
|
|
fddc67db93 | ||
|
|
df43aca222 | ||
|
|
fb9206aa8f | ||
|
|
e20c12619b | ||
|
|
211c7e70e1 | ||
|
|
d60b852b27 | ||
|
|
dacd9f7565 | ||
|
|
d76abe019f | ||
|
|
b6cd19d6ef | ||
|
|
74630f933a | ||
|
|
9133b59dbf | ||
|
|
10da7b714f | ||
|
|
908501cbc8 | ||
|
|
5d35cc0d10 | ||
|
|
f2b48d0f1a | ||
|
|
88ee83c7d8 | ||
|
|
d3ec2dbae2 | ||
|
|
78edcab86e | ||
|
|
627db24c63 | ||
|
|
7c56a8fa74 | ||
|
|
0527904c48 | ||
|
|
3642003dd2 | ||
|
|
2c47064d79 | ||
|
|
39a532cf87 | ||
|
|
ebaac290e7 | ||
|
|
5379e4b4bd | ||
|
|
6b03c4600d | ||
|
|
7ed54a166b | ||
|
|
2ab63d75fc | ||
|
|
1c248d1de8 | ||
|
|
261fbbc867 | ||
|
|
346015e528 | ||
|
|
8b8d538a9c | ||
|
|
5b260a5ba6 | ||
|
|
03892a517e | ||
|
|
30155c4a8c | ||
|
|
bfef2eb98e | ||
|
|
7ccb455174 | ||
|
|
80df137437 | ||
|
|
a605cd3048 | ||
|
|
c7f8689bfe | ||
|
|
12a7f957c3 | ||
|
|
c6fee3c1f4 | ||
|
|
81854d1daf | ||
|
|
4836f52a5d | ||
|
|
5c05afae42 | ||
|
|
77052e15b0 | ||
|
|
ecc0fbdae9 | ||
|
|
00f4bd594f | ||
|
|
3529acfeec | ||
|
|
1510f66121 | ||
|
|
c22dcc18dc | ||
|
|
b6f9769488 | ||
|
|
188dc4c782 | ||
|
|
0126aa794f | ||
|
|
2bc7efd20e | ||
|
|
566df69ca5 | ||
|
|
40f21b10cd | ||
|
|
a7801db6e7 | ||
|
|
06bbca7ae3 | ||
|
|
331be63c9e | ||
|
|
d3df568aec | ||
|
|
9e909e8532 | ||
|
|
1b2fa4924b | ||
|
|
20673b9edd | ||
|
|
3b4bfba85e | ||
|
|
42bdb42573 | ||
|
|
c9a958f861 | ||
|
|
9a316fe84a | ||
|
|
92423911a9 | ||
|
|
6770a965a6 | ||
|
|
33cb18517a | ||
|
|
9ea91f4f5d | ||
|
|
d9d3739118 | ||
|
|
0b885ec5ec | ||
|
|
b16110bcd0 | ||
|
|
936d766cae | ||
|
|
108d0578a2 | ||
|
|
39343f984a | ||
|
|
628c0193f3 | ||
|
|
def6b365fa | ||
|
|
0ab9ffdc93 | ||
|
|
1b3efb1a78 | ||
|
|
d6156dee68 | ||
|
|
541f5e54dc | ||
|
|
793ab6b24b | ||
|
|
082134b9a0 | ||
|
|
2db727e40f | ||
|
|
fc5420db27 | ||
|
|
aeb24dabdb | ||
|
|
3d0d1e1dcb | ||
|
|
5f7cff9af8 | ||
|
|
d7c367f095 | ||
|
|
aa9641024a | ||
|
|
60d6c748ef | ||
|
|
dc4da6087f | ||
|
|
8a3b885eca | ||
|
|
ce7f659a32 | ||
|
|
e4e58f6d97 | ||
|
|
a18987aa59 | ||
|
|
5db74b724e | ||
|
|
aba3e374c3 | ||
|
|
dcf1cdf526 | ||
|
|
68b9a073af | ||
|
|
f1ba8e3d9b | ||
|
|
e7193dbb5f | ||
|
|
e15ef345bc | ||
|
|
564e33bc18 | ||
|
|
daa7b5edd4 | ||
|
|
a012c4b772 | ||
|
|
58f7aa0a57 | ||
|
|
81f2393b46 | ||
|
|
5d783a743a | ||
|
|
c335b62d26 | ||
|
|
e7ca2d6adc | ||
|
|
ceae5bb88b | ||
|
|
36aec50bce | ||
|
|
b8cf0d7fd2 | ||
|
|
dca7bd51cd | ||
|
|
6b9a3c656d | ||
|
|
829b3a4ee8 | ||
|
|
f5ccddb52b | ||
|
|
94e1dcf2cb | ||
|
|
7465de389f | ||
|
|
c83d91eea7 | ||
|
|
dbe28751df | ||
|
|
d392a895d9 | ||
|
|
1026d59cad | ||
|
|
1ada457364 | ||
|
|
12246029ef | ||
|
|
c977948c2c | ||
|
|
9994e1eb84 | ||
|
|
1755d0f970 | ||
|
|
f5010e960b | ||
|
|
9bf4ade35b | ||
|
|
ce7495ecce | ||
|
|
41ddbb16a8 | ||
|
|
410db750c6 | ||
|
|
b91df6642d | ||
|
|
420ba065da | ||
|
|
ca69a10838 | ||
|
|
9c76dbef7a | ||
|
|
96e69240ca | ||
|
|
6c27885702 | ||
|
|
5a2e2b1f3f | ||
|
|
316c6b5fa1 | ||
|
|
b2f8413057 | ||
|
|
17a436bc27 | ||
|
|
93a29e0e34 | ||
|
|
d46f04de0b | ||
|
|
55941b106b | ||
|
|
ebaf355878 | ||
|
|
21d290beb7 | ||
|
|
a9f1a98fa2 | ||
|
|
5fe9f1a217 | ||
|
|
9da74f7bc6 | ||
|
|
e4d61de406 | ||
|
|
93fcd1ae86 | ||
|
|
43fcca5ffa | ||
|
|
9c31a360ee | ||
|
|
bb00825cd2 | ||
|
|
db0eb8f22b | ||
|
|
c40c202220 | ||
|
|
eaf35ded0c | ||
|
|
ecbf663b18 | ||
|
|
23dd001a9b | ||
|
|
48607f8ab3 | ||
|
|
c2871d94ed | ||
|
|
7744b1fd8a | ||
|
|
5756e27711 | ||
|
|
fbb1fcf500 | ||
|
|
5f9b0e9b86 | ||
|
|
9fe6ef82a5 | ||
|
|
fd07b077b9 | ||
|
|
158f92f17f | ||
|
|
e73f9b7bf5 | ||
|
|
2ba85533c2 | ||
|
|
490e66fe07 | ||
|
|
4a61bf21de | ||
|
|
b3187710d0 | ||
|
|
e472fb6c1e | ||
|
|
1af7f7d550 | ||
|
|
400cefebc8 | ||
|
|
d3c251bc52 | ||
|
|
0274a641b2 | ||
|
|
0917536ccc | ||
|
|
724c29c4a7 | ||
|
|
8e6bb34d1b | ||
|
|
c02964e95c | ||
|
|
cb8e5af8f7 | ||
|
|
06bea715a3 | ||
|
|
3d01b0b9da | ||
|
|
f339aa7454 | ||
|
|
e69ac489c7 | ||
|
|
52f08eda08 | ||
|
|
a746019790 | ||
|
|
efdcc263dd | ||
|
|
4ee32ebaf3 | ||
|
|
acd3b3c064 | ||
|
|
c53b95aa93 | ||
|
|
40d4daa96b | ||
|
|
68b793f059 | ||
|
|
f705f1145a | ||
|
|
5321a8a558 | ||
|
|
46e1d7b66b | ||
|
|
497423ddc2 | ||
|
|
80707d1734 | ||
|
|
275bcde081 | ||
|
|
24eaff6951 | ||
|
|
5e87d8793d | ||
|
|
0791c658ad | ||
|
|
37615d4790 | ||
|
|
b9487276e9 | ||
|
|
46dea00b2f | ||
|
|
85be5cbfc1 | ||
|
|
2b79a129aa | ||
|
|
d42fd3b095 | ||
|
|
25b6f6fb34 | ||
|
|
9478678ea0 | ||
|
|
2c078cbc7c | ||
|
|
3627331527 | ||
|
|
f4ebb93546 | ||
|
|
64e794f1b5 | ||
|
|
5bba0fc2fa | ||
|
|
a4273d2d0a | ||
|
|
0c765f7b71 | ||
|
|
4e0e223599 | ||
|
|
7eba8e58e3 | ||
|
|
43a8d25619 | ||
|
|
24e6fded91 | ||
|
|
dee9055347 | ||
|
|
0ce53bd98f | ||
|
|
14991ac3b9 | ||
|
|
57836047f6 | ||
|
|
9873084667 | ||
|
|
e8f6862fd2 | ||
|
|
4d69a1f1c6 | ||
|
|
f203567381 | ||
|
|
0d601073a6 | ||
|
|
daf3b202c3 | ||
|
|
087240aa67 | ||
|
|
210cae2736 | ||
|
|
dae0f05378 | ||
|
|
4d1a2668f5 | ||
|
|
7d3bba75e1 | ||
|
|
b111e3d6c7 | ||
|
|
6cc11276c8 | ||
|
|
5db596f0a5 | ||
|
|
aa3ffdbaaf | ||
|
|
8724d5e9ed | ||
|
|
da9401dd1a | ||
|
|
85b1b44e20 | ||
|
|
c36f989c52 | ||
|
|
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 | ||
|
|
290be28dae | ||
|
|
f488e985ab | ||
|
|
8678e25427 | ||
|
|
d41c1c4c00 | ||
|
|
6a13260e67 | ||
|
|
6403eaa0db | ||
|
|
4edad1b7a4 | ||
|
|
21a7a4e530 | ||
|
|
d9af161a18 | ||
|
|
83381446a0 | ||
|
|
093b8c14d6 | ||
|
|
116c1e9f29 | ||
|
|
706d86dd21 | ||
|
|
df81854f89 | ||
|
|
b0469da462 | ||
|
|
2e9c6de5d0 | ||
|
|
f96fb997da | ||
|
|
b0f781ec16 | ||
|
|
93fd850b63 | ||
|
|
a2327a093b | ||
|
|
4415a3c858 | ||
|
|
6ba54d9cb1 | ||
|
|
8d3e185894 | ||
|
|
01a48e530f | ||
|
|
675fe750f6 | ||
|
|
8ead49504b | ||
|
|
47c7cea5a5 | ||
|
|
f6fa093369 | ||
|
|
6738aa8c68 | ||
|
|
48266e0bd6 | ||
|
|
1975b875a5 | ||
|
|
0a7b580799 | ||
|
|
d18fc889d5 | ||
|
|
a5e8c290ef | ||
|
|
8b5ed3c9da | ||
|
|
de34fee72a | ||
|
|
346fce177f | ||
|
|
7ca910ec46 | ||
|
|
5081810a96 | ||
|
|
ac1d798a36 | ||
|
|
2d2f8bfbcd | ||
|
|
7414781b3a | ||
|
|
ea62bc9ed1 | ||
|
|
2cfc5b9501 | ||
|
|
222dda50bc | ||
|
|
b021d10de5 | ||
|
|
6763ea6197 | ||
|
|
697be6a822 | ||
|
|
a1de70ff89 | ||
|
|
6254586a65 | ||
|
|
3d827d7513 | ||
|
|
4b2f3a6f5f | ||
|
|
2ba41701e1 | ||
|
|
07c307f4ea | ||
|
|
daa93b0a2f | ||
|
|
5836d60d88 | ||
|
|
92d1715d88 | ||
|
|
7abc86847e | ||
|
|
a6913a982a | ||
|
|
8d1239c316 | ||
|
|
de1575f757 | ||
|
|
6c8ef93f9f | ||
|
|
a260356d78 | ||
|
|
27a17ed5a6 | ||
|
|
870cabfa05 | ||
|
|
7cd51fe1eb | ||
|
|
ac38899d1f | ||
|
|
faa415a823 | ||
|
|
30c236f1a9 | ||
|
|
b83211e98d | ||
|
|
6dfab37ef8 | ||
|
|
a0e23eb22a | ||
|
|
0fada7ffc2 | ||
|
|
453745c1b6 | ||
|
|
3b63205e70 | ||
|
|
ffdcfd527a | ||
|
|
472c7c4b23 | ||
|
|
c415f9ee15 | ||
|
|
e51dbb45c1 | ||
|
|
e5f3aeca78 | ||
|
|
59d27e6829 | ||
|
|
6464bbfc3c | ||
|
|
ba78a82a26 | ||
|
|
c6d629659b | ||
|
|
5ff87aa24e | ||
|
|
8bd6e45303 | ||
|
|
73cbcb7b7e | ||
|
|
624be50026 | ||
|
|
f14b1f3ff0 | ||
|
|
0c7fa454e9 | ||
|
|
aac11a9fb8 | ||
|
|
0d515e4938 | ||
|
|
b63d192df7 | ||
|
|
d582d76346 | ||
|
|
9394bf592c | ||
|
|
4919548ef5 | ||
|
|
374d984ced | ||
|
|
413062f8e8 | ||
|
|
7554a599b4 | ||
|
|
dfb1e19948 | ||
|
|
f2fb8d33d4 | ||
|
|
2d77400a65 | ||
|
|
8a6503da8a | ||
|
|
ab35346f24 | ||
|
|
28844cb41d | ||
|
|
8fcccfd46e | ||
|
|
f220e1b2ee | ||
|
|
346c3ad2a0 | ||
|
|
7a013a42f7 | ||
|
|
264e708c1d | ||
|
|
620fb356cc | ||
|
|
43d8e181be | ||
|
|
ac648cefcf | ||
|
|
7e3f236393 | ||
|
|
b8fc6f5130 | ||
|
|
a578199dab | ||
|
|
8440a10b9e | ||
|
|
756492f349 | ||
|
|
6905515f3d | ||
|
|
3d1faebf15 | ||
|
|
d1c0cdf65b | ||
|
|
36fb1da46d | ||
|
|
8b08b03fbf | ||
|
|
733cf0afac | ||
|
|
57fe71c800 | ||
|
|
ec86c7bfda | ||
|
|
ad8680be38 | ||
|
|
805821c928 | ||
|
|
e38f63254f | ||
|
|
97cb072981 | ||
|
|
4285ea7348 | ||
|
|
36c82d0c7f | ||
|
|
2a967303cb | ||
|
|
ae49dfe8f2 | ||
|
|
7078d5c980 | ||
|
|
059f5d6a73 | ||
|
|
c523f35c5e | ||
|
|
c122bd68e0 | ||
|
|
59277f8b7a | ||
|
|
8eaef1e559 | ||
|
|
5904c2daf5 | ||
|
|
33b965644b | ||
|
|
34008569dd | ||
|
|
371c15aa33 | ||
|
|
b034485ce8 | ||
|
|
76ea4d25a4 | ||
|
|
fdec6277eb | ||
|
|
2a34986acb | ||
|
|
d59d1e5f7f | ||
|
|
28977bd579 | ||
|
|
f9b1e2922d | ||
|
|
960334d087 | ||
|
|
005caba234 | ||
|
|
2c5bb4710e | ||
|
|
bcb7e17105 | ||
|
|
304e861a28 | ||
|
|
16269c1a49 | ||
|
|
9613bb01de | ||
|
|
5b87c43535 | ||
|
|
d021eddb16 | ||
|
|
1aa12e4ff1 | ||
|
|
55919fc7d3 | ||
|
|
f338bccc3b | ||
|
|
5a6f1ae062 | ||
|
|
8b02797ede | ||
|
|
2848b4e9c1 | ||
|
|
88bbd66a3b | ||
|
|
a17e1d4056 | ||
|
|
279d53afde | ||
|
|
56bd9a61ea | ||
|
|
76493215c5 | ||
|
|
a3c0f06c5f | ||
|
|
f9f70ce989 | ||
|
|
8840434c7c | ||
|
|
6fb4cdca62 | ||
|
|
4a57dba586 | ||
|
|
291f2b0e91 | ||
|
|
43b057c40c | ||
|
|
5b6d4371c8 | ||
|
|
e9cd86f468 | ||
|
|
7cae2f4aac | ||
|
|
a7147a44ca | ||
|
|
d04a419a80 | ||
|
|
e78a2e3e41 | ||
|
|
2c332a968f | ||
|
|
b3f02a73a4 | ||
|
|
1d520310ac | ||
|
|
7cd22804dd | ||
|
|
de1a79a7ca | ||
|
|
82fbee2bc0 | ||
|
|
7441da4b57 | ||
|
|
6dc43f7e12 | ||
|
|
0775f3d0c6 | ||
|
|
e1addb16fd | ||
|
|
62e5f85473 | ||
|
|
b92000dd46 | ||
|
|
a4638f6c21 | ||
|
|
0abfc76871 | ||
|
|
470cc13b0e | ||
|
|
6b45c0c1d8 | ||
|
|
f114985dc6 | ||
|
|
52907155d2 | ||
|
|
5853f3f447 | ||
|
|
98b3c990e0 | ||
|
|
e5cb27f5b7 | ||
|
|
de462b1d0f | ||
|
|
7a94fb3a6b | ||
|
|
e2850ee77e | ||
|
|
9c76875896 | ||
|
|
d19737f4c5 | ||
|
|
d235139e6b | ||
|
|
4f97ebb28d | ||
|
|
f082d4dd44 | ||
|
|
89fa9ba47e |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# Editorconfig file for moonraker repo, courtesy of @trevjonez
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
charset = utf-8
|
||||
|
||||
[*.py]
|
||||
max_line_length = 80
|
||||
@@ -0,0 +1,3 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
ko_fi: arksine
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Announcement
|
||||
about: Create a Moonraker Announcement. For dev use only.
|
||||
title: ''
|
||||
labels: announcement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
name: Bug report
|
||||
description: Create a report to help us improve
|
||||
labels: ["bug", "triage"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
This issue form is for reporting bugs only!
|
||||
If you have a feature request, please use [Feature Request](/new?template=feature_request.yml)
|
||||
- type: textarea
|
||||
id: what-happened
|
||||
attributes:
|
||||
label: What happened
|
||||
description: >-
|
||||
A clear and concise description of what the bug is.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: client
|
||||
attributes:
|
||||
label: Client
|
||||
multiple: true
|
||||
description: On what clients are you seeing the problem?
|
||||
options:
|
||||
- Mainsail
|
||||
- Fluidd
|
||||
- MoonCord
|
||||
- KlipperScreen
|
||||
- MobileRaker
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: browser
|
||||
attributes:
|
||||
label: Browser
|
||||
multiple: true
|
||||
description: On what browsers are you seeing the problem?
|
||||
options:
|
||||
- Chrome
|
||||
- Firefox
|
||||
- Safari
|
||||
- Microsoft Edge
|
||||
- Brave
|
||||
- Other or N/A
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: repro-steps
|
||||
attributes:
|
||||
label: How to reproduce
|
||||
description: >-
|
||||
Minimal and precise steps to reproduce this bug.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: additional-info
|
||||
attributes:
|
||||
label: Additional information
|
||||
description: |
|
||||
Please attach moonraker.log using the field below. If you are using
|
||||
a Browser or Client not provided in the options above please specify
|
||||
them here.
|
||||
|
||||
You may also include any additional information, screenshots, or files
|
||||
that helpful in describing the issue.
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Klipper Discord
|
||||
url: https://discord.klipper3d.org/
|
||||
about: Quickest way to get in contact
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Feature request
|
||||
description: Suggest an idea for this project
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
This issue form is for feature requests only!
|
||||
If you've found a bug, please use [bug_report](/new?template=bug_report.yml)
|
||||
- type: textarea
|
||||
id: problem-description
|
||||
attributes:
|
||||
label: Is your feature request related to a problem? Please describe
|
||||
description: >-
|
||||
A clear and concise description of what the problem is.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: solution-description
|
||||
attributes:
|
||||
label: Describe the solution you'd like
|
||||
description: >-
|
||||
A clear and concise description of what you want to happen.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: possible-alternatives
|
||||
attributes:
|
||||
label: Describe alternatives you've considered
|
||||
description: >-
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
- type: textarea
|
||||
id: additional-info
|
||||
attributes:
|
||||
label: Additional information
|
||||
description: |
|
||||
If you have any additional information for us, use the field below.
|
||||
|
||||
Please note, you can attach screenshots or screen recordings here, by
|
||||
dragging and dropping files in the field below.
|
||||
@@ -0,0 +1,7 @@
|
||||
<!---
|
||||
Thank you for contributing to Moonraker. Before creating your pull request please
|
||||
review the [contributing documentation](https://moonraker.readthedocs.io/en/latest/contributing/).
|
||||
Be sure that each commit message is formatted as described, with a signature containing
|
||||
your real name and a reachable email address. Your signature acknowledges that you accept the
|
||||
[developer certificate of origin](https://github.com/Arksine/moonraker/blob/master/docs/developer-certificate-of-origin).
|
||||
--->
|
||||
@@ -0,0 +1,51 @@
|
||||
# CI Code for generating and publishing beta assets
|
||||
|
||||
name: publish_assets
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
jobs:
|
||||
generate_assets:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Moonraker
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.ref }}
|
||||
path: moonraker
|
||||
|
||||
- name: Checkout Klipper
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
repository: Klipper3d/klipper
|
||||
path: klipper
|
||||
|
||||
- name: Build Beta Assets
|
||||
if: ${{ github.event.release.prerelease }}
|
||||
run: >
|
||||
./moonraker/scripts/build-zip-release.sh -b
|
||||
-o ${{ github.workspace }}
|
||||
-k ${{ github.workspace }}/klipper
|
||||
|
||||
- name: Build Stable Assets
|
||||
if: ${{ !github.event.release.prerelease }}
|
||||
run: >
|
||||
./moonraker/scripts/build-zip-release.sh
|
||||
-o ${{ github.workspace }}
|
||||
-k ${{ github.workspace }}/klipper
|
||||
|
||||
- name: Upload assets
|
||||
run: |
|
||||
cd moonraker
|
||||
gh release upload ${{ env.TAG }} ${{ env.FILES }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
FILES: >
|
||||
${{ github.workspace }}/moonraker.zip
|
||||
${{ github.workspace }}/klipper.zip
|
||||
${{ github.workspace }}/RELEASE_INFO
|
||||
${{ github.workspace }}/COMMIT_LOG
|
||||
TAG: ${{ github.event.release.tag_name }}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# CI for code style and application tests
|
||||
|
||||
name: test-code
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
lint-python-code:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: ricardochaves/python-lint@v1.4.0
|
||||
with:
|
||||
python-root-list: "moonraker scripts"
|
||||
use-pylint: false
|
||||
use-pycodestyle: true
|
||||
use-flake8: false
|
||||
use-black: false
|
||||
use-mypy: true
|
||||
use-isort: false
|
||||
extra-pycodestyle-options: "--ignore=E226,E301,E302,E303,W503,W504 --max-line-length=88 --max-doc-length=88"
|
||||
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.devel
|
||||
|
||||
.venv
|
||||
venv
|
||||
start_moonraker
|
||||
*.env
|
||||
.pdm.toml
|
||||
build
|
||||
dist
|
||||
@@ -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,9 +1,44 @@
|
||||
[](https://pdm.fming.dev)
|
||||
|
||||
# Moonraker - API Web Server for Klipper
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use interact with Klipper. Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket.
|
||||
client applications may use to interact with the 3D printing firmware
|
||||
[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.
|
||||
|
||||
Moonraker depends on Tornado for its server functionality. Moonraker
|
||||
does not come bundled with a client, you will need to install one,
|
||||
such as [Mainsail](https://github.com/meteyou/mainsail).
|
||||
Documentation for users and developers can be found on
|
||||
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
|
||||
|
||||
### Clients
|
||||
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following clients are currently available:
|
||||
|
||||
- [Mainsail](https://github.com/mainsail-crew/mainsail) by [Mainsail-Crew](https://github.com/mainsail-crew)
|
||||
- [Fluidd](https://github.com/fluidd-core/fluidd) by Cadriel
|
||||
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
|
||||
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
|
||||
|
||||
### Raspberry Pi Images
|
||||
|
||||
Moonraker is available pre-installed with the following Raspberry Pi images:
|
||||
|
||||
- [MainsailOS](https://github.com/mainsail-crew/MainsailOS) by [Mainsail-Crew](https://github.com/mainsail-crew)
|
||||
- Includes Klipper, Moonraker, and Mainsail
|
||||
- [FluiddPi](https://github.com/fluidd-core/FluiddPi) by Cadriel
|
||||
- Includes Klipper, Moonraker, and Fluidd
|
||||
|
||||
### Docker Containers
|
||||
|
||||
The following projects deploy Moonraker via Docker:
|
||||
|
||||
- [prind](https://github.com/mkuf/prind) by mkuf
|
||||
- A suite of containers which allow you to run Klipper in
|
||||
Docker. Includes support for OctoPrint and Moonraker.
|
||||
|
||||
### Changes
|
||||
|
||||
Please refer to the [changelog](https://moonraker.readthedocs.io/en/latest/changelog)
|
||||
for a list of notable changes to Moonraker.
|
||||
@@ -0,0 +1,402 @@
|
||||
##
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
|
||||
### February 20th 2023
|
||||
- The following new endpoints are available when at least one `[sensor]`
|
||||
section has been configured:
|
||||
- `GET /server/sensors/list`
|
||||
- `GET /server/sensors/sensor`
|
||||
- `GET /server/sensors/measurements`
|
||||
|
||||
See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
- A `sensors:sensor_update` notification has been added. When at least one
|
||||
monitored sensor is reporting a changed value Moonraker will broadcast this
|
||||
notification.
|
||||
|
||||
See [web_api.md](web_api.md) for details on this new notification.
|
||||
|
||||
### February 17 2023
|
||||
- Moonraker API Version 1.2.1
|
||||
- An error in the return value for some file manager endpoints has
|
||||
been corrected. Specifically, the returned result contains an `item` object
|
||||
with a `path` field that was prefixed with the root (ie: "gcodes").
|
||||
This is inconsistent with the websocket notification and has been corrected
|
||||
to remove the prefix. This affects the following endpoints:
|
||||
- `POST /server/files/directory` | `server.files.post_directory`
|
||||
- `DELETE /server/files/directory` | `server.files.delete_directory`
|
||||
- `POST /server/files/move` | `server.files.move`
|
||||
- `POST /server/files/copy` | `server.files.copy`
|
||||
|
||||
### March 4th 2022
|
||||
- Moonraker API Version 1.0.1
|
||||
- The `server.websocket.id` endpoint has been deprecated. It is
|
||||
recommended to use `server.connection.identify` method to identify
|
||||
your client. This method returns a `connection_id` which is
|
||||
the websocket's unique id. See
|
||||
[the documentation](web_api.md#identify-connection) for details.
|
||||
|
||||
### May 8th 2021
|
||||
- The `file_manager` has been refactored to support system file
|
||||
file events through `inotify`. Only mutable `roots` are monitored,
|
||||
(currently `gcodes` and `config`). Subfolders within these
|
||||
these roots are also monitored, however hidden folders are not.
|
||||
The following changes API changes have been made to acccommodate
|
||||
this functionality:
|
||||
- The `notify_filelist_changed` actions have changed. The new
|
||||
actions are as follows:
|
||||
- `create_file`: sent when a new file has been created. This
|
||||
includes file uploads and copied files.
|
||||
- `create_dir`: sent when a new directory has been created.
|
||||
- `delete_file`: sent when a file has been deleted.
|
||||
- `delete_dir`: sent when a directory has been deleted.
|
||||
- `move_file`: sent when a file has moved.
|
||||
- `move_dir`: sent when a directory has moved.
|
||||
- `modify_file`: sent when an existing file has been modified
|
||||
- `root_update`: sent when a root directory location has been set.
|
||||
For example, if a user changes the gcode path in Klipper, this
|
||||
action is sent with a `notify_filelist_changed` notification.
|
||||
- File list notifications for gcode files are now only sent after
|
||||
all metadata has been processed. Likewise, requests to copy,
|
||||
move, or upload a file will only return after metadata has been
|
||||
processed. Notifications are synced with requests so that the
|
||||
request should always return before the notification is sent.
|
||||
- Thumbnails are now stored in the `.thumbs` directory to prevent
|
||||
changes to thumbnails from emitting filelist notications. This
|
||||
change will be reflected in the metadata's `relative_path` field,
|
||||
so clients that use this field should not need to take additional
|
||||
action. Note that existing thumbnails will remain in the `thumbs`
|
||||
directory and filelist notifications will be sent for changes to
|
||||
these thumbnails.
|
||||
- The `notify_metadata_update` notification has been removed Clients
|
||||
- can reliably expect metadata to be available for new or moved gcode
|
||||
files when a request returns.
|
||||
- The return values for several endpoints have been updated. They
|
||||
now contain information similar to that which is pushed by the
|
||||
`notify_filelist_changed` notification.
|
||||
- The deprecated `data` field in gcode metadata has been removed.
|
||||
The `size` field now returns the size of the `.png` file.
|
||||
|
||||
|
||||
### 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:
|
||||
- `GET /machine/update/status`
|
||||
- `POST /machine/update/moonraker`
|
||||
- `POST /machine/update/klipper`
|
||||
- `POST /machine/update/client`
|
||||
- `POST /machine/update/system`
|
||||
- The following endpoint has been added and is available as part of the
|
||||
core API:
|
||||
- `POST /machine/services/restart`
|
||||
|
||||
See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
|
||||
### November 23rd 2020
|
||||
- Moonraker now serves Klipper's "docs" directory. This can be access
|
||||
at `GET /server/files/docs/<filename>`.
|
||||
|
||||
### November 19th 2020
|
||||
- The path for the power APIs has changed from `gpio_power` to `device_power`:
|
||||
- `GET /machine/device_power/devices`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.devices","id":"1"}`\
|
||||
Returns an array of objects listing all detected devices.
|
||||
Each object in the array is guaranteed to have the following
|
||||
fields:
|
||||
- `device`: The device name
|
||||
- `status`: May be "init", "on", "off", or "error"
|
||||
- `type`: May be "gpio" or "tplink_smartplug"
|
||||
- `GET /machine/device_power/status?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.status","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
It is no longer possible to call this method with no arguments.
|
||||
Status will only be returned for the requested device, to get
|
||||
status of all devices use `/machine/device_power/devices`. As
|
||||
before, this returns an object in the format of
|
||||
`{device_name: status}`, where device_name is the name of the device
|
||||
and `status` is the devices current status.
|
||||
- `POST /machine/device_power/on?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.on","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device on. Returns the current status of the device.
|
||||
- `POST /machine/device_power/off?dev_name`\
|
||||
`{"jsonrpc":"2.0","method":"machine.device_power.off","id":"1",
|
||||
"params":{"dev_name":null}}`\
|
||||
Toggles device off. Returns the current status of the device.
|
||||
- The `notify_power_changed` notification now includes an object
|
||||
containing device info, matching that which would be recieved
|
||||
from a single item in `/machine/power/devices`.
|
||||
|
||||
### November 12th 2020
|
||||
- Two new fields have been added to the gcode metadata:
|
||||
- `gcode_start_byte`: Indicates the byte position in the
|
||||
file where the first "Gxx" or "Mxx" command is detected.
|
||||
- `gcode_end_byte`: Indicates the byte position in the
|
||||
file where the last "Gxx" or "Mxx" command is detected.
|
||||
These fields may be used to more accurately predict print
|
||||
progress based on the file size.
|
||||
|
||||
### November 11th 2020
|
||||
- The `server.websocket.id` API has been added. This returns a
|
||||
unique ID that Moonraker uses to track each client connection.
|
||||
As such, this API is only available over the websocket, there
|
||||
is no complementary HTTP request.
|
||||
- All HTTP API request may now include arguments in either the
|
||||
query string or in the request's body.
|
||||
- Subscriptions are now managed on a per connection basis. Each
|
||||
connection will only recieve updates for objects in which they
|
||||
are currently subscribed. If an "empty" request is sent, the
|
||||
subscription will be cancelled.
|
||||
- The `POST /printer/object/subscribe` now requires a
|
||||
`connection_id` argument. This is used to identify which
|
||||
connection's associated subscription should be updated.
|
||||
Currenlty subscriptions are only supported over the a
|
||||
websocket connection, one may use the id received from
|
||||
`server.websocket.id`.
|
||||
- The `notify_klippy_ready` websocket notification has been
|
||||
added.
|
||||
|
||||
### November 2nd 2020
|
||||
- The `GET /server/files/directory` endpoint now accepts a new
|
||||
optional argument, `extended`. If `extended=true`, then
|
||||
the data returned for gcode files will also include extracted
|
||||
metadata if it exists.
|
||||
|
||||
### October 25th 2020
|
||||
- The `modified` field reported for files and directories is no
|
||||
longer represented as a string. It is now a floating point
|
||||
value representing unix time (in seconds). This can be used
|
||||
to display the "last modified date" based on the client's
|
||||
timezone.
|
||||
|
||||
### October 21st 2020
|
||||
- The `/server/gcode_store` endpoint no longer returns a string
|
||||
in the result's `gcode_store` field. It now returns an
|
||||
Array of objects, each object containing `message` and `time`
|
||||
fields. The time refers to a timestamp in unix time (seconds),
|
||||
and may be used to determine when the gcode store received the
|
||||
accompanying `message`.
|
||||
|
||||
### September 30th 2020
|
||||
- Two new endpoints have been added:
|
||||
- `GET /server/info` (`server.info`)
|
||||
- `GET /server/gcode_store` (`server.gcode_store`)
|
||||
See web_api.md for details on their usage.
|
||||
|
||||
### September 7th 2020
|
||||
- A new websocket API has been added, `server.files.delete_file`:
|
||||
```
|
||||
{jsonrpc: "2.0", method: "server.files.delete_file", params:
|
||||
{path: "<root>/<file_name>"}, id: <request id>}
|
||||
```
|
||||
Where <root> is either "gcodes" or "config", and <file_name> is
|
||||
the relative path to the file for deletion. For example:
|
||||
`path: "gcodes/my_sub_dir/my_gcode_file.gcode"`
|
||||
|
||||
|
||||
### September 3rd 2020
|
||||
- The Websocket APIs have changed for clarity. The APIs methods now
|
||||
use namespaces similar to those found in common programming languages.
|
||||
This change affects all websocket APIs, however websocket events have
|
||||
not changed. Below is a chart mapping the Previous API to the New API:
|
||||
| Previous Websocket Method | New Websocket Method |
|
||||
|---------------------------|----------------------|
|
||||
| get_printer_info | printer.info |
|
||||
| post_printer_emergency_stop | printer.emergency_stop |
|
||||
| post_printer_restart | printer.restart |
|
||||
| post_printer_firmware_restart | printer.firmware_restart |
|
||||
| get_printer_objects_list | printer.objects.list |
|
||||
| get_printer_objects_query | printer.objects.query |
|
||||
| post_printer_objects_subscribe | printer.objects.subscribe |
|
||||
| get_printer_query_endstops_status | printer.query_endstops.status |
|
||||
| post_printer_gcode_script | printer.gcode.script |
|
||||
| get_printer_gcode_help | printer.gcode.help |
|
||||
| post_printer_print_start | printer.print.start |
|
||||
| post_printer_print_pause | printer.print.pause |
|
||||
| post_printer_print_resume | printer.print.resume |
|
||||
| post_printer_print_cancel | printer.print.cancel |
|
||||
| post_machine_reboot | machine.reboot |
|
||||
| post_machine_shutdown | machine.shutdown |
|
||||
| get_server_temperature_store | server.temperature_store |
|
||||
| get_file_list | server.files.list |
|
||||
| get_file_metadata | server.files.metadata |
|
||||
| get_directory | server.files.get_directory |
|
||||
| post_directory | server.files.post_directory |
|
||||
| delete_directory | server.files.delete_directory |
|
||||
| post_file_move | server.files.move |
|
||||
| post_file_copy | server.files.copy |
|
||||
- The "power" plugin APIs have changed. This affects both HTTP and
|
||||
Websocket APIs. They were originally added to the "/printer" path,
|
||||
however this adds the possibility of a naming conflict. The new
|
||||
APIs are as follows:
|
||||
- `GET /machine/gpio_power/devices` : `machine.gpio_power.devices`
|
||||
- `GET /machine/gpio_power/status` : `machine.gpio_power.status`
|
||||
- `POST /machine/gpio_power/on` : `machine.gpio_power.on`
|
||||
- `POST /machine/gpio_power/off` : `machine.gpio_power.off`
|
||||
|
||||
### September 1st 2020
|
||||
- A new notification has been added: `notify_metdata_update`. This
|
||||
notification is sent when Moonraker parses metdata from a new upload.
|
||||
Note that the upload must be made via the API, files manually (using
|
||||
SAMBA, SCP, etc) do not trigger a notification. The notification is
|
||||
sent in the following format:
|
||||
```
|
||||
{jsonrpc: "2.0", method: "notify_metadata_update", params: [metadata]}
|
||||
```
|
||||
Where `metadata` is an object in the following format:
|
||||
|
||||
```json
|
||||
{
|
||||
filename: "file name",
|
||||
size: <file size>,
|
||||
modified: "last modified date",
|
||||
slicer: "Slicer Name",
|
||||
first_layer_height: <in mm>,
|
||||
layer_height: <in mm>,
|
||||
object_height: <in mm>,
|
||||
estimated_time: <time in seconds>,
|
||||
filament_total: <in mm>,
|
||||
thumbnails: [
|
||||
{
|
||||
width: <in pixels>,
|
||||
height: <in pixels>,
|
||||
size: <length of string>,
|
||||
data: <base64 string>
|
||||
}, ...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### August 16th 2020
|
||||
- The structure of data returned from `/printer/info` (`get_printer_info`)
|
||||
has changed to the following format:
|
||||
```json
|
||||
{
|
||||
state: "<klippy state>",
|
||||
state_message: "<current state message>",
|
||||
hostname: "<hostname>",
|
||||
software_version: "<version>",
|
||||
cpu_info: "<cpu_info>",
|
||||
klipper_path: "<moonraker use only>",
|
||||
python_path: "<moonraker use only>",
|
||||
log_file: "<moonraker use only>",
|
||||
config_file: "<moonraker use only>",
|
||||
}
|
||||
```
|
||||
The "state" item can be one of the following:
|
||||
- "startup" - Klippy is in the process of starting up
|
||||
- "ready" - Klippy is ready
|
||||
- "shutdown" - Klippy has shutdown
|
||||
- "error" - Klippy has experienced an error during startup
|
||||
|
||||
The message from each state can be found in the `state_message`.
|
||||
- A `webhooks` printer object has been added, available for subscription or
|
||||
query. It includes the following items:
|
||||
- `state` - Printer state identical to that returned from `/printer/info`
|
||||
- `state_message` - identical to that returned from `/printer/info`
|
||||
- `/printer/objects/status` (`get_printer_objects_status`) has been renamed to
|
||||
`/printer/objects/query` (`get_printer_objects_query`). The format of the
|
||||
websocket request has changed, it should now look like the following:
|
||||
```json
|
||||
{
|
||||
jsonrpc: "2.0",
|
||||
method: "get_printer_objects_query",
|
||||
params: {
|
||||
objects: {
|
||||
gcode: null,
|
||||
toolhead: ["position", "status"]
|
||||
}
|
||||
},
|
||||
id: <request id>
|
||||
}
|
||||
```
|
||||
As shown above, printer objects are now wrapped in an "objects" parameter.
|
||||
When a client wishes to subscribe to all items of a printer object, they
|
||||
should now be set to `null` rather than an empty array.
|
||||
The return value has also changed:
|
||||
```json
|
||||
{
|
||||
eventtime: <klippy time of update>,
|
||||
status: {
|
||||
gcode: {
|
||||
busy: true,
|
||||
gcode_position: [0, 0, 0 ,0],
|
||||
...},
|
||||
toolhead: {
|
||||
position: [0, 0, 0, 0],
|
||||
status: "Ready",
|
||||
...},
|
||||
...}
|
||||
}
|
||||
```
|
||||
The `status` item now contains the requested status.
|
||||
- `/printer/objects/subscription` (`post_printer_objects_subscription`) is now
|
||||
`printer/objects/subscribe` (`post_printer_objects_subscribe`). This
|
||||
request takes parameters in the same format as the `query`. It now returns
|
||||
state for all currently subscribed objects (in the same format as a `query`).
|
||||
This data can be used to initialize all local state after the request
|
||||
completes.
|
||||
- Subscriptions are now pushed as "diffs". Clients will only recieve updates
|
||||
for subscribed items when that data changes. This requires that clients
|
||||
initialize their local state with the data returned from the subscription
|
||||
request.
|
||||
- The structure of data returned from `/printer/objects/list` has changed. It
|
||||
now returns an array of available printer objects:
|
||||
```json
|
||||
{ objects: ["gcode", "toolhead", "bed_mesh", "configfile",....]}
|
||||
```
|
||||
- The `notify_klippy_state_changed` notification has been removed. Clients
|
||||
can subscribe to `webhooks` and use `webhooks.state` to be notified of
|
||||
transitions to the "ready" and "shutdown" states
|
||||
- A `notify_klippy_disconnected` event has been added to notify clients
|
||||
when the connection between Klippy and Moonraker has been terminated.
|
||||
This event is sent with no parameters:
|
||||
```json
|
||||
{jsonrpc: "2.0", method: "notify_klippy_disconnected"}
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
Notable changes prior to 2023-02-01 may be found in [user_changes.md] and
|
||||
[api_changes.md].
|
||||
|
||||
The format is based on [Keep a Changelog].
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Added this changelog!
|
||||
- Added pyproject.toml with support for builds through [pdm](https://pdm.fming.dev/latest/).
|
||||
- **sensor**: New component for generic sensor configuration.
|
||||
- [Configuration Docs](configuration.md#sensor)
|
||||
- [API Docs](web_api.md#sensor-apis)
|
||||
- [Websocket Notification Docs](web_api.md#sensor-events)
|
||||
- **file_manager**: Added new [scan metadata](web_api.md#scan-gcode-metadata) endpoint.
|
||||
- **file_manager**: Added new [thumbnails](web_api.md#get-gcode-thumbnails) endpoint.
|
||||
- **file_manager**: Added [file_system_observer](configuration.md#file_manager)
|
||||
configuration option.
|
||||
- **file_manager**: Added [enable_observer_warnings](configuration.md#file_manager)
|
||||
configuration option.
|
||||
- **file_manager**: Added ability to upload to symbolic links.
|
||||
- **metadata**: Added support for Simplify3D V5 metadata parsing
|
||||
- **machine**: Added [shutdown_action](configuration.md#machine) configuration
|
||||
option.
|
||||
- **machine**: Added service detection to the `supervisord_cli` provider.
|
||||
- **machine**: Added `octoeverywhere` to the list of default allowed service.
|
||||
- **power**: Added support for "Hue" device groups.
|
||||
- **websockets**: Added support for [direct bridge](web_api.md#bridge-websocket)
|
||||
connections.
|
||||
- **update_manager**: Added new [refresh](web_api.md#refresh-update-status) endpoint.
|
||||
- **update_manager**: Added support for pinned pip upgrades.
|
||||
- **websockets**: Added support for post connection authentication over the websocket.
|
||||
- **scripts**: Added database backup and restore scripts.
|
||||
|
||||
### Changed
|
||||
|
||||
- Converted Moonraker source into a Python package.
|
||||
- The source from `moonraker.py` has been moved to `server.py`. The remaining code in
|
||||
`moonraker.py` serves as a legacy entry point for launching Moonraker.
|
||||
- **file_manager**: Improved inotify synchronization with API requests.
|
||||
- **file_manager**: Endpoint return values are now consistent with their
|
||||
respective websocket notifications.
|
||||
- **machine**: The [provider](configuration.md#machine) configuration option
|
||||
now expects `supervisord_cli` instead of `supervisord`.
|
||||
- **update_manager**: Relaxed requirement for git repo tag detection. Now only two
|
||||
parts are required (ie: v1.5 and v1.5.0 are acceptable).
|
||||
|
||||
### Deprecated
|
||||
|
||||
- **file_manager**: The `enable_inotify_warnings` configuration option has been
|
||||
deprecated in favor of `enable_observer_warnings`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **file_manager**: Fix edge condition where `create_file` notifications
|
||||
may be sent before a `create_dir` notification.
|
||||
- **power** - Fixed URL encoding issues for http devices.
|
||||
- **template**: A ConfigError is now raised when a template fails to
|
||||
render during configuration.
|
||||
- **machine**: Fixed support for Supervisord Version 4 and above.
|
||||
- **update_manager**: Added package resolution step to the APT backend.
|
||||
- **update_manger**: Fixed PackageKit resolution step for 64-bit systems.
|
||||
- **update_manager**: Fixed Python requirements file parsing. Comments are now ignored.
|
||||
|
||||
### Removed
|
||||
|
||||
- Pycurl dependency. Moonraker no longer uses Tornado's curl based http client.
|
||||
|
||||
## [0.7.1] - 2021-07-08
|
||||
|
||||
- Experimental pre-release
|
||||
|
||||
<!-- Links -->
|
||||
[keep a changelog]: https://keepachangelog.com/en/1.0.0/
|
||||
[semantic versioning]: https://semver.org/spec/v2.0.0.html
|
||||
[user_changes.md]: user_changes.md
|
||||
[api_changes.md]: api_changes.md
|
||||
|
||||
<!-- Versions -->
|
||||
[unreleased]: https://github.com/Arksine/moonraker/compare/v0.7.1...HEAD
|
||||
[0.7.1]: https://github.com/Arksine/moonraker/releases/tag/v0.7.1
|
||||
@@ -0,0 +1,365 @@
|
||||
## 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, transports=["http", "websocket", "mqtt"], 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 `transports` argument is a list containing any combination of
|
||||
`http`, `websocket` and `mqtt`. JSON-RPC methods for `websocket` and `mqtt`
|
||||
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
|
||||
`ServerError` 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 `ServerError` 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 `ServerError` 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 `ServerError` 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 `ServerError` will be raised.
|
||||
|
||||
### MQTT
|
||||
|
||||
If configured by the user the MQTT component is available for lookup.
|
||||
Developers may use this to subscribe and publish topics.
|
||||
|
||||
#### *MQTTClient.is_connected()*
|
||||
|
||||
Returns true if Moonraker is currently connected to the Broker, false
|
||||
otherwise.
|
||||
|
||||
#### *MQTTClient.wait_connection(timeout=None)*
|
||||
|
||||
Blocks until a connection with the broker has been successfully established
|
||||
or until the specified timeout has exceeded. Returns true if the connection
|
||||
was successful established, or False on timeout. If no timeout is specified
|
||||
then this method will block indefinitely until a connection has been
|
||||
established.
|
||||
|
||||
#### *MQTTClient.publish_topic(topic, payload=None, qos=None, retain=False)*
|
||||
|
||||
Attempts to publish a topic to the Broker. The `payload` may be a bool, int,
|
||||
float, string, or json encodable (Dict or List). If omitted then an empty
|
||||
payload is sent. The `qos` may be an integer from 0 to 2. If not specifed
|
||||
then the QOS level will use the configured default. If `retain` is set to
|
||||
`True` then the retain flag for the payload will be set.
|
||||
|
||||
Returns a Future that will block until topic is confirmed as published.
|
||||
For QOS level 0 an exception will be raised if the broker is not connected.
|
||||
|
||||
|
||||
#### *MQTTClient.publish_topic_with_response(topic, response_topic, payload=None, qos=None, retain=False, timeout=None)*
|
||||
|
||||
Publishes the supplied `topic` with the arguments specified by `payload`,
|
||||
`qos`, and `retain`, then subscribes to the `response_topic`. The payload
|
||||
delivered by the response topic is returned. Note that this method is
|
||||
a coroutine, it must always be awaited. The call will block until the
|
||||
entire process has completed unless a `timeout` (in seconds) is specifed.
|
||||
The `timeout` is applied to both the attempt to publish and the pending
|
||||
response, so the maximum waiting time would be approximately 2*timeout.
|
||||
|
||||
!!! warning
|
||||
This should only be used when it is guaranteed that the `response_topic`
|
||||
does not have a retained value. Otherwise the returned response will
|
||||
be the retained value.
|
||||
|
||||
#### *MQTTClient.subscribe_topic(topic, callback, qos=None)*
|
||||
|
||||
Subscibes to the supplied `topic` with the specified `qos`. If `qos` is not
|
||||
supplied the configured default will be used. The `callback` should be a
|
||||
callable that accepts a `payload` argument of a `bytes` type. The callable
|
||||
may be a coroutine. The callback will be run each time the subscribed topic
|
||||
is published by another client.
|
||||
|
||||
Returns a `SubscriptionHandle` that may be used to unsubscribe the topic.
|
||||
|
||||
#### *MQTTClinet.unsubscribe(hdl)*
|
||||
|
||||
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
|
||||
exist for the topic then the topic is unsubscribed from the broker.
|
||||
File diff suppressed because it is too large.
Load diff
+118
-21
@@ -6,26 +6,123 @@ the Moonraker application into the Klipper repo after Moonraker matures,
|
||||
at which point this repo will be archived. As such, contibuting guidelines
|
||||
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
|
||||
```
|
||||
- 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
|
||||
#### New Module Contributions
|
||||
|
||||
More detailed explanation if necessary.
|
||||
All source files should begin with a copyright notice in the following format:
|
||||
|
||||
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
|
||||
email address.
|
||||
```python
|
||||
# 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
|
||||
```
|
||||
|
||||
#### Git Commit Format
|
||||
|
||||
Commits should be contain one functional change. Changes that are unrelated
|
||||
or independent should be broken up into multiple commits. It is acceptable
|
||||
for a commit to contain multiple files if a change to one module depends on a
|
||||
change to another (ie: changing the name of a method).
|
||||
|
||||
Avoid merge commits. If it is necessary to update a Pull Request from the
|
||||
master branch use git's interactive rebase and force push.
|
||||
|
||||
Each Commit message should be in the following format:
|
||||
|
||||
```text
|
||||
module: brief description of commit
|
||||
|
||||
More detailed explanation of the change if required
|
||||
|
||||
Signed-off-by: Your Name <your email address>
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
- `module`: is the name of the Python module you are changing or parent
|
||||
folder if not applicable
|
||||
- `Your Name`: Your real first and last name
|
||||
- `<your email address>`: A real, reachable email address
|
||||
|
||||
For example, the git log of a new `power.py` device implementation might look
|
||||
like the following:
|
||||
|
||||
```git
|
||||
power: add support for mqtt devices
|
||||
|
||||
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
|
||||
```
|
||||
```git
|
||||
docs: add mqtt power device documentation
|
||||
|
||||
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
|
||||
```
|
||||
|
||||
By signing off on commits, you acknowledge that you agree to the
|
||||
[developer certificate of origin](../developer-certificate-of-origin)
|
||||
shown below. As mentioned above, 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.
|
||||
```
|
||||
#### Code Style
|
||||
Python methods should be fully annotated. Variables should be annotated where
|
||||
the type cannot be inferred. Moonraker uses the `mypy` static type checker for
|
||||
code validation with the following options:
|
||||
|
||||
- `--ignore-missing-imports`
|
||||
- `--follow-imports=silent`
|
||||
|
||||
No line in the source code should exceed 80 characters. Be sure there is no
|
||||
trailing whitespace. To validate code before submission one may use
|
||||
`pycodestyle` with the following options:
|
||||
|
||||
- `--ignore=E226,E301,E302,E303,W503,W504`
|
||||
- `--max-line-length=80`
|
||||
- `--max-doc-length=80`
|
||||
|
||||
Generally speaking, each line in submitted documentation should also be no
|
||||
longer than 80 characters, however there are situations where this isn't
|
||||
possible, such as long hyperlinks or example return values. Documentation
|
||||
isn't linted, so it
|
||||
|
||||
Don't peek into the member variables of another class. Use getters or
|
||||
properties to access object state.
|
||||
+58
-2
@@ -1,3 +1,59 @@
|
||||
### Moonraker Version 0.1 - August 11 2020
|
||||
- It is no longer possible to configure the subscription timer. All subscribed
|
||||
objects will update at an interval of 250ms.
|
||||
- Request timeout configuration has been removed. The server will no longer
|
||||
apply a timeout to requests. Any requests pending when Klippy disconnects
|
||||
will be aborted with an error. All pending requests are logged each minute.
|
||||
- The RESET_SD gcode is now SDCARD_RESET_FILE
|
||||
- The "virtual_sdcard" object has removed the following items:
|
||||
- "filename"
|
||||
- "total_duration"
|
||||
- "print_duration"
|
||||
- "filament_used"
|
||||
- A new object, "print_stats", has been added. It reports the following items:
|
||||
- "filename"
|
||||
- "total_duration"
|
||||
- "print_duration"
|
||||
- "filament_used"
|
||||
- "state" - can be one of the following:
|
||||
- "standby" - sd print not in progress
|
||||
- "printing" - print in progress
|
||||
- "paused" - print paused
|
||||
- "error" - print experienced an error
|
||||
- "complete" - print complete
|
||||
- "message" - contains error message when state is "error"
|
||||
- The behavior of print_stats is slightly different. When a print is finished the stats are
|
||||
not cleared. They will remain populated with the final data until the user issues a
|
||||
SDCARD_RESET_FILE gcode.
|
||||
- Moonraker Configuration has moved to moonraker.conf
|
||||
- Klippy now hosts the Unix Domain Socket. As a result, the order in which the
|
||||
Klipper and Moonraker services are started no longer matters.
|
||||
- The `notify_filelist_changed` event has been refactored for clarity. It now
|
||||
returns a result in the following format:
|
||||
```json
|
||||
{
|
||||
action: "<action>",
|
||||
item: {
|
||||
path: "<file or directory path>",
|
||||
root: "<root_name>",
|
||||
size: <file size>,
|
||||
modified: "<date modified>"
|
||||
},
|
||||
source_item: {
|
||||
path: "<file or directory path>",
|
||||
root: "<root_name>"
|
||||
}
|
||||
}
|
||||
```
|
||||
Note that the `source_item` is only present for `move_item` and `copy_item`
|
||||
actions. Below is a list of all available actions:
|
||||
- `upload_file`
|
||||
- `delete_file`
|
||||
- `create_dir`
|
||||
- `delete_dir`
|
||||
- `move_item`
|
||||
- `copy_item`
|
||||
|
||||
### Moonraker Version .08-alpha - 7/2/2020
|
||||
- Moonraker has moved to its own repo.
|
||||
- Python 3 support has been added.
|
||||
@@ -125,7 +181,7 @@
|
||||
metadata from gcode files.
|
||||
- Clean up API registration. All endpoints are now registered by Klippy
|
||||
host modules outside of static files and `/api/version`, which is used for
|
||||
compatibility with Octoprint's legacy file upload API.
|
||||
compatibility with OctoPrint's file upload API.
|
||||
- The server now runs in its own process. Communication between the Host and
|
||||
the server is done over a duplex pipe. Currently this results in a second
|
||||
log file being generated specifically for the server at
|
||||
@@ -221,7 +277,7 @@
|
||||
/printer/extras/endstops` to `GET /printer/endstops`
|
||||
- Serveral API changes have been made to accomodate the addition of webhooks:
|
||||
- `GET /printer/klippy_info` is now `GET /printer/info`. This endpoint no
|
||||
longer returns host information, as that can be retreived direct via the
|
||||
longer returns host information, as that can be retrieved direct via the
|
||||
`location` object in javascript. Instead it returns CPU information.
|
||||
- `GET /printer/objects` is no longer used to accomodate multiple request
|
||||
types by modifying the "Accept" headers. Each request has been broken
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
mkdocs==1.3.0
|
||||
pymdown-extensions==9.1
|
||||
@@ -0,0 +1,106 @@
|
||||
# Example Home Assistant configuration file for a Artillery Sidewinder X1
|
||||
# Credit to GitHub users @Kruppes and @pedrolamas
|
||||
# extended by @tispokes
|
||||
camera:
|
||||
- platform: generic
|
||||
still_image_url: http://192.168.178.66/webcam/?action=snapshot
|
||||
stream_source: http://192.168.178.66/webcam/?action=stream
|
||||
framerate: 10
|
||||
|
||||
sensor:
|
||||
- platform: rest
|
||||
name: SWX1_sensor
|
||||
resource: "http://192.168.178.66:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
|
||||
json_attributes_path: "$.result.status"
|
||||
json_attributes:
|
||||
- heater_bed
|
||||
- extruder
|
||||
- print_stats
|
||||
- toolhead
|
||||
- display_status
|
||||
- virtual_sdcard
|
||||
value_template: >-
|
||||
{{ "OK" if ("result" in value_json) else "offline" }}
|
||||
# Adding an API key is only necessary while using the [authorization] component
|
||||
# and if Home Assistant is not a trusted client
|
||||
headers:
|
||||
x-api-key: 123456789abcdefghijklmno
|
||||
|
||||
- platform: template
|
||||
sensors:
|
||||
swx1_state:
|
||||
unique_id: sensor.swx1_state
|
||||
friendly_name: "Status"
|
||||
icon_template: mdi:printer-3d
|
||||
value_template: >-
|
||||
{{ states.sensor.swx1_sensor.attributes['print_stats']['state'] if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_current_print:
|
||||
unique_id: sensor.swx1_current_print
|
||||
friendly_name: >-
|
||||
{{ "Printed" if states.sensor.swx1_sensor.attributes['display_status']['progress'] == 1 else "Printing..." }}
|
||||
icon_template: mdi:video-3d
|
||||
value_template: >-
|
||||
{{ states.sensor.swx1_sensor.attributes['print_stats']['filename'].split(".")[0] if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_current_progress:
|
||||
unique_id: sensor.swx1_current_progress
|
||||
friendly_name: "Progress"
|
||||
unit_of_measurement: '%'
|
||||
icon_template: mdi:file-percent
|
||||
value_template: >-
|
||||
{{ (states.sensor.swx1_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_print_time:
|
||||
unique_id: sensor.swx1_print_time
|
||||
friendly_name: "T-elapsed"
|
||||
icon_template: mdi:clock-start
|
||||
value_template: >-
|
||||
{{ states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_time_remaining:
|
||||
unique_id: sensor.swx1_time_remaining
|
||||
friendly_name: "T-remaining"
|
||||
icon_template: mdi:clock-end
|
||||
value_template: >-
|
||||
{{ (((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0) | timestamp_custom('%H:%M:%S', 0)) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_eta:
|
||||
unique_id: sensor.swx1_eta
|
||||
friendly_name: "T-ETA"
|
||||
icon_template: mdi:clock-outline
|
||||
value_template: >-
|
||||
{{ (as_timestamp(now()) + 2 * 60 * 60 + ((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0)) | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_nozzletemp:
|
||||
unique_id: sensor.swx1_nozzletemp
|
||||
friendly_name: >-
|
||||
Nozzle
|
||||
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['extruder']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
|
||||
icon_template: >-
|
||||
{{ "mdi:printer-3d-nozzle-heat" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:printer-3d-nozzle-heat-outline" }}
|
||||
value_template: >-
|
||||
{{ states.sensor.swx1_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
|
||||
swx1_bedtemp:
|
||||
unique_id: sensor.swx1_bedtemp
|
||||
friendly_name: >-
|
||||
Bed
|
||||
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['heater_bed']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
|
||||
icon_template: >-
|
||||
{{ "mdi:radiator" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:radiator-off" }}
|
||||
value_template: >-
|
||||
{{ states.sensor.swx1_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
|
||||
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
|
||||
# Make sure to change the `Printer` name below to the device name on your configuration
|
||||
#
|
||||
switch:
|
||||
- platform: rest
|
||||
name: SWX1_power
|
||||
resource: "http://192.168.178.66:7125/machine/device_power/device?device=SWX1"
|
||||
body_on: '{"action": "on"}'
|
||||
body_off: '{"action": "off"}'
|
||||
headers:
|
||||
Content-Type: 'application/json'
|
||||
is_on_template: >-
|
||||
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
|
||||
@@ -0,0 +1,111 @@
|
||||
# Example Home Assistant configuration file for a Voron V0.
|
||||
# Credit to GitHub users @Kruppes and @pedrolamas
|
||||
#
|
||||
sensor:
|
||||
- platform: rest
|
||||
name: Voron_V0_sensor
|
||||
resource: "http://192.168.178.56:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
|
||||
json_attributes_path: "$.result.status"
|
||||
json_attributes:
|
||||
- heater_bed
|
||||
- extruder
|
||||
- print_stats
|
||||
- toolhead
|
||||
- display_status
|
||||
- virtual_sdcard
|
||||
value_template: >-
|
||||
{{ 'OK' if ('result' in value_json) else None }}
|
||||
# Adding an API key is only necessary while using the [authorization] component
|
||||
# and if Home Assistant is not a trusted client
|
||||
headers:
|
||||
x-api-key: 123456789abcdefghijklmno
|
||||
|
||||
- platform: template
|
||||
sensors:
|
||||
|
||||
vzero_hotend_target:
|
||||
friendly_name: 'V0.126 Hotend Target'
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['extruder']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_hotend_actual:
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_bed_target:
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_bed_actual:
|
||||
device_class: temperature
|
||||
unit_of_measurement: '°C'
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_state:
|
||||
icon_template: mdi:printer-3d
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['state'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_current_print:
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['filename'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_current_progress:
|
||||
unit_of_measurement: '%'
|
||||
icon_template: mdi:file-percent
|
||||
value_template: >-
|
||||
{{ (states.sensor.voron_v0_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_print_time:
|
||||
icon_template: mdi:clock-start
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_time_remaining:
|
||||
icon_template: mdi:clock-end
|
||||
value_template: >-
|
||||
{{ (((states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] / states.sensor.voron_v0_sensor.attributes['display_status']['progress'] - states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration']) if states.sensor.voron_v0_sensor.attributes['display_status']['progress'] > 0 else 0) | timestamp_custom('%H:%M:%S', 0)) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_eta:
|
||||
icon_template: mdi:clock-outline
|
||||
value_template: >-
|
||||
{{ (as_timestamp(now()) + 2 * 60 * 60 + ((states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] / states.sensor.voron_v0_sensor.attributes['display_status']['progress'] - states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration']) if states.sensor.voron_v0_sensor.attributes['display_status']['progress'] > 0 else 0)) | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_nozzletemp:
|
||||
icon_template: mdi:thermometer
|
||||
value_template: >-
|
||||
{{ [(states.sensor.voron_v0_sensor.attributes['extruder']['temperature'] | float | round(1) | string), " / ", (states.sensor.voron_v0_sensor.attributes['extruder']['target'] | float | round(1) | string)] | join if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_bedtemp:
|
||||
icon_template: mdi:thermometer
|
||||
value_template: >-
|
||||
{{ [(states.sensor.voron_v0_sensor.attributes['heater_bed']['temperature'] | float | round(1) | string), " / ", (states.sensor.voron_v0_sensor.attributes['heater_bed']['target'] | float | round(1) | string)] | join if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
|
||||
# Make sure to change the `Printer` name below to the device name on your configuration
|
||||
#
|
||||
switch:
|
||||
- platform: rest
|
||||
name: Voron_V0_power
|
||||
resource: "http://192.168.178.56:7125/machine/device_power/device?device=Printer"
|
||||
body_on: '{"action": "on"}'
|
||||
body_off: '{"action": "off"}'
|
||||
headers:
|
||||
Content-Type: 'application/json'
|
||||
is_on_template: >-
|
||||
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
|
||||
|
||||
# MJPEG camera can be exposed to HA
|
||||
#
|
||||
camera:
|
||||
- platform: mjpeg
|
||||
name: Voron_V0_camera
|
||||
still_image_url: http://192.168.178.56/webcam/?action=snapshot
|
||||
mjpeg_url: http://192.168.178.56/webcam/?action=stream
|
||||
@@ -0,0 +1,21 @@
|
||||
# Welcome to Moonraker Documentation
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use to interact with the 3D printing firmware
|
||||
[Klipper](https://github.com/Klipper3d/klipper). Communcation between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
|
||||
is used to provide Moonraker's server functionality.
|
||||
|
||||
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.
|
||||
+576
-185
@@ -6,241 +6,632 @@ 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.
|
||||
|
||||
### Installing Klipper
|
||||
|
||||
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.
|
||||
[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).
|
||||
|
||||
Moonraker is still in alpha development, and thus some of its dependencies
|
||||
in Klipper have yet to be merged. Until this has been done it will be
|
||||
necessary to add a remote and work off a developmental branch of Klipper
|
||||
to correctly run Moonraker.
|
||||
### Klipper Configuration Requirements
|
||||
|
||||
```
|
||||
cd ~/klipper
|
||||
git remote add arksine https://github.com/Arksine/klipper.git
|
||||
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: ~/printer_data/gcodes
|
||||
```
|
||||
|
||||
Now fetch and checkout:
|
||||
```
|
||||
git fetch arksine
|
||||
git checkout arksine/dev-moonraker-testing
|
||||
```
|
||||
Note that you are now in a detached head state and you cannot pull. Any
|
||||
time you want to update to the latest version of this branch you must
|
||||
repeat the two commands above.
|
||||
### Enabling the Unix Socket
|
||||
|
||||
|
||||
For reference, if you want to switch back to the clone of the official repo:
|
||||
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:
|
||||
```
|
||||
git checkout master
|
||||
sudo nano /etc/default/klipper
|
||||
```
|
||||
Note that the above command is NOT part of the Moonraker install procedure.
|
||||
You should see a file that looks something like the following:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
|
||||
```
|
||||
|
||||
Add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
|
||||
```
|
||||
|
||||
!!! 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 configure `printer.cfg` and
|
||||
`klippy.log` so they are located in Moonraker's `data_path`, for example:
|
||||
|
||||
```
|
||||
# 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_data/config/printer.cfg -l /home/pi/printer_data/logs/klippy.log -a /tmp/klippy_uds"
|
||||
```
|
||||
|
||||
Moonraker's install script will create the data folder, however you
|
||||
may wish to create it now and move `printer.cfg` to the correct
|
||||
location, ie:
|
||||
```
|
||||
mkdir ~/printer_data
|
||||
mkdir ~/printer_data/logs
|
||||
mkdir ~/printer_data/config
|
||||
mv printer.cfg ~/printer_data/config
|
||||
```
|
||||
|
||||
### Installing Moonraker
|
||||
|
||||
Begin by cloning the git respository:
|
||||
|
||||
You can now install the Moonraker application:
|
||||
```
|
||||
cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
If you have an older version of moonraker installed, it must be removed:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./uninstall-moonraker.sh
|
||||
```
|
||||
The install script will attempt to create a basic configuration if
|
||||
`moonraker.conf` does not exist at the expected location, however if you
|
||||
prefer to have Moonraker start with a robust configuration you may create
|
||||
it now. By default the configuration file should be located at
|
||||
`$HOME/printer_data/config/moonraker.conf`, however the location of the
|
||||
data path may be configured using the script's command line options.
|
||||
The [sample moonraker.conf](./moonraker.conf) may be used as a starting
|
||||
point, full details can be found in the
|
||||
[confguration documentation](./configuration.md).
|
||||
|
||||
Finally, run moonraker's install script:
|
||||
For a default installation run the following commands:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
|
||||
- `-f`:
|
||||
Force an overwrite of Moonraker's systemd script. By default the
|
||||
the systemd script will not be modified if it exists.
|
||||
- `-a <alias>`:
|
||||
The installer uses this option to determine the name of the service
|
||||
to install. If `-d` is not provided then this options will also be
|
||||
used to determine the name of the data path folder. If omitted this
|
||||
defaults to `moonraker`.
|
||||
- `-d <path to data folder>`:
|
||||
Specifies the path to Moonraker's data folder. This folder organizes
|
||||
files and directories used by moonraker. See the `Data Folder Structure`
|
||||
section for details. If omitted this defaults to `$HOME/printer_data`.
|
||||
- `-c <path to configuration file>`
|
||||
Specifies the path to Moonraker's configuation file. By default the
|
||||
configuration is expected at `<data_folder>/config/moonraker.conf`. ie:
|
||||
`/home/pi/printer_data/config/moonraker.conf`.
|
||||
- `-l <path to log file>`
|
||||
Specifies the path to Moonraker's log file. By default Moonraker logs
|
||||
to `<data_folder>/logs/moonraker.log`. ie:
|
||||
`/home/pi/printer_data/logs/moonraker.log`.
|
||||
- `-z`:
|
||||
Disables `systemctl` commands during install (ie: daemon-reload, restart).
|
||||
This is useful for installations that occur outside of a standard environment
|
||||
where systemd is not running.
|
||||
- `-x`:
|
||||
Skips installation of [polkit rules](#policykit-permissions). This may be
|
||||
necessary to install Moonraker on systems that do not have policykit
|
||||
installed.
|
||||
|
||||
Additionally, installation may be customized with the following environment
|
||||
variables:
|
||||
|
||||
- `MOONRAKER_VENV`
|
||||
- `MOONRAKER_REBUILD_ENV`
|
||||
- `MOONRAKER_FORCE_DEFAULTS`
|
||||
- `MOONRAKER_DISABLE_SYSTEMCTL`
|
||||
- `MOONRAKER_SKIP_POLKIT`
|
||||
- `MOONRAKER_CONFIG_PATH`
|
||||
- `MOONAKER_LOG_PATH`
|
||||
- `MOONRAKER_DATA_PATH`
|
||||
|
||||
When the script completes it should start both Moonraker and Klipper. In
|
||||
`klippy.log` you should find the following entry:\
|
||||
`Moonraker: server connection detected`
|
||||
`klippy.log` you should find the following entry:
|
||||
|
||||
Currently Moonraker is responsible for creating the Unix Domain Socket,
|
||||
so so it must be started first for Klippy to connect. In any instance
|
||||
where Klipper was started first simply restart the klipper service.
|
||||
```
|
||||
sudo service klipper restart
|
||||
```
|
||||
After the connection is established Klippy will register API endpoints and
|
||||
send configuration to the server. Once the initial configuration is sent
|
||||
to Moonraker its configuration will be retained when Klippy disconnects
|
||||
(either through a restart or by stopping the service), and updated when
|
||||
Klippy reconnects.
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
|
||||
|
||||
Now you may install a client, such as
|
||||
[Mainsail](https://github.com/mainsail-crew/mainsail) or
|
||||
[Fluidd](https://github.com/cadriel/fluidd).
|
||||
|
||||
!!! Note
|
||||
Moonraker's install script no longer includes the nginx dependency.
|
||||
If you want to install one of the above clients on the local machine,
|
||||
you may want to first install nginx (`sudo apt install nginx` on
|
||||
debian/ubuntu distros).
|
||||
|
||||
|
||||
### Data Folder Structure
|
||||
|
||||
As mentioned previously, files and folders used by Moonraker are organized
|
||||
in a primary data folder. The example below illustrates the folder
|
||||
structure using the default data path of `$HOME/printer_data`.
|
||||
|
||||
# Configuration
|
||||
The host, port, log file location, socket file location and api key file
|
||||
are all specified via command arguments:
|
||||
```
|
||||
usage: moonraker.py [-h] [-a <address>] [-p <port>] [-s <socketfile>]
|
||||
[-l <logfile>] [-k <apikeyfile>]
|
||||
/home/pi/printer_data
|
||||
├── backup
|
||||
│ └── 20220822T202419Z
|
||||
│ ├── config
|
||||
│ │ └── moonraker.conf
|
||||
│ └── service
|
||||
│ └── moonraker.service
|
||||
├── certs
|
||||
│ ├── moonraker.cert (optional)
|
||||
│ └── moonraker.key (optional)
|
||||
├── config
|
||||
│ ├── moonraker.conf
|
||||
│ └── printer.cfg
|
||||
├── database
|
||||
│ ├── data.mdb
|
||||
│ └── lock.mdb
|
||||
├── gcodes
|
||||
│ ├── test_gcode_one.gcode
|
||||
│ └── test_gcode_two.gcode
|
||||
├── logs
|
||||
│ ├── klippy.log
|
||||
│ └── moonraker.log
|
||||
├── systemd
|
||||
│ └── moonraker.env
|
||||
├── moonraker.secrets (optional)
|
||||
└── moonraker.asvc
|
||||
```
|
||||
|
||||
If it is not desirible for the files and folders to exist in these specific
|
||||
locations it is acceptable to use symbolic links. For example, it is common
|
||||
for the gcode folder to be located at `$HOME/gcode_files`. Rather than
|
||||
reconfigure Klipper's `virtual_sdcard` it may be desirable to create a
|
||||
`gcodes` symbolic link in the data path pointing to this location.
|
||||
|
||||
!!! Note
|
||||
It is still possible to directly configure the paths to the configuration
|
||||
and log files if you do not wish to use the default file names of
|
||||
`moonraker.conf` and `moonraker.log`
|
||||
|
||||
When Moonraker attempts to update legacy installations symbolic links
|
||||
are used to avoid an unrecoverable error. Additionally a `backup`
|
||||
folder is created which contains the prior configuration and/or
|
||||
systemd service unit, ie:
|
||||
|
||||
```
|
||||
/home/pi/printer_data
|
||||
├── backup
|
||||
│ └── 20220822T202419Z
|
||||
│ ├── config
|
||||
│ │ ├── include
|
||||
│ │ │ ├── extras.conf
|
||||
│ │ │ ├── power.conf
|
||||
│ │ │ └── updates.conf
|
||||
│ │ └── moonraker.conf
|
||||
│ └── service
|
||||
│ └── moonraker.service
|
||||
├── certs
|
||||
│ ├── moonraker.cert -> /home/pi/certs/certificate.pem
|
||||
│ └── moonraker.key -> /home/pi/certs/key.pem
|
||||
├── config -> /home/pi/klipper_config
|
||||
├── database -> /home/pi/.moonraker_database
|
||||
├── gcodes -> /home/pi/gcode_files
|
||||
├── logs -> /home/pi/logs
|
||||
├── systemd
|
||||
│ └── moonraker.env
|
||||
└── moonraker.secrets -> /home/pi/moonraker_secrets.ini
|
||||
```
|
||||
|
||||
!!! Warning
|
||||
The gcode and config paths should not contain symbolic links
|
||||
that result in an "overlap" of on another. Moonraker uses
|
||||
inotify to watch files in each of these folders and takes action
|
||||
when a file change is detected. The action taken depends on the
|
||||
"root" folder, thus it is important that they be distinct.
|
||||
|
||||
### The systemd service file
|
||||
|
||||
The default installation will create `/etc/systemd/system/moonraker.service`.
|
||||
Below is a common example of service file, installed on a Raspberry Pi:
|
||||
|
||||
```ini
|
||||
# systemd service file for moonraker
|
||||
[Unit]
|
||||
Description=API Server for Klipper SV1
|
||||
Requires=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=pi
|
||||
SupplementaryGroups=moonraker-admin
|
||||
RemainAfterExit=yes
|
||||
WorkingDirectory=/home/pi/moonraker
|
||||
EnvironmentFile=/home/pi/printer_data/systemd/moonraker.env
|
||||
ExecStart=/home/pi/moonraker-env/bin/python $MOONRAKER_ARGS
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
```
|
||||
|
||||
Following are some items to take note of:
|
||||
|
||||
- The `Description` contains a string that Moonraker uses to validate
|
||||
the version of the service file, (notice `SV1` at the end, ie: Service
|
||||
Version 1).
|
||||
- The `moonraker-admin` supplementary group is used to grant policykit
|
||||
permissions.
|
||||
- The `EnvironmentFile` field contains Moonraker's arguments. More on this
|
||||
below.
|
||||
- The `ExecStart` field begins with the python executable, followed by
|
||||
by the enviroment variable `MOONRAKER_ARGS`. This variable is set in
|
||||
the environment file.
|
||||
|
||||
#### The Environment File
|
||||
|
||||
The environment file, `moonraker.env`. is created in the data path during
|
||||
installation. A default installation's environment file will contain the path
|
||||
to `moonraker.py` and the data path option, ie:
|
||||
|
||||
```
|
||||
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data"
|
||||
```
|
||||
|
||||
A legacy installation converted to the updated flexible service unit
|
||||
might contain the following:
|
||||
|
||||
```
|
||||
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log"
|
||||
```
|
||||
|
||||
Post installation it is simple to customize the [arguments](#command-line-usage)
|
||||
supplied to Moonraker by editing this file and restarting the service.
|
||||
|
||||
|
||||
### 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]p [-d <data path>] [-c <configfile>] [-l <logfile>] [-n]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
optional arguments:
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
-a <address>, --address <address>
|
||||
host name or ip to bind to the Web Server
|
||||
-p <port>, --port <port>
|
||||
port the Web Server will listen on
|
||||
-s <socketfile>, --socketfile <socketfile>
|
||||
file name and location for the Unix Domain Socket
|
||||
-d <data path>, --datapath <data path>
|
||||
Location of Moonraker Data File Path
|
||||
-c <configfile>, --configfile <configfile>
|
||||
Location of moonraker configuration file
|
||||
-l <logfile>, --logfile <logfile>
|
||||
log file name and location
|
||||
-k <apikeyfile>, --apikey <apikeyfile>
|
||||
API Key file location
|
||||
-n, --nologfile disable logging to a file
|
||||
-v, --verbose Enable verbose logging
|
||||
-g, --debug Enable Moonraker debug features
|
||||
-o, --asyncio-debug Enable asyncio debug flag
|
||||
```
|
||||
|
||||
The default configuration is:
|
||||
- address = 0.0.0.0 (Bind to all interfaces)
|
||||
- port = 7125
|
||||
- socketfile = /tmp/moonraker
|
||||
- logfile = /tmp/moonraker.log
|
||||
- apikeyfile = ~/.moonraker_api_key
|
||||
- `data path`: `$HOME/printer_data`
|
||||
- `config file`: `$HOME/printer_data/config/moonraker.conf`
|
||||
- `log file`: `$HOME/printer_data/logs/moonraker.log`
|
||||
- logging to a file is enabled
|
||||
- Verbose logging is disabled
|
||||
- Moonraker's debug features are disabled
|
||||
- The asyncio debug flag is set to false
|
||||
|
||||
It is recommended to use the defaults, however one may change these
|
||||
arguments by editing `/etc/default/moonraker`.
|
||||
!!! Tip
|
||||
While the `data path` option may be omitted it is recommended that it
|
||||
always be included for new installations. This allows Moonraker
|
||||
to differentiate between new and legacy installations.
|
||||
|
||||
All other configuration is sent to the server via Klippy, thus it is done in
|
||||
printer.cfg. A basic configuration that authorizes clients on a range from
|
||||
192.168.1.1 - 192.168.1.254 is as follows:
|
||||
If is necessary to run Moonraker without logging to a file the
|
||||
`-n` option may be used, for example:
|
||||
```
|
||||
[moonraker]
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -d ~/printer_data -n
|
||||
```
|
||||
|
||||
Below is a detailed explanation of all options currently available:
|
||||
```
|
||||
#[moonraker]
|
||||
#require_auth: True
|
||||
# Enables Authorization. When set to true, only trusted clients and
|
||||
# requests with an API key are accepted.
|
||||
#enable_cors: False
|
||||
# Enables CORS support. If serving static files from a different http
|
||||
# server then CORS will need to be enabled.
|
||||
#trusted_clients:
|
||||
# A list of new line separated ip addresses and/or ip ranges that are trusted.
|
||||
# Trusted clients are given full access to the API. Both IPv4 and IPv6
|
||||
# addresses and ranges are supported. Ranges must be expressed in CIDR
|
||||
# notation (see http://ip.sb/cidr for more info). For example an entry of
|
||||
# 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
|
||||
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
|
||||
# of the ip address must be 0.
|
||||
# The default is no clients or ranges are trusted.
|
||||
#request_timeout: 5.
|
||||
# The amount of time (in seconds) a client request has to process before the
|
||||
# server returns an error. This timeout does NOT apply to gcode requests.
|
||||
# Default is 5 seconds.
|
||||
#long_running_gcodes:
|
||||
# BED_MESH_CALIBRATE, 120.
|
||||
# M104, 200.
|
||||
# A list of gcodes that will be assigned their own timeout. The list should
|
||||
# be in the format presented above, where the first item is the gcode name
|
||||
# and the second item is the timeout (in seconds). Each pair should be
|
||||
# separated by a newline. The default is an empty list where no gcodes have
|
||||
# a unique timeout.
|
||||
#long_running_requests:
|
||||
# gcode/script, 60.
|
||||
# pause_resume/pause, 60.
|
||||
# pause_resume/resume, 60.
|
||||
# pause_resume/cancel, 60.
|
||||
# A list of requests that will be assigned their own timeout. The list
|
||||
# should be formatted in the same manner as long_running_gcodes. The
|
||||
# default is matches the example shown above.
|
||||
#status_tier_1:
|
||||
# toolhead
|
||||
# gcode
|
||||
#status_tier_2:
|
||||
# fan
|
||||
#status_tier_3:
|
||||
# extruder
|
||||
# virtual_sdcard
|
||||
# Subscription Configuration. By default items in tier 1 are polled every
|
||||
# 250 ms, tier 2 every 500 ms, tier 3 every 1s, tier 4 every 2s, tier
|
||||
# 5 every 4s, tier 6 every 8s.
|
||||
#tick_time: .25
|
||||
# This is the base interval used for status tier 1. All other status tiers
|
||||
# are calculated using the value defined by tick_time (See below for more
|
||||
# information). Default is 250ms.
|
||||
#config_include_path: ~/klipper_config
|
||||
# The path of a directory in which "included" configuration files reside.
|
||||
# If specified, moonraker will serve this path allowing file and directory
|
||||
# manipuation within it. Note that this should not be the same directory
|
||||
# in which printer.cfg is located (the home directory for most installations).
|
||||
# The default is None, in which no included config files will be served.
|
||||
In general it is not recommended to install Moonraker with file logging
|
||||
disabled. While moonraker will still log to stdout, all requests for support
|
||||
must be accompanied by moonraker.log.
|
||||
|
||||
These options may be changed by editing `moonraker.env`.
|
||||
|
||||
### PolicyKit Permissions
|
||||
|
||||
Some of Moonraker's components require elevated privileges to perform actions.
|
||||
Previously these actions could only be run via commandline programs launched
|
||||
with the `sudo` prefix. This has significant downsides:
|
||||
|
||||
- The user must be granted `NOPASSWD` sudo access. Raspberry Pi OS
|
||||
grants the Pi user this access by default, however most other distros
|
||||
require that this be enabled through editing `visudo` or adding files
|
||||
in `/etc/sudoers.d/`.
|
||||
- Some linux distributions require additional steps such as those taken
|
||||
in `sudo_fix.sh`.
|
||||
- Running CLI programs is relatively expensive. This isn't an issue for
|
||||
programs that are run once at startup, but is undesirable if Moonraker
|
||||
wants to poll information about the system.
|
||||
|
||||
Moonraker now supports communicating with system services via D-Bus.
|
||||
Operations that require elevated privileges are authrorized through
|
||||
PolicyKit. On startup Moonraker will check for the necessary privileges
|
||||
and warn users if they are not available. Warnings are presented in
|
||||
`moonraker.log` and directly to the user through some clients.
|
||||
|
||||
To resolve these warnings users have two options:
|
||||
|
||||
1) Install the PolicyKit permissions with the `set-policykit-rules.sh` script,
|
||||
for example:
|
||||
|
||||
```shell
|
||||
cd ~/moonraker/scripts
|
||||
./set-policykit-rules.sh
|
||||
sudo service moonraker restart
|
||||
```
|
||||
|
||||
The "status tiers" are used to determine how fast each klippy object is allowed
|
||||
to be polled. Each tier is calculated using the `tick_time` option. There are
|
||||
6 tiers, `tier_1 = tick_time` (.25s), `tier_2 = tick_time*2` (.5s),
|
||||
`tier_3 = tick_time*4` (1s), `tier_4 = tick_time*8` (2s),
|
||||
`tier_5 = tick_time*16` (4s), and `tier_6 = tick_time*16` (8s). This method
|
||||
was chosen to provide some flexibility for slower hosts while making it easy to
|
||||
batch subscription updates together.
|
||||
!!! tip
|
||||
If you still get warnings after installing the PolKit rules, run the
|
||||
install script with no options to make sure that all new dependencies
|
||||
are installed.
|
||||
|
||||
## Plugin Configuration
|
||||
The core plugins are configured via the primary configuration above. Optional
|
||||
plugins each need their own configuration as outlined below.
|
||||
```shell
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
### PanelDue Plugin
|
||||
2) Configure Moonraker to use the legacy backend implementations for
|
||||
the `machine` and/or `update_manager` components, ie:
|
||||
|
||||
```
|
||||
[moonraker_plugin paneldue]
|
||||
serial: /dev/ttyAMA0
|
||||
baud: 57600
|
||||
machine_name: Voron 2
|
||||
macros:
|
||||
LOAD_FILAMENT
|
||||
UNLOAD_FILAMENT
|
||||
PREHEAT_CHAMBER
|
||||
TURN_OFF_MOTORS
|
||||
TURN_OFF_HEATERS
|
||||
PANELDUE_BEEP FREQUENCY=500 DURATION=1
|
||||
```ini
|
||||
# Use the systemd CLI provider rather than the DBus Provider
|
||||
[machine]
|
||||
provider: systemd_cli
|
||||
|
||||
# Edit your existing [update_manager] section to disable
|
||||
# PackageKit. This will fallback to the APT CLI Package Update
|
||||
# implementation.
|
||||
[update_manager]
|
||||
#..other update manager options
|
||||
enable_packagekit: False
|
||||
|
||||
# Alternatively system updates can be disabled
|
||||
[update_manager]
|
||||
#..other update manager options
|
||||
enable_system_updates: False
|
||||
```
|
||||
|
||||
Most options above are self explanatory. The "macros" option can be used
|
||||
to specify commands (either built in or gcode_macros) that will show up
|
||||
in the PanelDue's "macro" menu.
|
||||
!!! Note
|
||||
Previously installed PolicyKit rules can be removed by running
|
||||
`set-policykit-rules.sh -c`
|
||||
|
||||
### Completing Privileged Upgrades
|
||||
|
||||
At times an update to Moonraker may require a change to the systemd service
|
||||
file, which requires sudo permission to complete. Moonraker will present
|
||||
an announcement when it need's the user's password and the process can
|
||||
be completed by entering the password through Moonraker's landing page.
|
||||
|
||||
Some users prefer not to provide these credentials via the web browser and
|
||||
instead would like to do so over ssh. These users may run
|
||||
`scripts/finish-upgrade.sh` to provide Moonraker the necessary credentials
|
||||
via ssh:
|
||||
|
||||
Note that buzzing the piezo requires the following gcode_macro:
|
||||
```
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
# Beep frequency
|
||||
default_parameter_FREQUENCY: 300
|
||||
# Beep duration in seconds
|
||||
default_parameter_DURATION: 1.
|
||||
gcode:
|
||||
{ printer.moonraker.action_call_remote_method(
|
||||
"paneldue_beep", frequency=FREQUENCY|int,
|
||||
duration=DURATION|float) }
|
||||
Utility to complete privileged upgrades for Moonraker
|
||||
|
||||
usage: finish-upgrade.sh [-h] [-a <address>] [-p <port>] [-k <api_key>]
|
||||
|
||||
optional arguments:
|
||||
-h show this message
|
||||
-a <address> address for Moonraker instance
|
||||
-p <port> port for Moonraker instance
|
||||
-k <api_key> API Key for authorization
|
||||
```
|
||||
|
||||
### Power Control Plugin
|
||||
By default the script will connect to a Moonraker instances on the local
|
||||
machine at port 7125. If the instance is not bound to localhost or is
|
||||
bound to another port the user may specify a custom address and port.
|
||||
|
||||
The API Key (`-k`) option is only necessary if the localhost is not authorized
|
||||
to access Moonraker's API.
|
||||
|
||||
### Retrieving the API Key
|
||||
|
||||
Some clients may require an API Key to connect to Moonraker. After the
|
||||
`[authorization]` component is first configured Moonraker will automatically
|
||||
generate an API Key. There are two ways in which the key may be retrieved
|
||||
by the user:
|
||||
|
||||
Retrieve the API Key via the command line (SSH):
|
||||
```
|
||||
[moonraker_plugin power]
|
||||
devices: printer, led
|
||||
# A comma separated list of devices you wish to control. Do not use spaces in
|
||||
# the device's name here
|
||||
#{dev}_name: Friendly Name
|
||||
# This is the friendly name for the device. {dev} must be swapped for the name
|
||||
# of the device used under devices, as an example:
|
||||
# printer_name: My Printer
|
||||
{dev}_pin: 23
|
||||
# This option is required.
|
||||
# The GPIO Pin number you wish to control
|
||||
#{dev}_active_low: False
|
||||
# If you have a device that needs a low or 0 signal to be turned on, set this
|
||||
# option to True.
|
||||
cd ~/moonraker/scripts
|
||||
./fetch-apikey.sh
|
||||
```
|
||||
|
||||
Define the devices you wish to control under _devices_ with a comma separated
|
||||
list. For device specific configrations, swap {dev} for the name of the device
|
||||
that you listed under devices.
|
||||
Retrieve the API Key via the browser from a trusted client:
|
||||
|
||||
Each device can have a Friendly Name, pin, and activehigh set. Pin is the only
|
||||
required option. For devices that should be active when the signal is 0 or low,
|
||||
set {dev}_activehigh to False, otherwise don't put the option in the
|
||||
configuration.
|
||||
- Navigate to `http://{moonraker-host}/access/api_key`, where
|
||||
`{moonraker-host}` is the host name or ip address of the desired
|
||||
moonraker instance.
|
||||
- The result will appear in the browser window in JSON format. Copy
|
||||
The API Key without the quotes.
|
||||
|
||||
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
|
||||
|
||||
### LMDB Database Backup and Restore
|
||||
|
||||
Moonraker uses a [LMDB Database](http://www.lmdb.tech/doc/) for persistent
|
||||
storage of procedurally generated data. LMDB database files are platform
|
||||
dependent, and thus cannot be easily transferred between different machines.
|
||||
A file generated on a Raspberry Pi cannot be directly transferred to an x86
|
||||
machine. Likewise, a file generated on a 32-bit version of Linux cannot
|
||||
be transferred to a 64-bit machine.
|
||||
|
||||
Moonraker includes two scripts, `backup-database.sh` and `restore-database.sh`
|
||||
to help facilitate database backups and transfers.
|
||||
|
||||
```shell
|
||||
~/moonraker/scripts/backup-database.sh -h
|
||||
Moonraker Database Backup Utility
|
||||
|
||||
usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]
|
||||
|
||||
optional arguments:
|
||||
-h show this message
|
||||
-e <env path> Moonraker Python Environment
|
||||
-d <database path> Moonraker LMDB database to backup
|
||||
-o <output file> backup file to save to
|
||||
```
|
||||
|
||||
```shell
|
||||
~/moonraker/scripts/restore-database.sh -h
|
||||
Moonraker Database Restore Utility
|
||||
|
||||
usage: restore-database.sh [-h] [-e <python env path>] [-d <database path>] [-i <input file>]
|
||||
|
||||
optional arguments:
|
||||
-h show this message
|
||||
-e <env path> Moonraker Python Environment
|
||||
-d <database path> Moonraker LMDB database path to restore to
|
||||
-i <input file> backup file to restore from
|
||||
```
|
||||
|
||||
Both scripts include default values for the Moonraker Environment and Database
|
||||
Path. These are `$HOME/moonraker-env` and `$HOME/printer_data/database`
|
||||
respectively. The `backup` script defaults the output value to
|
||||
`$HOME/database.backup`. The `restore` script requires that the user specify
|
||||
the input file using the `-i` option.
|
||||
|
||||
To backup a database for a default Moonraker installation the user may ssh into
|
||||
the machine and run the following command:
|
||||
|
||||
```shell
|
||||
~/moonraker/scripts/backup-database.sh -o ~/moonraker-database.backup
|
||||
```
|
||||
|
||||
And to restore the database:
|
||||
```shell
|
||||
sudo service moonraker stop
|
||||
~/moonraker/scripts/restore-database.sh -i ~/moonraker-database.backup
|
||||
sudo service moonraker start
|
||||
```
|
||||
|
||||
The backup file contains [cdb like](https://manpages.org/cdb/5) entries
|
||||
for each key/value pair in the database. All keys and values are base64
|
||||
encoded, however the data is not encrypted. Moonraker's database may
|
||||
contain credentials and other sensitive information, so users should treat
|
||||
this file accordingly. It is not recommended to keep backups in any folder
|
||||
served by Moonraker.
|
||||
|
||||
### Recovering a broken repo
|
||||
|
||||
Currently Moonraker is deployed using `git`. Without going into the gritty
|
||||
details,`git` is effectively a file system, and as such is subject to
|
||||
file system corruption in the event of a loss of power, bad sdcard, etc.
|
||||
If this occurs, updates using the `[update_manager]` may fail. In most
|
||||
cases Moonraker provides an automated method to recover, however in some
|
||||
edge cases this is not possible and the user will need to do so manually.
|
||||
This requires that you `ssh` into your machine. The example below assumes
|
||||
the following:
|
||||
|
||||
- You are using a Raspberry Pi
|
||||
- Moonraker and Klipper are installed at the default locations in the `home`
|
||||
directory
|
||||
- Both Moonraker and Klipper have been corrupted and need to be restored
|
||||
|
||||
The following commands may be used to restore Moonraker:
|
||||
|
||||
```shell
|
||||
cd ~
|
||||
rm -rf moonraker
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
cd moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
./set-policykit-rules.sh
|
||||
sudo systemctl restart moonraker
|
||||
```
|
||||
|
||||
And for Klipper:
|
||||
|
||||
```shell
|
||||
cd ~
|
||||
rm -rf klipper
|
||||
git clone https://github.com/Klipper3d/klipper.git
|
||||
sudo systemctl restart klipper
|
||||
```
|
||||
|
||||
### Debug options for developers
|
||||
|
||||
Moonraker accepts several command line arguments that can be used to
|
||||
assist both front end developers and developers interested in extending
|
||||
Moonraker.
|
||||
|
||||
- The `-v` (`--verbose`) argument enables verbose logging. This includes
|
||||
logging that reports information on all requests received and responses.
|
||||
- The `-g` (`--debug`) argument enables Moonraker's debug features,
|
||||
including:
|
||||
- Debug endpoints
|
||||
- The `update_manager` will bypass strict git repo validation, allowing
|
||||
updates from unofficial remotes and repos in a `detached HEAD` state.
|
||||
- The `-o` (`--asyncio-debug`) argument enables the asyncio debug flag. This
|
||||
will substantially increase logging and is intended for low level debugging
|
||||
of the asyncio event loop.
|
||||
|
||||
!!! Warning
|
||||
The debug option should not be enabled in production environments. The
|
||||
database debug endpoints grant read/write access to all namespaces,
|
||||
including those typically exclusive to Moonraker. Items such as user
|
||||
credentials are exposed.
|
||||
|
||||
Installations using systemd can enable debug options by editing `moonraker.env`
|
||||
via ssh:
|
||||
|
||||
```
|
||||
nano ~/printer_data/systemd/moonraker.env
|
||||
```
|
||||
|
||||
Once the file is open, append the debug option(s) (`-v` and `-g` in this example) to the
|
||||
value of `MOONRAKER_ARGS`:
|
||||
```
|
||||
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log -v -g"
|
||||
```
|
||||
|
||||
Save the file, exit the text editor, and restart the Moonraker service:
|
||||
|
||||
```
|
||||
sudo systemctl restart moonraker
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Sample Moonraker Configuration File
|
||||
#
|
||||
# !!! Moonraker does not load this file. See configuration.md !!!
|
||||
# !!! for details on path to Moonraker's configuration. !!!
|
||||
#
|
||||
|
||||
[server]
|
||||
# Bind server defaults of 0.0.0.0, port 7125
|
||||
enable_debug_logging: False
|
||||
|
||||
[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]
|
||||
# Default webcam config values:
|
||||
# flip_h = false
|
||||
# flip_v = false
|
||||
# rotate_90 = false
|
||||
# stream_url = /webcam/?action=stream
|
||||
# webcam_enabled = true
|
||||
@@ -1,3 +0,0 @@
|
||||
## Plugins
|
||||
|
||||
Documentation Forthcoming
|
||||
@@ -0,0 +1,385 @@
|
||||
#
|
||||
As mentioned in the API documentation, it is possible to
|
||||
[query](web_api.md#query-printer-object-status) or
|
||||
[subscribe](web_api.md#subscribe-to-printer-object-status)
|
||||
to "Klipper Printer Objects." There are numerous printer objects in
|
||||
Klipper, many of which are optional and only report status if they are
|
||||
enabled by Klipper's configuration. Client's may retrieve a list of
|
||||
available printer objects via the
|
||||
[list objects endpoint](web_api.md#list-available-printer-objects). This
|
||||
should be done after Klipper reports its state as "ready".
|
||||
|
||||
This section will provide an overview of the most useful printer objects.
|
||||
If a developer is interested in retrieving state for an object not listed here,
|
||||
look in Klipper's source code for module you wish to query. If the module
|
||||
contains a "get_status()" method, its return value will contain a dictionary
|
||||
that reports state which can be queried.
|
||||
|
||||
## webhooks
|
||||
```json
|
||||
{
|
||||
"state": "startup",
|
||||
"state_message": "message"
|
||||
}
|
||||
```
|
||||
The `webhooks` object contains the current printer state and the current
|
||||
state message. These fields match those returned via the `/printer/info`
|
||||
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
|
||||
so they are asynchonously notified of a change to printer state. The `state`
|
||||
may be `startup`, `ready`, `shutdown`, or `error`. The `state_message`
|
||||
contains a message specific to the current printers state.
|
||||
|
||||
## gcode_move
|
||||
```json
|
||||
{
|
||||
"speed_factor": 1.0,
|
||||
"speed": 100.0,
|
||||
"extrude_factor": 1.0,
|
||||
"absolute_coordinates": true,
|
||||
"absolute_extrude": false,
|
||||
"homing_origin": [0.0, 0.0, 0.0, 0.0],
|
||||
"position": [0.0, 0.0, 0.0, 0.0],
|
||||
"gcode_position": [0.0, 0.0, 0.0, 0.0]
|
||||
}
|
||||
```
|
||||
The `gcode_move` object reports the current gcode state:
|
||||
|
||||
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
|
||||
- `speed`: The current gcode speed in mm/s.
|
||||
- `extrude_factor`: AKA "extrusion multiplier".
|
||||
- `absolute_coorinates`: true if the machine axes are moved using
|
||||
absolute coordinates, false if using relative coordinates.
|
||||
- `absolute_extrude`: true if the extruder is moved using absolute
|
||||
coordinates, false if using relative coordinates.
|
||||
- `homing_origin`: [X, Y, Z, E] - returns the "gcode offset" applied to
|
||||
each axis. For example, the "Z" axis can be checked to determine how
|
||||
much offset has been applied via "babystepping".
|
||||
- `position`: [X, Y, Z, E] - The internal gcode position, including
|
||||
any offsets (gcode_offset, G92, etc) added to an axis.
|
||||
- `gcode_position`: [X, Y, Z, E] - The current gcode position
|
||||
sans any offsets applied. For X, Y, and Z, this should match
|
||||
the most recent "G1" or "G0" processed assuming the machine is
|
||||
using absolute coordinates.
|
||||
|
||||
!!! Note
|
||||
The printer's actual movement 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
|
||||
}
|
||||
```
|
||||
The `toolhead` object reports state of the current tool:
|
||||
|
||||
- `homed_axes`: a string containing the axes that are homed. If no axes
|
||||
are homed, returns a null string.
|
||||
- `print_time`: internal value, not generally useful for clients
|
||||
- `estimated_print_time`: internal value, not generally useful for clients.
|
||||
- `extruder`: the name of the currently selected extruder, ie "extruder"
|
||||
or "extruder1".
|
||||
- `position`: [X, Y, Z, E] - This the the last position toward which the tool
|
||||
was commanded to move. It includes any offsets applied via gcode as well
|
||||
as any transforms made by modules such as "bed_mesh", "bed_tilt", or
|
||||
"skew_correction".
|
||||
- `max_velocity`: The currently set maximum velocity of the tool (mm/s^2).
|
||||
- `max_accel`: The currently set maximum acceleration of the tool (mm/s^2).
|
||||
- `max_accel_to_decel`: The currently set maximum accel to decel of the tool.
|
||||
This value is the maximum rate at which the tool can transition from
|
||||
acceleration to deceleration (mm/s^2).
|
||||
- `square_corner_velocity`: The currently set square corner velocity. This
|
||||
is the maximum velocity at which the tool may travel a 90 degree corner.
|
||||
|
||||
!!! 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": {},
|
||||
"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. 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
|
||||
the user with the option to execute a SAVE_CONFIG gcode which will
|
||||
save the configuration to printer.cfg and restart the Klippy Host.
|
||||
|
||||
## extruder
|
||||
*Enabled when `[extruder]` is included in printer.cfg*
|
||||
!!! note
|
||||
If multiple extruders are configured, extruder 0 is available as
|
||||
`extruder`, extruder 1 as `extruder1` and so on.
|
||||
```json
|
||||
{
|
||||
"temperature": 0.0,
|
||||
"target": 0.0,
|
||||
"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*
|
||||
```json
|
||||
{
|
||||
"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*
|
||||
```json
|
||||
{
|
||||
"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
|
||||
}
|
||||
```
|
||||
|
||||
The `idle_timeout` object reports the idle state of the printer:
|
||||
|
||||
- `state`: Can be `Idle`, `Ready`, or `Printing`. The printer will
|
||||
transition to the `Printing` state whenever a gcode is issued that
|
||||
commands the tool, this includes manual commands. Thus this should
|
||||
not be used to determine if a gcode file print is in progress. It can
|
||||
however be used to determine if the printer is busy.
|
||||
- `printing_time`: The amount of time the printer has been in the
|
||||
`Printing` state. This is reset to 0 whenever the printer transitions
|
||||
from `Printing` to `Ready`.
|
||||
|
||||
## virtual_sdcard
|
||||
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
"progress": 0.0,
|
||||
"is_active": false,
|
||||
"file_position": 0
|
||||
}
|
||||
```
|
||||
The `virtual_sdcard` object reports the state of the virtual sdcard:
|
||||
|
||||
- `progress`: The print progress reported as a percentage of the file
|
||||
read, in the range of 0.0 - 1.0.
|
||||
- `is_active`: Returns true if the virtual sdcard is currently processing
|
||||
a file. Note that this will return false if a virtual sdcard print is
|
||||
paused.
|
||||
- `file_position`: The current file position in bytes. This will always
|
||||
be an integer value
|
||||
|
||||
!!! Note
|
||||
`progress` and `file_position` will persist after a print has
|
||||
paused, completed, or errored. They are cleared when the user issues
|
||||
a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## print_stats
|
||||
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
"filename": "",
|
||||
"total_duration": 0.0,
|
||||
"print_duration": 0.0,
|
||||
"filament_used": 0.0,
|
||||
"state": "standby",
|
||||
"message": ""
|
||||
}
|
||||
```
|
||||
The `print_stats` object reports `virtual_sdcard` print state:
|
||||
|
||||
- `filename`: The name of the current file loaded. This will be a null
|
||||
string if no file is loaded. Note that name is a path relative to the
|
||||
gcode folder, thus if the file is located in a subdirectory it would
|
||||
be reported as "my_sub_dir/myprint.gcode".
|
||||
- `total_duration`: The total time (in seconds) elapsed since a print
|
||||
has started. This includes time spent paused.
|
||||
- `print_duration`: The total time spent printing (in seconds). This is
|
||||
equivalent to `total_duration` - time paused.
|
||||
- `filament_used`: The amount of filament used during the current print
|
||||
(in mm). Any extrusion during a pause is excluded.
|
||||
- `state`: Current print state. Can be one of the following values:
|
||||
- `"standby"`
|
||||
- `"printing"`
|
||||
- `"paused"`
|
||||
- `"complete"`
|
||||
- `"cancelled"`
|
||||
- `"error"` - Note that if an error is detected the print will abort
|
||||
- `message`: If an error is detected, this field contains the error
|
||||
message generated. Otherwise it will be a null string.
|
||||
|
||||
!!! Note
|
||||
After a print has started all of the values above will persist until
|
||||
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## display_status
|
||||
*Enabled when `[display]` or `[display_status]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
"message": "",
|
||||
"progress": 0.0
|
||||
}
|
||||
```
|
||||
The `display_status` object contains state typically used to update displays:
|
||||
|
||||
- `message`: The message set by a M117 gcode. If no message is set this will
|
||||
be a null string.
|
||||
- `progress`: The percentage of print progress, as reported by M73. This
|
||||
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
|
||||
will fallback to the eqivalent of `virtual_sdcard.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.*
|
||||
```json
|
||||
{
|
||||
"temperature": 0.0,
|
||||
"measured_min_temp": 0.0,
|
||||
"measured_max_temp": 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_sensor` reports the following state:
|
||||
|
||||
- `temperature`: Sensor's current reported temperature
|
||||
- `measured_min_temp`: The mimimum temperature read from the sensor
|
||||
- `measured_max_temp`: The maximum temperature read from the sensor
|
||||
|
||||
## temperature_fan fan_name
|
||||
*Enabled when `[temperature_fan fan_name]` is included in printer.cfg. It is
|
||||
possible for multiple temperature fans to be configured.*
|
||||
```json
|
||||
{
|
||||
"speed": 0.0,
|
||||
"temperature": 0.0,
|
||||
"target": 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_fan` reports the following state:
|
||||
|
||||
- `speed`: Current fan speed as a percentage of maximum speed, reported
|
||||
in the range of 0.0 - 1.0
|
||||
- `temperature`: Currently reported temperature of the sensor associated
|
||||
with the fan
|
||||
- `target`: The current target temperature for the `temperature_fan`.
|
||||
|
||||
## filament_switch_sensor sensor_name
|
||||
*Enabled when `[filament_switch_sensor sensor_name]` is included in
|
||||
printer.cfg. It is possible for multiple filament sensors to be configured.*
|
||||
```json
|
||||
{
|
||||
"filament_detected": false,
|
||||
"enabled": true
|
||||
}
|
||||
```
|
||||
A `filament_switch_sensor` reports the following state:
|
||||
|
||||
- `filament_detected`: Set to true if the switch detects filament, otherwise
|
||||
false
|
||||
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
|
||||
|
||||
## output_pin pin_name
|
||||
*Enabled when `[output_pin pin_name]` is included in printer.cfg.
|
||||
It is possible for multiple output pins to be configured.*
|
||||
```json
|
||||
{
|
||||
"value": 0.0
|
||||
}
|
||||
```
|
||||
An `output_pin` reports the following state:
|
||||
|
||||
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
|
||||
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
|
||||
across the entire range.
|
||||
|
||||
## bed_mesh
|
||||
*Enabled when `[bed_mesh]` is included in printer.cfg.*
|
||||
```json
|
||||
{
|
||||
"profile_name": "",
|
||||
"mesh_min": [0.0, 0.0],
|
||||
"mesh_max": [0.0, 0.0],
|
||||
"probed_matrix": [[]],
|
||||
"mesh_matrix": [[]]
|
||||
}
|
||||
```
|
||||
The `bed_mesh` printer object reports the following state:
|
||||
|
||||
- `profile_name`: The name of the currently loaded profile. If no profile is
|
||||
loaded then this will report a null string. If the user is not using
|
||||
bed_mesh profile management then this will report `default` after mesh
|
||||
calibration completes.
|
||||
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
|
||||
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
|
||||
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
|
||||
values. If the matrix has not been probed the the result is `[[]]`.
|
||||
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
|
||||
no matrix has been generated the result is `[[]]`.
|
||||
|
||||
!!! 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.*
|
||||
|
||||
Gcode macros will report the state of configured `variables`.
|
||||
While user defined macros likely won't report state that is useful
|
||||
for a client, it is possible for client developers to recommend or
|
||||
request a specific gcode_macro configuration, then have the client
|
||||
take action based on the variables reported by the macro.
|
||||
@@ -0,0 +1,177 @@
|
||||
##
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
|
||||
### Februrary 8th 2023
|
||||
- The `provider` option in the `[machine]` section no longer accepts
|
||||
`supervisord` as an option. It has been renamed to `supervisord_cli`.
|
||||
|
||||
### January 2nd 2023
|
||||
- The `bound_service` option for `[power]` devices has been deprecated in
|
||||
favor of `bound_services`. Currently this change does not generate a
|
||||
warning as it can be reliably resolved internally.
|
||||
|
||||
### October 14th 2022
|
||||
- The systemd service file is now versioned. Moonraker can now detect when
|
||||
the file is out of date and automate corrections as necessary.
|
||||
- Moonraker's command line options are now specified in an environment file,
|
||||
making it possible to change these options without modifying the service file
|
||||
and reloading the systemd daemon. The default location of the environment
|
||||
file is `~/printer_data/systemd/moonraker.env`.
|
||||
- Moonraker now manages files and folders in a primary data folder supplied
|
||||
by the `-d` (`--data-path`) command line option. As a result, the following
|
||||
options have been deprecated:
|
||||
- `ssl_certificate_path` in `[server]`
|
||||
- `ssl_key_path` in `[server]`
|
||||
- `database_path` in `[database]`
|
||||
- `config_path` in `[file_manager]`
|
||||
- `log_path` in `[file_manager]`
|
||||
- `secrets_path` in `[secrets]`
|
||||
- Debugging options are now supplied to Moonraker via the command line.
|
||||
The `-v` (`--verbose`) option enables verbose logging, while the `-g`
|
||||
(`--debug`) option enables debug features, including access to debug
|
||||
endpoints and the repo debug feature in `update_manager`. As a result,
|
||||
the following options are deprecated:
|
||||
- `enable_debug_logging` in `[server]`
|
||||
- `enable_repo_debug` in `[update_manager]`
|
||||
|
||||
### July 27th 2022
|
||||
- The behavior of `[include]` directives has changed. Included files
|
||||
are now parsed as they are encountered. If sections are duplicated
|
||||
options in the last section parsed take precendence. If you are
|
||||
using include directives to override configuration in `moonraker.conf`
|
||||
the directives should be moved to the bottom of the file.
|
||||
- Configuration files now support inline comments.
|
||||
|
||||
### April 6th 2022
|
||||
- The ability to configure core components in the `[server]`section
|
||||
is now deprecated. When legacy items are detected in `[server]` a
|
||||
warning will be generated. It is crucially important to move configuration
|
||||
to the correct section as in the future it will be a hard requirement.
|
||||
|
||||
### Feburary 22nd 2022
|
||||
- The `on_when_upload_queued` option for [power] devices has been
|
||||
deprecated in favor of `on_when_job_queued`. As the new option
|
||||
name implies, this option will power on the device when any new
|
||||
job is queued, not only when its sourced from an upload. The
|
||||
`on_when_upload_queued` option will be treated as an alias to
|
||||
`on_when_job_queued` until its removal.
|
||||
|
||||
### February 16th 2022
|
||||
- Webcam settings can now be defined in the `moonraker.conf` file, under
|
||||
the `[octoprint_compat]` section. The default values are being used as
|
||||
default values.
|
||||
|
||||
Default values:
|
||||
| Setting | Default value |
|
||||
|---------|---------------|
|
||||
| flip_h | False |
|
||||
| flip_v | False |
|
||||
| rotate_90 | False |
|
||||
| stream_url | /webcam/?action=stream |
|
||||
| webcam_enabled | True |
|
||||
|
||||
### January 22th 2022
|
||||
- The `color_order` option in the `[wled]` section has been deprecated.
|
||||
This is configured in wled directly. This is not a breaking change,
|
||||
the setting will simply be ignored not affecting functionality.
|
||||
|
||||
### December 24th 2021
|
||||
- The `password_file` option in the `[mqtt]` section has been deprecated.
|
||||
Use the `password` option instead. This option may be a template, thus
|
||||
can resolve secrets stored in the `[secrets]` module.
|
||||
|
||||
### November 7th 2021
|
||||
- Previously all core components received configuration through
|
||||
the `[server]` config section. As Moonraker's core functionality
|
||||
has expanded this is becoming unsustainable, thus core components
|
||||
should now be configured in their own section. For example, the
|
||||
`config_path` and `log_path` should now be configured in the
|
||||
`[file_manager]` section of `moonraker.conf`. See the
|
||||
[configuration documentation](https://moonraker.readthedocs.io/en/latest/configuration/)
|
||||
for details. This is not a breaking change, core components
|
||||
will still fall back to checking the `[server]` section for
|
||||
configuration.
|
||||
|
||||
### April 19th 2021
|
||||
- The `[authorization]` module is now a component, thus is only
|
||||
loaded if the user has it configured in `moonraker.conf`. This
|
||||
deprecates the previous `enable` option, as it is enabled
|
||||
if configured and disabled otherwise.
|
||||
- The API Key is now stored in the database. This deprecates the
|
||||
`api_key_file` option in the `[authorization]` module. Users can
|
||||
no longer read the contents of the API Key file to retrieve the
|
||||
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
|
||||
print the API Key. Alternative a user can navigate to
|
||||
`http://{moonraker-host}/access/api_key` from a trusted client
|
||||
to retrieve the API Key.
|
||||
|
||||
### 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:\
|
||||
`-r` Rebuild the python virtual env\
|
||||
`-f` Force an overwrite of `/etc/default/moonraker` during installation\
|
||||
`-c /path/to/moonraker.conf` Allows user to specify the path to
|
||||
moonraker.conf during configuration. Using this in conjunction with `-f`
|
||||
will update the defaults file wih the new path.
|
||||
- New dependencies have been added to Moonraker which require reinstallation.
|
||||
Run the following command to reinstall and rebuild the virtualenv:
|
||||
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
|
||||
- The power plugin configuration has changed. See the
|
||||
[install guide](installation.md#power-control-plugin) for
|
||||
details on the new configuration.
|
||||
- Users transitioning from the previous version of the power plugin will need
|
||||
to unexport any curently used pins. For example, the following command
|
||||
may be used to unexport pin 19:
|
||||
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
|
||||
Alternatively one may reboot the machine after upgrading:
|
||||
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
|
||||
Make sure that the power plugin configuration has been updated prior
|
||||
to rebooting the machine.
|
||||
+6838
-597
File diff suppressed because it is too large.
Load diff
+24
@@ -0,0 +1,24 @@
|
||||
site_name: Moonraker
|
||||
site_url: https://moonraker.readthedocs.io
|
||||
repo_url: https://github.com/Arksine/moonraker
|
||||
nav:
|
||||
- 'User Documentation':
|
||||
- Installation: installation.md
|
||||
- Configuration : configuration.md
|
||||
- 'Developer Documenation':
|
||||
- Remote API: web_api.md
|
||||
- Printer Objects: printer_objects.md
|
||||
- Components: components.md
|
||||
- 'Miscellaneous':
|
||||
- Contributing: contributing.md
|
||||
- Changelog: changelog.md
|
||||
theme:
|
||||
name: readthedocs
|
||||
plugins:
|
||||
- search
|
||||
markdown_extensions:
|
||||
- admonition
|
||||
- pymdownx.superfences
|
||||
- pymdownx.highlight:
|
||||
use_pygments: false
|
||||
- pymdownx.inlinehilite
|
||||
@@ -0,0 +1,5 @@
|
||||
# Top level package definition for Moonraker
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
@@ -0,0 +1,9 @@
|
||||
# Package entry point for Moonraker
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from .server import main
|
||||
|
||||
main()
|
||||
+968
-233
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
# Assets Package Definition
|
||||
@@ -0,0 +1,500 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Moonraker {{ version }}</title>
|
||||
<style>
|
||||
body {
|
||||
background-color: rgb(48, 48, 48);
|
||||
color: rgb(230, 230, 230);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
margin: 0px;
|
||||
}
|
||||
.nav-bar {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
.nav-bar a {
|
||||
float: right;
|
||||
text-align: center;
|
||||
padding: .5em .75em;
|
||||
font-size: 1.2em;
|
||||
text-decoration: none;
|
||||
color: rgb(230, 230, 230);
|
||||
}
|
||||
.intro {
|
||||
font-size: 1.1em;
|
||||
margin-top: 7rem;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
width: 60%;
|
||||
}
|
||||
.intro h1 {
|
||||
font-size: 2.2rem;
|
||||
text-align: center;
|
||||
}
|
||||
.status {
|
||||
display: flex;
|
||||
margin-top: 2rem;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
width: 80%;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
column-gap: 1.5rem;
|
||||
row-gap: 1.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.card {
|
||||
background:none;
|
||||
border: 0px;
|
||||
border-radius: .75rem;
|
||||
width: 25rem;
|
||||
}
|
||||
.card h1 {
|
||||
background-color: #225353;
|
||||
text-align: center;
|
||||
line-height: 2.2rem;
|
||||
font-size: 1.1rem;
|
||||
height: 2.2rem;
|
||||
margin: 0;
|
||||
border-top-left-radius: .75rem;
|
||||
border-top-right-radius: .75rem;
|
||||
}
|
||||
.card .content{
|
||||
background-color: #1a1a1a;
|
||||
border-bottom-left-radius: .75rem;
|
||||
border-bottom-right-radius: .75rem;
|
||||
padding: .5rem;
|
||||
}
|
||||
.card .entry {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
}
|
||||
.card .entry:not(:last-child) {
|
||||
margin-bottom: .4rem;
|
||||
}
|
||||
.card .value {
|
||||
float: right;
|
||||
display: inline;
|
||||
}
|
||||
.messages {
|
||||
margin-top: 2rem;
|
||||
width: 51.5rem;
|
||||
padding: .5rem;
|
||||
}
|
||||
.messages .item {
|
||||
padding: .5rem;
|
||||
background: #242424;
|
||||
border-radius: .4rem;
|
||||
}
|
||||
.messages .announcement {
|
||||
cursor: pointer;
|
||||
}
|
||||
.messages .item:not(:last-child) {
|
||||
margin-bottom: .5rem;
|
||||
}
|
||||
.messages .item a {
|
||||
font-size: 1.2rem;
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
padding: 0rem;
|
||||
margin-bottom: .1rem;
|
||||
text-decoration: None;
|
||||
color: rgb(230, 230, 230);
|
||||
}
|
||||
.messages .item:hover {
|
||||
background-color: #3f3f3f;
|
||||
}
|
||||
.messages .item:hover a,
|
||||
.messages .item a:hover {
|
||||
color: rgb(235, 199, 0);
|
||||
}
|
||||
.messages .item p {
|
||||
font-size: 1rem;
|
||||
}
|
||||
.warning h1 {
|
||||
animation: glow 1s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@keyframes glow {
|
||||
from {
|
||||
background-color: #225353;
|
||||
}
|
||||
to {
|
||||
background-color: rgb(160, 64, 8);
|
||||
}
|
||||
}
|
||||
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
background-color: rgb(0,0,0);
|
||||
background-color: rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.modal-card {
|
||||
background: none;
|
||||
position: relative;
|
||||
border: 0px;
|
||||
border-radius: 1rem;
|
||||
background-color: #1a1a1a;
|
||||
margin: 20% auto 2rem auto;
|
||||
padding: 0rem;
|
||||
border: 0px;
|
||||
width: 50%;
|
||||
animation-name: fadein;
|
||||
animation-duration: .5s;
|
||||
}
|
||||
|
||||
.modal-card h1 {
|
||||
background-color: #006f7e;
|
||||
text-align: center;
|
||||
line-height: 3rem;
|
||||
font-size: 1.1rem;
|
||||
height: 3rem;
|
||||
margin: 0;
|
||||
border-top-left-radius: 1rem;
|
||||
border-top-right-radius: 1rem;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: #3e3e3e;
|
||||
padding: 1rem;
|
||||
margin: 0;
|
||||
height: auto
|
||||
}
|
||||
|
||||
.modal-content .entry {
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
}
|
||||
.modal-content .entry:not(:last-child) {
|
||||
margin-bottom: .5rem;
|
||||
}
|
||||
.modal-content .value {
|
||||
float: right;
|
||||
display: inline;
|
||||
}
|
||||
.modal-content input {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
-moz-border-radius: 4px;
|
||||
-webkit-border-radius: 4px;
|
||||
font-size: 1rem; color: #222;
|
||||
background: #F7F7F7;
|
||||
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
display: inline-block;
|
||||
background-color: #3e3e3e;
|
||||
margin: 0;
|
||||
height: auto;
|
||||
width: 100%;
|
||||
border-bottom-left-radius: 1rem;
|
||||
border-bottom-right-radius: 1rem;
|
||||
}
|
||||
|
||||
.modal-button {
|
||||
float: right;
|
||||
background: #cecece;
|
||||
border: none;
|
||||
width: auto;
|
||||
overflow: visible;
|
||||
font-size: 1rem;
|
||||
font-weight: bold;
|
||||
color: rgb(0, 0, 0);
|
||||
padding: .4rem .5rem;
|
||||
margin: 0rem .5rem .5rem 0rem;
|
||||
border-radius: .5rem;
|
||||
-webkit-border-radius: .5rem;
|
||||
-moz-border-radius: .5rem;
|
||||
}
|
||||
|
||||
.modal-button:hover {
|
||||
color: rgb(8, 154, 45);
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-status {
|
||||
display: none;
|
||||
position: relative;
|
||||
border: 0;
|
||||
border-radius: 1rem;
|
||||
background-color: #3e3e3e;
|
||||
margin: auto;
|
||||
padding: 0rem;
|
||||
width: 50%;
|
||||
animation-name: fadebottom;
|
||||
animation-duration: .5s;
|
||||
}
|
||||
|
||||
.modal-status:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-status .content {
|
||||
display: inline-block;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
@keyframes fadebottom {
|
||||
from {top: 10em; opacity: 0}
|
||||
to {top: 0em; opacity: 1}
|
||||
}
|
||||
|
||||
@keyframes fadein {
|
||||
from {opacity: 0}
|
||||
to {opacity: 1}
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
function setClickable(id) {
|
||||
const item = document.querySelector(`#${id}`);
|
||||
const primary_link = item.querySelector("a");
|
||||
const clickable = Array.from(item.querySelectorAll(".clickable"));
|
||||
clickable.forEach((element) => {
|
||||
element.addEventListener("click", (evt) => {
|
||||
evt.stopPropagation();
|
||||
})
|
||||
});
|
||||
function onItemClicked(evt) {
|
||||
const noTextSelected = !window.getSelection().toString();
|
||||
if (noTextSelected)
|
||||
primary_link.click();
|
||||
}
|
||||
item.addEventListener("click", onItemClicked);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<div class="nav-bar">
|
||||
<a href="https://github.com/Arksine/moonraker">GitHub</a>
|
||||
<a href="https://moonraker.readthedocs.io">Documentation</a>
|
||||
</div>
|
||||
<div class="intro">
|
||||
<h1>Welcome to Moonraker</h1>
|
||||
<p>You may have intended
|
||||
to navigate to one of Moonraker's front ends, if so check
|
||||
that you entered the correct port in the address bar.
|
||||
</p>
|
||||
</div>
|
||||
<div class="status">
|
||||
<article class="card">
|
||||
<h1>Authorization</h1>
|
||||
<div class="content">
|
||||
<div class="entry">
|
||||
Request IP:
|
||||
<div class="value">{{ remote_ip }}</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
Authorized:
|
||||
<div class="value">{{ authorized }}</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
CORS Enabled:
|
||||
<div class="value">{{ cors_enabled }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<h1>Status</h1>
|
||||
<div class="content">
|
||||
<div class="entry">
|
||||
Version:
|
||||
<div class="value">{{ version }}</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
Websocket Count:
|
||||
<div class="value">{{ ws_count }}</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
Klipper State:
|
||||
<div class="value">{{ klippy_state }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
{% if summary %}
|
||||
<article class="card messages">
|
||||
<h1>Summary</h1>
|
||||
<div class="content">
|
||||
{% for item in summary %}
|
||||
<article class="item">{{ item }}</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</article>
|
||||
{% endif %}
|
||||
{% if announcements %}
|
||||
<article class="card messages">
|
||||
<h1>Announcements</h1>
|
||||
<div class="content">
|
||||
{% for item in announcements %}
|
||||
{% set id = "announcement-" + item["entry_id"].replace("/", "-") %}
|
||||
<article class="item announcement" id="{{ id }}">
|
||||
{% set url = item["url"] %}
|
||||
<a href="{{ url }}" class="clickable">{{ item["title"] }}</a>
|
||||
<p>{{ item["description"] }}</p>
|
||||
</article>
|
||||
<script>
|
||||
setClickable("{{ id }}");
|
||||
</script>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</article>
|
||||
{% endif %}
|
||||
{% if warnings %}
|
||||
<article class="card messages warning">
|
||||
<h1>Warnings</h1>
|
||||
<div class="content">
|
||||
{% for warn in warnings %}
|
||||
<article class="item">{{ warn }}</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</article>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div id="update_modal" class="modal">
|
||||
<div class="modal-card">
|
||||
<h1 id="modal_header_msg">
|
||||
Moonraker Sudo Password Request
|
||||
</h1>
|
||||
<div id="modal_body" class="modal-content">
|
||||
<div id="main_form">
|
||||
<div class="entry">
|
||||
Service Name:
|
||||
<div class="value">
|
||||
{{ service_name }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
Host Name:
|
||||
<div class="value">
|
||||
{{ hostname }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
Host IP Address:
|
||||
<div class="value">
|
||||
{{ local_ip }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="entry">
|
||||
{{ sudo_request_message }}
|
||||
Please enter the password for linux user <b>{{ linux_user }}</b>:
|
||||
</div>
|
||||
<div class="entry">
|
||||
<input id="sudo_passwd" name="sudo_passwd" type="password" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" id="modal_close" class="modal-button">Cancel</button>
|
||||
<button type="button" id="modal_submit" class="modal-button">Submit</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="modal_status" class="modal-status">
|
||||
<div id="status_msg" class="content">
|
||||
Status Text
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const modal = document.getElementById("update_modal");
|
||||
{% if sudo_requested %}
|
||||
modal.style.display = "block";
|
||||
{% endif %}
|
||||
const main_form = document.getElementById("main_form")
|
||||
const status_item = document.getElementById("modal_status");
|
||||
const status_div = document.getElementById("status_msg");
|
||||
|
||||
function update_modal(status_msg) {
|
||||
status_div.innerHTML = status_msg
|
||||
status_item.style.display = "block";
|
||||
}
|
||||
|
||||
function dismiss_status() {
|
||||
status_item.style.display = "none";
|
||||
}
|
||||
|
||||
function check_success(req) {
|
||||
return (req.status < 205 || req.status == 304);
|
||||
}
|
||||
|
||||
function post_machine_password(passwd) {
|
||||
let pwd_req = new XMLHttpRequest();
|
||||
pwd_req.onload = () => {
|
||||
if (check_success(pwd_req)) {
|
||||
console.log("Successfully Set Sudo Password");
|
||||
let resp = JSON.parse(pwd_req.responseText)
|
||||
let msg = resp.result.sudo_responses.join("<br/>")
|
||||
msg += "<br/><br/>You may close this window and return to the front end.";
|
||||
update_modal(msg);
|
||||
} else {
|
||||
console.log("Password Request Error");
|
||||
let err_msg = `Code ${pwd_req.status}: `;
|
||||
let response = pwd_req.responseText;
|
||||
try {
|
||||
let json_resp = JSON.parse(response);
|
||||
err_msg = json_resp.error.message;
|
||||
} catch (error) {}
|
||||
update_modal(
|
||||
"Request failed with error:<br/><br/>" + err_msg +
|
||||
"<br/><br/>You may need to manually update your installation."
|
||||
);
|
||||
}
|
||||
};
|
||||
pwd_req.onerror = () => {
|
||||
console.log("Error setting password");
|
||||
update_modal(
|
||||
"Request to set sudo password failed with " +
|
||||
"a network error."
|
||||
)
|
||||
};
|
||||
pwd_req.open("POST", "/machine/sudo/password");
|
||||
pwd_req.setRequestHeader("Content-Type", "application/json");
|
||||
pwd_req.send(JSON.stringify({"password": passwd}));
|
||||
}
|
||||
|
||||
const modal_submit = document.getElementById("modal_submit");
|
||||
const pwd_input = document.getElementById("sudo_passwd");
|
||||
const modal_close = document.getElementById("modal_close");
|
||||
|
||||
modal_submit.onclick = () => {
|
||||
let val = pwd_input.value;
|
||||
pwd_input.value = "";
|
||||
dismiss_status();
|
||||
post_machine_password(val);
|
||||
};
|
||||
|
||||
pwd_input.addEventListener("keypress", (event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
modal_submit.click();
|
||||
}
|
||||
});
|
||||
|
||||
modal_close.onclick = () => {
|
||||
modal.style.display = "none";
|
||||
};
|
||||
|
||||
status_item.onclick = () => {
|
||||
dismiss_status();
|
||||
}
|
||||
|
||||
window.onclick = (event) => {
|
||||
if (event.target == modal) {
|
||||
modal.style.display = "none";
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,247 +0,0 @@
|
||||
# API Key Based Authorization
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import base64
|
||||
import uuid
|
||||
import os
|
||||
import time
|
||||
import ipaddress
|
||||
import logging
|
||||
import tornado
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
TOKEN_TIMEOUT = 5
|
||||
CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300 * 1000
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, api_key_file):
|
||||
self.api_key_loc = os.path.expanduser(api_key_file)
|
||||
self.api_key = self._read_api_key()
|
||||
self.auth_enabled = True
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
self.trusted_connections = {}
|
||||
self.access_tokens = {}
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
self.prune_handler.start()
|
||||
|
||||
def load_config(self, config):
|
||||
self.auth_enabled = config.get("require_auth", self.auth_enabled)
|
||||
# reset trusted ips
|
||||
self.trusted_ips = []
|
||||
trusted_ips = config.get("trusted_ips", [])
|
||||
for ip in trusted_ips:
|
||||
try:
|
||||
ip_addr = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
logging.info("IP address <%s> invalid" % (ip))
|
||||
continue
|
||||
self.trusted_ips.append(ip_addr)
|
||||
# reset trusted ranges
|
||||
self.trusted_ranges = []
|
||||
trusted_ranges = config.get("trusted_ranges", [])
|
||||
for ip_range in trusted_ranges:
|
||||
try:
|
||||
ip_net = ipaddress.ip_network(ip_range)
|
||||
except ValueError:
|
||||
logging.info("IP range <%s> invalid" % (ip_range))
|
||||
continue
|
||||
self.trusted_ranges.append(ip_net)
|
||||
self._reset_trusted_connections()
|
||||
t_clients = [str(ip) for ip in self.trusted_ips] + \
|
||||
[str(rng) for rng in self.trusted_ranges]
|
||||
logging.info(
|
||||
"Authorization Configuration Loaded\n"
|
||||
"Auth Enabled: %s\n"
|
||||
"Trusted Clients:\n%s" %
|
||||
(self.auth_enabled, "\n".join(t_clients)))
|
||||
|
||||
def register_handlers(self, app):
|
||||
# Register Authorization Endpoints
|
||||
app.register_local_handler(
|
||||
"/access/api_key", None, ['GET', 'POST'],
|
||||
self._handle_apikey_request, http_only=True)
|
||||
app.register_local_handler(
|
||||
"/access/oneshot_token", None, ['GET'],
|
||||
self._handle_token_request, http_only=True)
|
||||
|
||||
async def _handle_apikey_request(self, path, method, args):
|
||||
if method.upper() == 'POST':
|
||||
self.api_key = self._create_api_key()
|
||||
return self.api_key
|
||||
|
||||
async def _handle_token_request(self, path, method, args):
|
||||
return self.get_access_token()
|
||||
|
||||
def _read_api_key(self):
|
||||
if os.path.exists(self.api_key_loc):
|
||||
with open(self.api_key_loc, 'r') as f:
|
||||
api_key = f.read()
|
||||
return api_key
|
||||
# API Key file doesn't exist. Generate
|
||||
# a new api key and create the file.
|
||||
logging.info(
|
||||
"No API Key file found, creating new one at:\n%s"
|
||||
% (self.api_key_loc))
|
||||
return self._create_api_key()
|
||||
|
||||
def _create_api_key(self):
|
||||
api_key = uuid.uuid4().hex
|
||||
with open(self.api_key_loc, 'w') as f:
|
||||
f.write(api_key)
|
||||
return api_key
|
||||
|
||||
def _reset_trusted_connections(self):
|
||||
valid_conns = {}
|
||||
for ip, access_time in self.trusted_connections.items():
|
||||
if self._check_authorized_ip(ip):
|
||||
valid_conns[ip] = access_time
|
||||
else:
|
||||
logging.info(
|
||||
"Connection [%s] no longer trusted, removing" % (ip))
|
||||
self.trusted_connections = valid_conns
|
||||
|
||||
def _check_authorized_ip(self, ip):
|
||||
if ip in self.trusted_ips:
|
||||
return True
|
||||
for rng in self.trusted_ranges:
|
||||
if ip in rng:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _prune_conn_handler(self):
|
||||
cur_time = time.time()
|
||||
expired_conns = []
|
||||
for ip, access_time in self.trusted_connections.items():
|
||||
if cur_time - access_time > CONNECTION_TIMEOUT:
|
||||
expired_conns.append(ip)
|
||||
for ip in expired_conns:
|
||||
self.trusted_connections.pop(ip, None)
|
||||
logging.info(
|
||||
"Trusted Connection Expired, IP: %s" % (ip))
|
||||
|
||||
def _token_expire_handler(self, token):
|
||||
self.access_tokens.pop(token, None)
|
||||
|
||||
def is_enabled(self):
|
||||
return self.auth_enabled
|
||||
|
||||
def get_access_token(self):
|
||||
token = base64.b32encode(os.urandom(20)).decode()
|
||||
ioloop = IOLoop.current()
|
||||
self.access_tokens[token] = ioloop.call_later(
|
||||
TOKEN_TIMEOUT, self._token_expire_handler, token)
|
||||
return token
|
||||
|
||||
def _check_trusted_connection(self, ip):
|
||||
if ip is not None:
|
||||
if ip in self.trusted_connections:
|
||||
self.trusted_connections[ip] = time.time()
|
||||
return True
|
||||
elif self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
"Trusted Connection Detected, IP: %s" % (ip))
|
||||
self.trusted_connections[ip] = time.time()
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_access_token(self, token):
|
||||
if token in self.access_tokens:
|
||||
token_handler = self.access_tokens.pop(token, None)
|
||||
IOLoop.current().remove_timeout(token_handler)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def check_authorized(self, request):
|
||||
# Authorization is disabled, request may pass
|
||||
if not self.auth_enabled:
|
||||
return True
|
||||
|
||||
# Check if IP is trusted
|
||||
try:
|
||||
ip = ipaddress.ip_address(request.remote_ip)
|
||||
except ValueError:
|
||||
logging.exception(
|
||||
"Unable to Create IP Address %s" % (request.remote_ip))
|
||||
ip = None
|
||||
if self._check_trusted_connection(ip):
|
||||
return True
|
||||
|
||||
# Check API Key Header
|
||||
key = request.headers.get("X-Api-Key")
|
||||
if key and key == self.api_key:
|
||||
return True
|
||||
|
||||
# Check one-shot access token
|
||||
token = request.arguments.get('token', [b""])[0].decode()
|
||||
if self._check_access_token(token):
|
||||
return True
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
self.prune_handler.stop()
|
||||
|
||||
class AuthorizedRequestHandler(tornado.web.RequestHandler):
|
||||
def initialize(self, server, auth):
|
||||
self.server = server
|
||||
self.auth = auth
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def set_default_headers(self):
|
||||
if self.settings['enable_cors']:
|
||||
self.set_header("Access-Control-Allow-Origin", "*")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.settings['enable_cors']:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedRequestHandler, self).options()
|
||||
|
||||
# Due to the way Python treats multiple inheritance its best
|
||||
# to create a separate authorized handler for serving files
|
||||
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
|
||||
def initialize(self, server, auth, path, default_filename=None):
|
||||
super(AuthorizedFileHandler, self).initialize(path, default_filename)
|
||||
self.server = server
|
||||
self.auth = auth
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def set_default_headers(self):
|
||||
if self.settings['enable_cors']:
|
||||
self.set_header("Access-Control-Allow-Origin", "*")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
self.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.settings['enable_cors']:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedFileHandler, self).options()
|
||||
@@ -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>
|
||||
#
|
||||
@@ -0,0 +1,541 @@
|
||||
# Support for Moonraker/Klipper/Client announcements
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import datetime
|
||||
import pathlib
|
||||
import asyncio
|
||||
import logging
|
||||
import email.utils
|
||||
import xml.etree.ElementTree as etree
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
List,
|
||||
Dict,
|
||||
Any,
|
||||
Optional,
|
||||
Union
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .http_client import HttpClient
|
||||
from .database import MoonrakerDatabase
|
||||
|
||||
|
||||
MOONLIGHT_URL = "https://arksine.github.io/moonlight"
|
||||
UPDATE_CHECK_TIME = 1800.
|
||||
etree.register_namespace("moonlight", MOONLIGHT_URL)
|
||||
|
||||
class Announcements:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.entry_mgr = EntryManager(config)
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
self.update_timer = self.eventloop.register_timer(
|
||||
self._handle_update_timer
|
||||
)
|
||||
self.request_lock = asyncio.Lock()
|
||||
self.dev_mode = config.getboolean("dev_mode", False)
|
||||
self.subscriptions: Dict[str, RssFeed] = {
|
||||
"moonraker": RssFeed("moonraker", self.entry_mgr, self.dev_mode),
|
||||
"klipper": RssFeed("klipper", self.entry_mgr, self.dev_mode)
|
||||
}
|
||||
self.stored_feeds: List[str] = []
|
||||
sub_list: List[str] = config.getlist("subscriptions", [])
|
||||
self.configured_feeds: List[str] = ["moonraker", "klipper"]
|
||||
for sub in sub_list:
|
||||
sub = sub.lower()
|
||||
if sub in self.subscriptions:
|
||||
continue
|
||||
self.configured_feeds.append(sub)
|
||||
self.subscriptions[sub] = RssFeed(
|
||||
sub, self.entry_mgr, self.dev_mode
|
||||
)
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/list", ["GET"],
|
||||
self._list_announcements
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/dismiss", ["POST"],
|
||||
self._handle_dismiss_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/update", ["POST"],
|
||||
self._handle_update_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/feed", ["POST", "DELETE"],
|
||||
self._handle_feed_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/feeds", ["GET"],
|
||||
self._handle_list_feeds
|
||||
)
|
||||
self.server.register_notification(
|
||||
"announcements:dismissed", "announcement_dismissed"
|
||||
)
|
||||
self.server.register_notification(
|
||||
"announcements:entries_updated", "announcement_update"
|
||||
)
|
||||
self.server.register_notification(
|
||||
"announcements:dismiss_wake", "announcement_wake"
|
||||
)
|
||||
|
||||
async def component_init(self) -> None:
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
stored_feeds: List[str] = await db.get_item(
|
||||
"moonraker", "announcements.stored_feeds", []
|
||||
)
|
||||
self.stored_feeds = stored_feeds
|
||||
for name in stored_feeds:
|
||||
if name in self.subscriptions:
|
||||
continue
|
||||
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
|
||||
self.subscriptions[name] = feed
|
||||
async with self.request_lock:
|
||||
await self.entry_mgr.initialize()
|
||||
for sub in self.subscriptions.values():
|
||||
await sub.initialize()
|
||||
self.update_timer.start()
|
||||
|
||||
async def _handle_update_timer(self, eventtime: float) -> float:
|
||||
changed = False
|
||||
entries: List[Dict[str, Any]] = []
|
||||
async with self.request_lock:
|
||||
for sub in self.subscriptions.values():
|
||||
ret = await sub.update_entries()
|
||||
changed |= ret
|
||||
if changed:
|
||||
entries = await self.entry_mgr.list_entries()
|
||||
self.server.send_event(
|
||||
"announcements:entries_updated", {"entries": entries}
|
||||
)
|
||||
return eventtime + UPDATE_CHECK_TIME
|
||||
|
||||
async def _handle_dismiss_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
async with self.request_lock:
|
||||
entry_id: str = web_request.get_str("entry_id")
|
||||
wake_time: Optional[int] = web_request.get_int("wake_time", None)
|
||||
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
|
||||
return {
|
||||
"entry_id": entry_id
|
||||
}
|
||||
|
||||
async def _list_announcements(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
async with self.request_lock:
|
||||
incl_dsm = web_request.get_boolean("include_dismissed", True)
|
||||
entries = await self.entry_mgr.list_entries(incl_dsm)
|
||||
return {
|
||||
"entries": entries,
|
||||
"feeds": list(self.subscriptions.keys())
|
||||
}
|
||||
|
||||
async def _handle_update_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
subs: Optional[Union[str, List[str]]]
|
||||
subs = web_request.get("subscriptions", None)
|
||||
if isinstance(subs, str):
|
||||
subs = [sub.strip() for sub in subs.split(",") if sub.strip()]
|
||||
elif subs is None:
|
||||
subs = list(self.subscriptions.keys())
|
||||
for sub in subs:
|
||||
if sub not in self.subscriptions:
|
||||
raise self.server.error(f"No subscription for {sub}")
|
||||
async with self.request_lock:
|
||||
changed = False
|
||||
for sub in subs:
|
||||
ret = await self.subscriptions[sub].update_entries()
|
||||
changed |= ret
|
||||
entries = await self.entry_mgr.list_entries()
|
||||
if changed:
|
||||
self.eventloop.delay_callback(
|
||||
.05, self.server.send_event,
|
||||
"announcements:entries_updated",
|
||||
{"entries": entries})
|
||||
return {
|
||||
"entries": entries,
|
||||
"modified": changed
|
||||
}
|
||||
|
||||
async def _handle_list_feeds(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {"feeds": list(self.subscriptions.keys())}
|
||||
|
||||
async def _handle_feed_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
name: str = web_request.get("name")
|
||||
name = name.lower()
|
||||
changed: bool = False
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
result = "skipped"
|
||||
if action == "POST":
|
||||
if name not in self.subscriptions:
|
||||
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
|
||||
self.subscriptions[name] = feed
|
||||
await feed.initialize()
|
||||
changed = await feed.update_entries()
|
||||
self.stored_feeds.append(name)
|
||||
db.insert_item(
|
||||
"moonraker", "announcements.stored_feeds", self.stored_feeds
|
||||
)
|
||||
result = "added"
|
||||
elif action == "DELETE":
|
||||
if name not in self.stored_feeds:
|
||||
raise self.server.error(f"Feed '{name}' not stored")
|
||||
if name in self.configured_feeds:
|
||||
raise self.server.error(
|
||||
f"Feed '{name}' exists in the configuration, cannot remove"
|
||||
)
|
||||
self.stored_feeds.remove(name)
|
||||
db.insert_item(
|
||||
"moonraker", "announcements.stored_feeds", self.stored_feeds
|
||||
)
|
||||
if name in self.subscriptions:
|
||||
del self.subscriptions[name]
|
||||
changed = await self.entry_mgr.prune_by_feed(name)
|
||||
logging.info(f"Removed Announcement Feed: {name}")
|
||||
result = "removed"
|
||||
else:
|
||||
raise self.server.error(f"Feed does not exist: {name}")
|
||||
if changed:
|
||||
entries = await self.entry_mgr.list_entries()
|
||||
self.eventloop.delay_callback(
|
||||
.05, self.server.send_event, "announcements:entries_updated",
|
||||
{"entries": entries}
|
||||
)
|
||||
return {
|
||||
"feed": name,
|
||||
"action": result
|
||||
}
|
||||
|
||||
def add_internal_announcement(
|
||||
self, title: str, desc: str, url: str, priority: str, feed: str
|
||||
) -> Dict[str, Any]:
|
||||
date = datetime.datetime.utcnow()
|
||||
entry_id: str = f"{feed}/{date.isoformat(timespec='seconds')}"
|
||||
entry = {
|
||||
"entry_id": entry_id,
|
||||
"url": url,
|
||||
"title": title,
|
||||
"description": desc,
|
||||
"priority": priority,
|
||||
"date": date.timestamp(),
|
||||
"dismissed": False,
|
||||
"date_dismissed": None,
|
||||
"dismiss_wake": None,
|
||||
"source": "internal",
|
||||
"feed": feed
|
||||
}
|
||||
self.entry_mgr.add_entry(entry)
|
||||
return entry
|
||||
|
||||
async def remove_announcement(self, entry_id: str) -> None:
|
||||
ret = await self.entry_mgr.remove_entry(entry_id)
|
||||
if ret is not None:
|
||||
entries = await self.entry_mgr.list_entries()
|
||||
self.server.send_event(
|
||||
"announcements:entries_updated", {"entries": entries}
|
||||
)
|
||||
async def dismiss_announcement(
|
||||
self, entry_id, wake_time: Optional[int] = None
|
||||
) -> None:
|
||||
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
|
||||
|
||||
async def get_announcements(
|
||||
self, include_dismissed: bool = False
|
||||
) -> List[Dict[str, Any]]:
|
||||
return await self.entry_mgr.list_entries(include_dismissed)
|
||||
|
||||
def close(self):
|
||||
self.entry_mgr.close()
|
||||
|
||||
class EntryManager:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
database: MoonrakerDatabase
|
||||
database = self.server.lookup_component("database")
|
||||
database.register_local_namespace("announcements")
|
||||
self.announce_db = database.wrap_namespace("announcements")
|
||||
self.entry_id_map: Dict[str, str] = {}
|
||||
self.next_key = 0
|
||||
self.dismiss_handles: Dict[str, asyncio.TimerHandle] = {}
|
||||
|
||||
async def initialize(self) -> None:
|
||||
last_key = ""
|
||||
eventloop = self.server.get_event_loop()
|
||||
curtime = datetime.datetime.utcnow().timestamp()
|
||||
for key, entry in await self.announce_db.items():
|
||||
last_key = key
|
||||
aid = entry["entry_id"]
|
||||
self.entry_id_map[aid] = key
|
||||
if entry["dismissed"]:
|
||||
wake_time: Optional[float] = entry.get("dismiss_wake")
|
||||
if wake_time is not None:
|
||||
time_diff = wake_time - curtime
|
||||
if time_diff - 10. < 0.:
|
||||
# announcement is near or past wake time
|
||||
entry["dismissed"] = False
|
||||
entry["date_dismissed"] = None
|
||||
entry["dismiss_wake"] = None
|
||||
self.announce_db[key] = entry
|
||||
else:
|
||||
self.dismiss_handles[key] = eventloop.delay_callback(
|
||||
time_diff, self._wake_dismissed, key
|
||||
)
|
||||
if last_key:
|
||||
self.next_key = int(last_key, 16) + 1
|
||||
|
||||
async def list_entries(
|
||||
self, include_dismissed: bool = True
|
||||
) -> List[Dict[str, Any]]:
|
||||
vals: List[Dict[str, Any]] = await self.announce_db.values()
|
||||
vals = sorted(vals, key=lambda x: x["date"], reverse=True)
|
||||
if include_dismissed:
|
||||
return vals
|
||||
return [val for val in vals if not val["dismissed"]]
|
||||
|
||||
def has_entry(self, entry_id: str) -> bool:
|
||||
return entry_id in self.entry_id_map
|
||||
|
||||
def add_entry(self, entry: Dict[str, Any]) -> Awaitable[None]:
|
||||
aid = entry["entry_id"]
|
||||
key = f"{self.next_key:06X}"
|
||||
self.next_key += 1
|
||||
self.entry_id_map[aid] = key
|
||||
return self.announce_db.insert(key, entry)
|
||||
|
||||
def remove_entry(self, entry_id: str) -> Awaitable[Any]:
|
||||
key = self.entry_id_map.pop(entry_id, None)
|
||||
if key is None:
|
||||
raise self.server.error(f"No key matching entry id: {entry_id}")
|
||||
return self.announce_db.pop(key, None)
|
||||
|
||||
async def dismiss_entry(
|
||||
self, entry_id: str, wake_time: Optional[int] = None
|
||||
) -> None:
|
||||
key = self.entry_id_map.get(entry_id)
|
||||
if key is None:
|
||||
raise self.server.error(f"No key matching entry id: {entry_id}")
|
||||
entry = await self.announce_db[key]
|
||||
is_dismissed = entry["dismissed"]
|
||||
if is_dismissed:
|
||||
return
|
||||
entry["dismissed"] = True
|
||||
eventloop = self.server.get_event_loop()
|
||||
curtime = datetime.datetime.utcnow().timestamp()
|
||||
entry["date_dismissed"] = curtime
|
||||
if wake_time is not None:
|
||||
entry["dismiss_wake"] = curtime + wake_time
|
||||
self.dismiss_handles[key] = eventloop.delay_callback(
|
||||
wake_time, self._wake_dismissed, key
|
||||
)
|
||||
self.announce_db[key] = entry
|
||||
eventloop.delay_callback(
|
||||
.05, self.server.send_event, "announcements:dismissed",
|
||||
{"entry_id": entry_id}
|
||||
)
|
||||
|
||||
async def _wake_dismissed(self, key: str) -> None:
|
||||
self.dismiss_handles.pop(key, None)
|
||||
entry = await self.announce_db.get(key, None)
|
||||
if entry is None:
|
||||
return
|
||||
if not entry["dismissed"]:
|
||||
return
|
||||
entry["dismissed"] = False
|
||||
entry["date_dismissed"] = None
|
||||
entry["dismiss_wake"] = None
|
||||
self.announce_db[key] = entry
|
||||
self.server.send_event(
|
||||
"announcements:dismiss_wake", {"entry_id": entry["entry_id"]}
|
||||
)
|
||||
|
||||
def prune_by_prefix(self, prefix: str, valid_ids: List[str]) -> bool:
|
||||
del_keys: List[str] = []
|
||||
for entry_id in list(self.entry_id_map.keys()):
|
||||
if not entry_id.startswith(prefix) or entry_id in valid_ids:
|
||||
continue
|
||||
# Entry is no longer valid and should be removed
|
||||
key = self.entry_id_map.pop(entry_id, None)
|
||||
if key is not None:
|
||||
del_keys.append(key)
|
||||
if del_keys:
|
||||
self.announce_db.delete_batch(del_keys)
|
||||
return True
|
||||
return False
|
||||
|
||||
async def prune_by_feed(self, feed: str) -> bool:
|
||||
entries = await self.list_entries()
|
||||
del_keys: List[str] = []
|
||||
for entry in entries:
|
||||
if entry["feed"].lower() == feed:
|
||||
key = self.entry_id_map.pop(entry["entry_id"], None)
|
||||
if key is not None:
|
||||
del_keys.append(key)
|
||||
if del_keys:
|
||||
self.announce_db.delete_batch(del_keys)
|
||||
return True
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
for handle in self.dismiss_handles.values():
|
||||
handle.cancel()
|
||||
|
||||
class RssFeed:
|
||||
def __init__(
|
||||
self, name: str, entry_mgr: EntryManager, dev_mode: bool
|
||||
) -> None:
|
||||
self.server = entry_mgr.server
|
||||
self.name = name
|
||||
self.entry_mgr = entry_mgr
|
||||
self.client: HttpClient = self.server.lookup_component("http_client")
|
||||
self.database: MoonrakerDatabase
|
||||
self.database = self.server.lookup_component("database")
|
||||
self.xml_file = f"{self.name}.xml"
|
||||
self.asset_url = f"{MOONLIGHT_URL}/assets/{self.xml_file}"
|
||||
self.last_modified: int = 0
|
||||
self.etag: Optional[str] = None
|
||||
self.dev_xml_path: Optional[pathlib.Path] = None
|
||||
if dev_mode:
|
||||
res_dir = pathlib.Path(__file__).parent.parent.parent.resolve()
|
||||
res_path = res_dir.joinpath(".devel/announcement_xml")
|
||||
self.dev_xml_path = res_path.joinpath(self.xml_file)
|
||||
|
||||
async def initialize(self) -> None:
|
||||
self.etag = await self.database.get_item(
|
||||
"moonraker", f"announcements.{self.name}.etag", None
|
||||
)
|
||||
|
||||
async def update_entries(self) -> bool:
|
||||
if self.dev_xml_path is None:
|
||||
xml_data = await self._fetch_moonlight()
|
||||
else:
|
||||
xml_data = await self._fetch_local_folder()
|
||||
if not xml_data:
|
||||
return False
|
||||
return self._parse_xml(xml_data)
|
||||
|
||||
async def _fetch_moonlight(self) -> str:
|
||||
headers = {"Accept": "application/xml"}
|
||||
if self.etag is not None:
|
||||
headers["If-None-Match"] = self.etag
|
||||
resp = await self.client.get(
|
||||
self.asset_url, headers, attempts=5,
|
||||
retry_pause_time=.5, enable_cache=False,
|
||||
)
|
||||
if resp.has_error():
|
||||
logging.info(
|
||||
f"Failed to update subscription '{self.name}': {resp.error}"
|
||||
)
|
||||
return ""
|
||||
if resp.status_code == 304:
|
||||
logging.debug(f"Content at {self.xml_file} not modified")
|
||||
return ""
|
||||
# update etag
|
||||
self.etag = resp.etag
|
||||
try:
|
||||
if self.etag is not None:
|
||||
self.database.insert_item(
|
||||
"moonraker", f"announcements.{self.name}.etag", resp.etag
|
||||
)
|
||||
else:
|
||||
self.database.delete_item(
|
||||
"moonraker", f"announcements.{self.name}.etag",
|
||||
)
|
||||
except self.server.error:
|
||||
pass
|
||||
return resp.text
|
||||
|
||||
async def _fetch_local_folder(self) -> str:
|
||||
if self.dev_xml_path is None:
|
||||
return ""
|
||||
if not self.dev_xml_path.is_file():
|
||||
logging.info(f"No file at path {self.dev_xml_path}")
|
||||
return ""
|
||||
mtime = self.dev_xml_path.stat().st_mtime_ns
|
||||
if mtime <= self.last_modified:
|
||||
logging.debug(f"Content at {self.xml_file} not modified")
|
||||
return ""
|
||||
try:
|
||||
eventloop = self.server.get_event_loop()
|
||||
xml_data = await eventloop.run_in_thread(
|
||||
self.dev_xml_path.read_text)
|
||||
except Exception:
|
||||
logging.exception(f"Unable read xml file {self.dev_xml_path}")
|
||||
return ""
|
||||
self.last_modified = mtime
|
||||
return xml_data
|
||||
|
||||
def _parse_xml(self, xml_data: str) -> bool:
|
||||
root = etree.fromstring(xml_data)
|
||||
channel = root.find("channel")
|
||||
if channel is None:
|
||||
root_str = etree.tostring(root, encoding="unicode")
|
||||
logging.debug(f"Feed {self.name}: no channel found\n{root_str}")
|
||||
return False
|
||||
# extract prefix
|
||||
prefix = channel.findtext("title", "").lower()
|
||||
if not prefix:
|
||||
logging.info(f"Feed {self.name}: No prefix found")
|
||||
items = channel.findall("item")
|
||||
valid_ids: List[str] = []
|
||||
changed: bool = False
|
||||
for item in items:
|
||||
guid = item.findtext("guid")
|
||||
if guid is None:
|
||||
item_str = etree.tostring(item, encoding="unicode")
|
||||
logging.debug(f"Feed {self.name}: Invalid Item\n{item_str}")
|
||||
continue
|
||||
if not prefix:
|
||||
# fall back to first guid prefix
|
||||
prefix = "/".join(guid.split("/")[:2])
|
||||
elif not guid.startswith(prefix):
|
||||
logging.debug(
|
||||
f"Feed {self.name}: Guid {guid} is not "
|
||||
f"prefixed with {prefix}")
|
||||
valid_ids.append(guid)
|
||||
if self.entry_mgr.has_entry(guid):
|
||||
continue
|
||||
try:
|
||||
rfc_date = item.findtext("pubDate", "")
|
||||
dt = email.utils.parsedate_to_datetime(rfc_date)
|
||||
except Exception:
|
||||
dt = datetime.datetime.utcnow()
|
||||
entry: Dict[str, Any] = {
|
||||
"entry_id": guid,
|
||||
"url": item.findtext("link"),
|
||||
"title": item.findtext("title"),
|
||||
"description": item.findtext("description"),
|
||||
"priority": item.findtext("category"),
|
||||
"date": dt.timestamp(),
|
||||
"dismissed": False,
|
||||
"date_dismissed": None,
|
||||
"dismiss_wake": None,
|
||||
"source": "moonlight",
|
||||
"feed": self.name
|
||||
}
|
||||
changed = True
|
||||
self.entry_mgr.add_entry(entry)
|
||||
logging.debug(f"Feed {self.name}: found entries {valid_ids}")
|
||||
if prefix:
|
||||
pruned = self.entry_mgr.prune_by_prefix(prefix, valid_ids)
|
||||
changed = changed or pruned
|
||||
return changed
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Announcements:
|
||||
return Announcements(config)
|
||||
@@ -0,0 +1,874 @@
|
||||
# API Key Based Authorization
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import base64
|
||||
import uuid
|
||||
import hashlib
|
||||
import secrets
|
||||
import os
|
||||
import time
|
||||
import datetime
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
from tornado.web import HTTPError
|
||||
from libnacl.sign import Signer, Verifier
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Set,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest, WebsocketManager
|
||||
from tornado.httputil import HTTPServerRequest
|
||||
from tornado.web import RequestHandler
|
||||
from .database import MoonrakerDatabase as DBComp
|
||||
from .ldap import MoonrakerLDAP
|
||||
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
||||
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
|
||||
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], asyncio.Handle]
|
||||
|
||||
# Helpers for base64url encoding and decoding
|
||||
def base64url_encode(data: bytes) -> bytes:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
||||
|
||||
def base64url_decode(data: str) -> bytes:
|
||||
pad_cnt = len(data) % 4
|
||||
if pad_cnt:
|
||||
data += "=" * (4 - pad_cnt)
|
||||
return base64.urlsafe_b64decode(data)
|
||||
|
||||
|
||||
ONESHOT_TIMEOUT = 5
|
||||
TRUSTED_CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300.
|
||||
|
||||
AUTH_SOURCES = ["moonraker", "ldap"]
|
||||
HASH_ITER = 100000
|
||||
API_USER = "_API_KEY_USER_"
|
||||
TRUSTED_USER = "_TRUSTED_USER_"
|
||||
RESERVED_USERS = [API_USER, TRUSTED_USER]
|
||||
JWT_EXP_TIME = datetime.timedelta(hours=1)
|
||||
JWT_HEADER = {
|
||||
'alg': "EdDSA",
|
||||
'typ': "JWT"
|
||||
}
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.login_timeout = config.getint('login_timeout', 90)
|
||||
self.force_logins = config.getboolean('force_logins', False)
|
||||
self.default_source = config.get('default_source', "moonraker").lower()
|
||||
self.enable_api_key = config.getboolean('enable_api_key', True)
|
||||
self.max_logins = config.getint("max_login_attempts", None, above=0)
|
||||
self.failed_logins: Dict[IPAddr, int] = {}
|
||||
if self.default_source not in AUTH_SOURCES:
|
||||
raise config.error(
|
||||
"[authorization]: option 'default_source' - Invalid "
|
||||
f"value '{self.default_source}'"
|
||||
)
|
||||
self.ldap: Optional[MoonrakerLDAP] = None
|
||||
if config.has_section("ldap"):
|
||||
self.ldap = self.server.load_component(config, "ldap", None)
|
||||
if self.default_source == "ldap" and self.ldap is None:
|
||||
self.server.add_warning(
|
||||
"[authorization]: Option 'default_source' set to 'ldap',"
|
||||
" however [ldap] section failed to load or not configured"
|
||||
)
|
||||
database: DBComp = self.server.lookup_component('database')
|
||||
database.register_local_namespace('authorized_users', forbidden=True)
|
||||
self.user_db = database.wrap_namespace('authorized_users')
|
||||
self.users: Dict[str, Dict[str, Any]] = self.user_db.as_dict()
|
||||
api_user: Optional[Dict[str, Any]] = self.users.get(API_USER, None)
|
||||
if api_user is None:
|
||||
self.api_key = uuid.uuid4().hex
|
||||
self.users[API_USER] = {
|
||||
'username': API_USER,
|
||||
'api_key': self.api_key,
|
||||
'created_on': time.time()
|
||||
}
|
||||
else:
|
||||
self.api_key = api_user['api_key']
|
||||
hi = self.server.get_host_info()
|
||||
self.issuer = f"http://{hi['hostname']}:{hi['port']}"
|
||||
self.public_jwks: Dict[str, Dict[str, Any]] = {}
|
||||
for username, user_info in list(self.users.items()):
|
||||
if username == API_USER:
|
||||
# Validate the API User
|
||||
for item in ["username", "api_key", "created_on"]:
|
||||
if item not in user_info:
|
||||
self.users[API_USER] = {
|
||||
'username': API_USER,
|
||||
'api_key': self.api_key,
|
||||
'created_on': time.time()
|
||||
}
|
||||
break
|
||||
continue
|
||||
else:
|
||||
# validate created users
|
||||
valid = True
|
||||
for item in ["username", "password", "salt", "created_on"]:
|
||||
if item not in user_info:
|
||||
logging.info(
|
||||
f"Authorization: User {username} does not "
|
||||
f"contain field {item}, removing")
|
||||
del self.users[username]
|
||||
valid = False
|
||||
break
|
||||
if not valid:
|
||||
continue
|
||||
# generate jwks for valid users
|
||||
if 'jwt_secret' in user_info:
|
||||
try:
|
||||
priv_key = self._load_private_key(user_info['jwt_secret'])
|
||||
jwk_id = user_info['jwk_id']
|
||||
except (self.server.error, KeyError):
|
||||
logging.info("Invalid key found for user, removing")
|
||||
user_info.pop('jwt_secret', None)
|
||||
user_info.pop('jwk_id', None)
|
||||
self.users[username] = user_info
|
||||
continue
|
||||
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
|
||||
# sync user changes to the database
|
||||
self.user_db.sync(self.users)
|
||||
self.trusted_users: Dict[IPAddr, Any] = {}
|
||||
self.oneshot_tokens: Dict[str, OneshotToken] = {}
|
||||
self.permitted_paths: Set[str] = set()
|
||||
|
||||
# Get allowed cors domains
|
||||
self.cors_domains: List[str] = []
|
||||
for domain in config.getlist('cors_domains', []):
|
||||
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.")
|
||||
if domain.endswith("/"):
|
||||
self.server.add_warning(
|
||||
f"[authorization]: Invalid domain '{domain}' in option "
|
||||
"'cors_domains'. Domain's cannot contain a trailing "
|
||||
"slash.")
|
||||
else:
|
||||
self.cors_domains.append(
|
||||
domain.replace(".", "\\.").replace("*", ".*"))
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips: List[IPAddr] = []
|
||||
self.trusted_ranges: List[IPNetwork] = []
|
||||
self.trusted_domains: List[str] = []
|
||||
for val in config.getlist('trusted_clients', []):
|
||||
# Check IP address
|
||||
try:
|
||||
tc = ipaddress.ip_address(val)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.trusted_ips.append(tc)
|
||||
continue
|
||||
# Check ip network
|
||||
try:
|
||||
tn = ipaddress.ip_network(val)
|
||||
except ValueError as e:
|
||||
if "has host bits set" in str(e):
|
||||
self.server.add_warning(
|
||||
f"[authorization]: Invalid CIDR expression '{val}' "
|
||||
"in option 'trusted_clients'")
|
||||
continue
|
||||
pass
|
||||
else:
|
||||
self.trusted_ranges.append(tn)
|
||||
continue
|
||||
# Check hostname
|
||||
match = re.match(r"([a-z0-9]+(-[a-z0-9]+)*\.?)+[a-z]{2,}$", val)
|
||||
if match is not None:
|
||||
self.trusted_domains.append(val.lower())
|
||||
else:
|
||||
self.server.add_warning(
|
||||
f"[authorization]: Invalid domain name '{val}' "
|
||||
"in option 'trusted_clients'")
|
||||
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges] +
|
||||
self.trusted_domains)
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
eventloop = self.server.get_event_loop()
|
||||
self.prune_timer = eventloop.register_timer(
|
||||
self._prune_conn_handler)
|
||||
|
||||
# Register Authorization Endpoints
|
||||
self.permitted_paths.add("/server/redirect")
|
||||
self.permitted_paths.add("/access/login")
|
||||
self.permitted_paths.add("/access/refresh_jwt")
|
||||
self.permitted_paths.add("/access/info")
|
||||
self.server.register_endpoint(
|
||||
"/access/login", ['POST'], self._handle_login,
|
||||
transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/logout", ['POST'], self._handle_logout,
|
||||
transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
|
||||
transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/user", ['GET', 'POST', 'DELETE'],
|
||||
self._handle_user_request, transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/users/list", ['GET'], self._handle_list_request,
|
||||
transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/user/password", ['POST'], self._handle_password_reset,
|
||||
transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/api_key", ['GET', 'POST'],
|
||||
self._handle_apikey_request, transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/oneshot_token", ['GET'],
|
||||
self._handle_oneshot_request, transports=['http', 'websocket'])
|
||||
self.server.register_endpoint(
|
||||
"/access/info", ['GET'],
|
||||
self._handle_info_request, transports=['http', 'websocket'])
|
||||
wsm: WebsocketManager = self.server.lookup_component("websockets")
|
||||
wsm.register_notification("authorization:user_created")
|
||||
wsm.register_notification(
|
||||
"authorization:user_deleted", event_type="logout"
|
||||
)
|
||||
wsm.register_notification(
|
||||
"authorization:user_logged_out", event_type="logout"
|
||||
)
|
||||
|
||||
def register_permited_path(self, path: str) -> None:
|
||||
self.permitted_paths.add(path)
|
||||
|
||||
def is_path_permitted(self, path: str) -> bool:
|
||||
return path in self.permitted_paths
|
||||
|
||||
def _sync_user(self, username: str) -> None:
|
||||
self.user_db[username] = self.users[username]
|
||||
|
||||
async def component_init(self) -> None:
|
||||
self.prune_timer.start(delay=PRUNE_CHECK_TIME)
|
||||
|
||||
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
|
||||
action = web_request.get_action()
|
||||
if action.upper() == 'POST':
|
||||
self.api_key = uuid.uuid4().hex
|
||||
self.users[API_USER]['api_key'] = self.api_key
|
||||
self._sync_user(API_USER)
|
||||
return self.api_key
|
||||
|
||||
async def _handle_oneshot_request(self, web_request: WebRequest) -> str:
|
||||
ip = web_request.get_ip_address()
|
||||
assert ip is not None
|
||||
user_info = web_request.get_current_user()
|
||||
return self.get_oneshot_token(ip, user_info)
|
||||
|
||||
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
|
||||
ip = web_request.get_ip_address()
|
||||
if ip is not None and self.check_logins_maxed(ip):
|
||||
raise HTTPError(
|
||||
401, "Unauthorized, Maximum Login Attempts Reached"
|
||||
)
|
||||
try:
|
||||
ret = await self._login_jwt_user(web_request)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
if ip is not None:
|
||||
failed = self.failed_logins.get(ip, 0)
|
||||
self.failed_logins[ip] = failed + 1
|
||||
raise
|
||||
if ip is not None:
|
||||
self.failed_logins.pop(ip, None)
|
||||
return ret
|
||||
|
||||
async def _handle_logout(self, web_request: WebRequest) -> Dict[str, str]:
|
||||
user_info = web_request.get_current_user()
|
||||
if user_info is None:
|
||||
raise self.server.error("No user logged in")
|
||||
username: str = user_info['username']
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid log out request for user {username}")
|
||||
self.users[username].pop("jwt_secret", None)
|
||||
jwk_id: str = self.users[username].pop("jwk_id", None)
|
||||
self._sync_user(username)
|
||||
self.public_jwks.pop(jwk_id, None)
|
||||
eventloop = self.server.get_event_loop()
|
||||
eventloop.delay_callback(
|
||||
.005, self.server.send_event, "authorization:user_logged_out",
|
||||
{'username': username}
|
||||
)
|
||||
return {
|
||||
"username": username,
|
||||
"action": "user_logged_out"
|
||||
}
|
||||
|
||||
async def _handle_info_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
sources = ["moonraker"]
|
||||
if self.ldap is not None:
|
||||
sources.append("ldap")
|
||||
return {
|
||||
"default_source": self.default_source,
|
||||
"available_sources": sources
|
||||
}
|
||||
|
||||
async def _handle_refresh_jwt(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
refresh_token: str = web_request.get_str('refresh_token')
|
||||
try:
|
||||
user_info = self.decode_jwt(refresh_token, token_type="refresh")
|
||||
except Exception:
|
||||
raise self.server.error("Invalid Refresh Token", 401)
|
||||
username: str = user_info['username']
|
||||
if 'jwt_secret' not in user_info or "jwk_id" not in user_info:
|
||||
raise self.server.error("User not logged in", 401)
|
||||
private_key = self._load_private_key(user_info['jwt_secret'])
|
||||
jwk_id: str = user_info['jwk_id']
|
||||
token = self._generate_jwt(username, jwk_id, private_key)
|
||||
return {
|
||||
'username': username,
|
||||
'token': token,
|
||||
'source': user_info.get("source", "moonraker"),
|
||||
'action': 'user_jwt_refresh'
|
||||
}
|
||||
|
||||
async def _handle_user_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
if action == "GET":
|
||||
user = web_request.get_current_user()
|
||||
if user is None:
|
||||
return {
|
||||
'username': None,
|
||||
'source': None,
|
||||
'created_on': None,
|
||||
}
|
||||
else:
|
||||
return {
|
||||
'username': user['username'],
|
||||
'source': user.get("source", "moonraker"),
|
||||
'created_on': user.get('created_on')
|
||||
}
|
||||
elif action == "POST":
|
||||
# Create User
|
||||
return await self._login_jwt_user(web_request, create=True)
|
||||
elif action == "DELETE":
|
||||
# Delete User
|
||||
return self._delete_jwt_user(web_request)
|
||||
raise self.server.error("Invalid Request Method")
|
||||
|
||||
async def _handle_list_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
user_list = []
|
||||
for user in self.users.values():
|
||||
if user['username'] == API_USER:
|
||||
continue
|
||||
user_list.append({
|
||||
'username': user['username'],
|
||||
'source': user.get("source", "moonraker"),
|
||||
'created_on': user['created_on']
|
||||
})
|
||||
return {
|
||||
'users': user_list
|
||||
}
|
||||
|
||||
async def _handle_password_reset(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
password: str = web_request.get_str('password')
|
||||
new_pass: str = web_request.get_str('new_password')
|
||||
user_info = web_request.get_current_user()
|
||||
if user_info is None:
|
||||
raise self.server.error("No Current User")
|
||||
username = user_info['username']
|
||||
if user_info.get("source", "moonraker") == "ldap":
|
||||
raise self.server.error(
|
||||
f"Can´t Reset password for ldap user {username}")
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Reset Request for user {username}")
|
||||
salt = bytes.fromhex(user_info['salt'])
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
if hashed_pass != user_info['password']:
|
||||
raise self.server.error("Invalid Password")
|
||||
new_hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
|
||||
self.users[username]['password'] = new_hashed_pass
|
||||
self._sync_user(username)
|
||||
return {
|
||||
'username': username,
|
||||
'action': "user_password_reset"
|
||||
}
|
||||
|
||||
async def _login_jwt_user(
|
||||
self, web_request: WebRequest, create: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
username: str = web_request.get_str('username')
|
||||
password: str = web_request.get_str('password')
|
||||
source: str = web_request.get_str(
|
||||
'source', self.default_source
|
||||
).lower()
|
||||
if source not in AUTH_SOURCES:
|
||||
raise self.server.error(f"Invalid 'source': {source}")
|
||||
user_info: Dict[str, Any]
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Request for user {username}")
|
||||
if source == "ldap":
|
||||
if create:
|
||||
raise self.server.error("Cannot Create LDAP User")
|
||||
if self.ldap is None:
|
||||
raise self.server.error(
|
||||
"LDAP authentication not available", 401
|
||||
)
|
||||
await self.ldap.authenticate_ldap_user(username, password)
|
||||
if username not in self.users:
|
||||
create = True
|
||||
if create:
|
||||
if username in self.users:
|
||||
raise self.server.error(f"User {username} already exists")
|
||||
salt = secrets.token_bytes(32)
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
user_info = {
|
||||
'username': username,
|
||||
'password': hashed_pass,
|
||||
'salt': salt.hex(),
|
||||
'source': source,
|
||||
'created_on': time.time()
|
||||
}
|
||||
self.users[username] = user_info
|
||||
self._sync_user(username)
|
||||
action = "user_created"
|
||||
if source == "ldap":
|
||||
# Dont notify user created
|
||||
action = "user_logged_in"
|
||||
create = False
|
||||
else:
|
||||
if username not in self.users:
|
||||
raise self.server.error(f"Unregistered User: {username}")
|
||||
user_info = self.users[username]
|
||||
auth_src = user_info.get("source", "moonraker")
|
||||
if auth_src != source:
|
||||
raise self.server.error(
|
||||
f"Moonraker cannot authenticate user '{username}', must "
|
||||
f"specify source '{auth_src}'", 401
|
||||
)
|
||||
salt = bytes.fromhex(user_info['salt'])
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
action = "user_logged_in"
|
||||
if hashed_pass != user_info['password']:
|
||||
raise self.server.error("Invalid Password")
|
||||
jwt_secret_hex: Optional[str] = user_info.get('jwt_secret', None)
|
||||
if jwt_secret_hex is None:
|
||||
private_key = Signer()
|
||||
jwk_id = base64url_encode(secrets.token_bytes()).decode()
|
||||
user_info['jwt_secret'] = private_key.hex_seed().decode()
|
||||
user_info['jwk_id'] = jwk_id
|
||||
self.users[username] = user_info
|
||||
self._sync_user(username)
|
||||
self.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
|
||||
else:
|
||||
private_key = self._load_private_key(jwt_secret_hex)
|
||||
jwk_id = user_info['jwk_id']
|
||||
token = self._generate_jwt(username, jwk_id, private_key)
|
||||
refresh_token = self._generate_jwt(
|
||||
username, jwk_id, private_key, token_type="refresh",
|
||||
exp_time=datetime.timedelta(days=self.login_timeout))
|
||||
conn = web_request.get_client_connection()
|
||||
if create:
|
||||
event_loop = self.server.get_event_loop()
|
||||
event_loop.delay_callback(
|
||||
.005, self.server.send_event,
|
||||
"authorization:user_created",
|
||||
{'username': username})
|
||||
elif conn is not None:
|
||||
conn.user_info = user_info
|
||||
return {
|
||||
'username': username,
|
||||
'token': token,
|
||||
'source': user_info.get("source", "moonraker"),
|
||||
'refresh_token': refresh_token,
|
||||
'action': action
|
||||
}
|
||||
|
||||
def _delete_jwt_user(self, web_request: WebRequest) -> Dict[str, str]:
|
||||
username: str = web_request.get_str('username')
|
||||
current_user = web_request.get_current_user()
|
||||
if current_user is not None:
|
||||
curname = current_user.get('username', None)
|
||||
if curname is not None and curname == username:
|
||||
raise self.server.error(
|
||||
f"Cannot delete logged in user {curname}")
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Request for reserved user {username}")
|
||||
user_info: Optional[Dict[str, Any]] = self.users.get(username)
|
||||
if user_info is None:
|
||||
raise self.server.error(f"No registered user: {username}")
|
||||
if 'jwk_id' in user_info:
|
||||
self.public_jwks.pop(user_info['jwk_id'], None)
|
||||
del self.users[username]
|
||||
del self.user_db[username]
|
||||
event_loop = self.server.get_event_loop()
|
||||
event_loop.delay_callback(
|
||||
.005, self.server.send_event,
|
||||
"authorization:user_deleted",
|
||||
{'username': username})
|
||||
return {
|
||||
"username": username,
|
||||
"action": "user_deleted"
|
||||
}
|
||||
|
||||
def _generate_jwt(self,
|
||||
username: str,
|
||||
jwk_id: str,
|
||||
private_key: Signer,
|
||||
token_type: str = "access",
|
||||
exp_time: datetime.timedelta = JWT_EXP_TIME
|
||||
) -> str:
|
||||
curtime = int(time.time())
|
||||
payload = {
|
||||
'iss': self.issuer,
|
||||
'aud': "Moonraker",
|
||||
'iat': curtime,
|
||||
'exp': curtime + int(exp_time.total_seconds()),
|
||||
'username': username,
|
||||
'token_type': token_type
|
||||
}
|
||||
header = {'kid': jwk_id}
|
||||
header.update(JWT_HEADER)
|
||||
jwt_header = base64url_encode(json.dumps(header).encode())
|
||||
jwt_payload = base64url_encode(json.dumps(payload).encode())
|
||||
jwt_msg = b".".join([jwt_header, jwt_payload])
|
||||
sig = private_key.signature(jwt_msg)
|
||||
jwt_sig = base64url_encode(sig)
|
||||
return b".".join([jwt_msg, jwt_sig]).decode()
|
||||
|
||||
def decode_jwt(
|
||||
self, token: str, token_type: str = "access"
|
||||
) -> Dict[str, Any]:
|
||||
message, sig = token.rsplit('.', maxsplit=1)
|
||||
enc_header, enc_payload = message.split('.')
|
||||
header: Dict[str, Any] = json.loads(base64url_decode(enc_header))
|
||||
sig_bytes = base64url_decode(sig)
|
||||
|
||||
# verify header
|
||||
if header.get('typ') != "JWT" or header.get('alg') != "EdDSA":
|
||||
raise self.server.error("Invalid JWT header")
|
||||
jwk_id = header.get('kid')
|
||||
if jwk_id not in self.public_jwks:
|
||||
raise self.server.error("Invalid key ID")
|
||||
|
||||
# validate signature
|
||||
public_key = self._public_key_from_jwk(self.public_jwks[jwk_id])
|
||||
public_key.verify(sig_bytes + message.encode())
|
||||
|
||||
# validate claims
|
||||
payload: Dict[str, Any] = json.loads(base64url_decode(enc_payload))
|
||||
if payload['token_type'] != token_type:
|
||||
raise self.server.error(
|
||||
f"JWT Token type mismatch: Expected {token_type}, "
|
||||
f"Recd: {payload['token_type']}", 401)
|
||||
if payload['iss'] != self.issuer:
|
||||
raise self.server.error("Invalid JWT Issuer", 401)
|
||||
if payload['aud'] != "Moonraker":
|
||||
raise self.server.error("Invalid JWT Audience", 401)
|
||||
if payload['exp'] < int(time.time()):
|
||||
raise self.server.error("JWT Expired", 401)
|
||||
|
||||
# get user
|
||||
user_info: Optional[Dict[str, Any]] = self.users.get(
|
||||
payload.get('username', ""), None)
|
||||
if user_info is None:
|
||||
raise self.server.error("Unknown user", 401)
|
||||
return user_info
|
||||
|
||||
def validate_jwt(self, token: str) -> Dict[str, Any]:
|
||||
try:
|
||||
user_info = self.decode_jwt(token)
|
||||
except Exception as e:
|
||||
if isinstance(e, self.server.error):
|
||||
raise
|
||||
raise self.server.error(
|
||||
f"Failed to decode JWT: {e}", 401
|
||||
) from e
|
||||
return user_info
|
||||
|
||||
def validate_api_key(self, api_key: str) -> Dict[str, Any]:
|
||||
if not self.enable_api_key:
|
||||
raise self.server.error("API Key authentication is disabled", 401)
|
||||
if api_key and api_key == self.api_key:
|
||||
return self.users[API_USER]
|
||||
raise self.server.error("Invalid API Key", 401)
|
||||
|
||||
def _load_private_key(self, secret: str) -> Signer:
|
||||
try:
|
||||
key = Signer(bytes.fromhex(secret))
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
"Error decoding private key, user data may"
|
||||
" be corrupt", 500) from None
|
||||
return key
|
||||
|
||||
def _generate_public_jwk(self, private_key: Signer) -> Dict[str, Any]:
|
||||
public_key = private_key.vk
|
||||
return {
|
||||
'x': base64url_encode(public_key).decode(),
|
||||
'kty': "OKP",
|
||||
'crv': "Ed25519",
|
||||
'use': "sig"
|
||||
}
|
||||
|
||||
def _public_key_from_jwk(self, jwk: Dict[str, Any]) -> Verifier:
|
||||
if jwk.get('kty') != "OKP":
|
||||
raise self.server.error("Not an Octet Key Pair")
|
||||
if jwk.get('crv') != "Ed25519":
|
||||
raise self.server.error("Invalid Curve")
|
||||
if 'x' not in jwk:
|
||||
raise self.server.error("No 'x' argument in jwk")
|
||||
key = base64url_decode(jwk['x'])
|
||||
return Verifier(key.hex().encode())
|
||||
|
||||
def _prune_conn_handler(self, eventtime: float) -> float:
|
||||
cur_time = time.time()
|
||||
for ip, user_info in list(self.trusted_users.items()):
|
||||
exp_time: float = user_info['expires_at']
|
||||
if cur_time >= exp_time:
|
||||
self.trusted_users.pop(ip, None)
|
||||
logging.info(
|
||||
f"Trusted Connection Expired, IP: {ip}")
|
||||
return eventtime + PRUNE_CHECK_TIME
|
||||
|
||||
def _oneshot_token_expire_handler(self, token):
|
||||
self.oneshot_tokens.pop(token, None)
|
||||
|
||||
def get_oneshot_token(self,
|
||||
ip_addr: IPAddr,
|
||||
user: Optional[Dict[str, Any]]
|
||||
) -> str:
|
||||
token = base64.b32encode(os.urandom(20)).decode()
|
||||
event_loop = self.server.get_event_loop()
|
||||
hdl = event_loop.delay_callback(
|
||||
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
|
||||
self.oneshot_tokens[token] = (ip_addr, user, hdl)
|
||||
return token
|
||||
|
||||
def _check_json_web_token(self,
|
||||
request: HTTPServerRequest
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
auth_token: Optional[str] = request.headers.get("Authorization")
|
||||
if auth_token is None:
|
||||
auth_token = request.headers.get("X-Access-Token")
|
||||
if auth_token is None:
|
||||
qtoken = request.query_arguments.get('access_token', None)
|
||||
if qtoken is not None:
|
||||
auth_token = qtoken[-1].decode()
|
||||
elif auth_token.startswith("Bearer "):
|
||||
auth_token = auth_token[7:]
|
||||
else:
|
||||
return None
|
||||
if auth_token:
|
||||
try:
|
||||
return self.decode_jwt(auth_token)
|
||||
except Exception:
|
||||
logging.exception(f"JWT Decode Error {auth_token}")
|
||||
raise HTTPError(401, "JWT Decode Error")
|
||||
return None
|
||||
|
||||
def _check_authorized_ip(self, ip: IPAddr) -> bool:
|
||||
if ip in self.trusted_ips:
|
||||
return True
|
||||
for rng in self.trusted_ranges:
|
||||
if ip in rng:
|
||||
return True
|
||||
fqdn = socket.getfqdn(str(ip)).lower()
|
||||
if fqdn in self.trusted_domains:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_trusted_connection(self,
|
||||
ip: Optional[IPAddr]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if ip is not None:
|
||||
curtime = time.time()
|
||||
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
|
||||
if ip in self.trusted_users:
|
||||
self.trusted_users[ip]['expires_at'] = exp_time
|
||||
return self.trusted_users[ip]
|
||||
elif self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
f"Trusted Connection Detected, IP: {ip}")
|
||||
self.trusted_users[ip] = {
|
||||
'username': TRUSTED_USER,
|
||||
'password': None,
|
||||
'created_on': curtime,
|
||||
'expires_at': exp_time
|
||||
}
|
||||
return self.trusted_users[ip]
|
||||
return None
|
||||
|
||||
def _check_oneshot_token(self,
|
||||
token: str,
|
||||
cur_ip: Optional[IPAddr]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if token in self.oneshot_tokens:
|
||||
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
|
||||
hdl.cancel()
|
||||
if cur_ip != ip_addr:
|
||||
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
|
||||
f", Recd: {cur_ip}")
|
||||
return None
|
||||
return user
|
||||
else:
|
||||
return None
|
||||
|
||||
def check_logins_maxed(self, ip_addr: IPAddr) -> bool:
|
||||
if self.max_logins is None:
|
||||
return False
|
||||
return self.failed_logins.get(ip_addr, 0) >= self.max_logins
|
||||
|
||||
def check_authorized(self,
|
||||
request: HTTPServerRequest
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if (
|
||||
request.path in self.permitted_paths
|
||||
or request.method == "OPTIONS"
|
||||
):
|
||||
return None
|
||||
|
||||
# Check JSON Web Token
|
||||
jwt_user = self._check_json_web_token(request)
|
||||
if jwt_user is not None:
|
||||
return jwt_user
|
||||
|
||||
try:
|
||||
ip = ipaddress.ip_address(request.remote_ip) # type: ignore
|
||||
except ValueError:
|
||||
logging.exception(
|
||||
f"Unable to Create IP Address {request.remote_ip}")
|
||||
ip = None
|
||||
|
||||
# Check oneshot access token
|
||||
ost: Optional[List[bytes]] = request.arguments.get('token', None)
|
||||
if ost is not None:
|
||||
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
|
||||
if ost_user is not None:
|
||||
return ost_user
|
||||
|
||||
# Check API Key Header
|
||||
if self.enable_api_key:
|
||||
key: Optional[str] = request.headers.get("X-Api-Key")
|
||||
if key and key == self.api_key:
|
||||
return self.users[API_USER]
|
||||
|
||||
# If the force_logins option is enabled and at least one
|
||||
# user is created this is an unauthorized request
|
||||
if self.force_logins and len(self.users) > 1:
|
||||
raise HTTPError(401, "Unauthorized, Force Logins Enabled")
|
||||
|
||||
# Check if IP is trusted
|
||||
trusted_user = self._check_trusted_connection(ip)
|
||||
if trusted_user is not None:
|
||||
return trusted_user
|
||||
|
||||
raise HTTPError(401, "Unauthorized")
|
||||
|
||||
def check_cors(self,
|
||||
origin: Optional[str],
|
||||
req_hdlr: Optional[RequestHandler] = None
|
||||
) -> bool:
|
||||
if origin is None or not self.cors_domains:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
if match is not None:
|
||||
if match.group() == origin:
|
||||
logging.debug(f"CORS Pattern Matched, origin: {origin} "
|
||||
f" | pattern: {regex}")
|
||||
self._set_cors_headers(origin, req_hdlr)
|
||||
return True
|
||||
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, req_hdlr)
|
||||
return True
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def _set_cors_headers(self,
|
||||
origin: str,
|
||||
req_hdlr: Optional[RequestHandler]
|
||||
) -> None:
|
||||
if req_hdlr is None:
|
||||
return
|
||||
req_hdlr.set_header("Access-Control-Allow-Origin", origin)
|
||||
if req_hdlr.request.method == "OPTIONS":
|
||||
req_hdlr.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
req_hdlr.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token, Authorization, X-Access-Token, "
|
||||
"X-Api-Key")
|
||||
if req_hdlr.request.headers.get(
|
||||
"Access-Control-Request-Private-Network", None) == "true":
|
||||
req_hdlr.set_header(
|
||||
"Access-Control-Allow-Private-Network",
|
||||
"true")
|
||||
|
||||
def cors_enabled(self) -> bool:
|
||||
return self.cors_domains is not None
|
||||
|
||||
def close(self) -> None:
|
||||
self.prune_timer.stop()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Authorization:
|
||||
return Authorization(config)
|
||||
@@ -0,0 +1,130 @@
|
||||
# Support for GPIO Button actions
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .gpio import GpioFactory
|
||||
from ..app import InternalTransport as ITransport
|
||||
|
||||
|
||||
class ButtonManager:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.buttons: Dict[str, GpioButton] = {}
|
||||
prefix_sections = config.get_prefix_sections("button")
|
||||
logging.info(f"Loading Buttons: {prefix_sections}")
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
# Reserve the "type" option for future use
|
||||
btn_type = cfg.get('type', "gpio")
|
||||
try:
|
||||
btn = GpioButton(cfg)
|
||||
except Exception as e:
|
||||
msg = f"Failed to load button [{cfg.get_name()}]\n{e}"
|
||||
self.server.add_warning(msg)
|
||||
continue
|
||||
self.buttons[btn.name] = btn
|
||||
self.server.register_notification("button:button_event")
|
||||
|
||||
def component_init(self) -> None:
|
||||
for btn in self.buttons.values():
|
||||
btn.initialize()
|
||||
|
||||
class GpioButton:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
self.name = config.get_name().split()[-1]
|
||||
self.itransport: ITransport = self.server.lookup_component(
|
||||
'internal_transport')
|
||||
self.mutex = asyncio.Lock()
|
||||
gpio: GpioFactory = self.server.load_component(config, 'gpio')
|
||||
self.gpio_event = gpio.register_gpio_event(
|
||||
config.get('pin'), self._on_gpio_event)
|
||||
min_event_time = config.getfloat(
|
||||
'minimum_event_time', .05, minval=.010)
|
||||
self.gpio_event.setup_debounce(min_event_time, self._on_gpio_error)
|
||||
self.press_template = config.gettemplate(
|
||||
"on_press", None, is_async=True)
|
||||
self.release_template = config.gettemplate(
|
||||
"on_release", None, is_async=True)
|
||||
if (
|
||||
self.press_template is None and
|
||||
self.release_template is None
|
||||
):
|
||||
raise config.error(
|
||||
f"[{config.get_name()}]: No template option configured")
|
||||
self.notification_sent: bool = False
|
||||
self.user_data: Dict[str, Any] = {}
|
||||
self.context: Dict[str, Any] = {
|
||||
'call_method': self.itransport.call_method,
|
||||
'send_notification': self._send_notification,
|
||||
'event': {
|
||||
'elapsed_time': 0.,
|
||||
'received_time': 0.,
|
||||
'render_time': 0.,
|
||||
'pressed': False,
|
||||
},
|
||||
'user_data': self.user_data
|
||||
}
|
||||
|
||||
def initialize(self) -> None:
|
||||
self.gpio_event.start()
|
||||
self.context['event']['pressed'] = bool(self.gpio_event.get_value())
|
||||
|
||||
def get_status(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'name': self.name,
|
||||
'type': "gpio",
|
||||
'event': self.context['event'],
|
||||
}
|
||||
|
||||
def _send_notification(self, result: Any = None) -> None:
|
||||
if self.notification_sent:
|
||||
# Only allow execution once per template
|
||||
return
|
||||
self.notification_sent = True
|
||||
data = self.get_status()
|
||||
data['aux'] = result
|
||||
self.server.send_event("button:button_event", data)
|
||||
|
||||
async def _on_gpio_event(self,
|
||||
eventtime: float,
|
||||
elapsed_time: float,
|
||||
pressed: int
|
||||
) -> None:
|
||||
template = self.press_template if pressed else self.release_template
|
||||
if template is None:
|
||||
return
|
||||
async with self.mutex:
|
||||
self.notification_sent = False
|
||||
event_info: Dict[str, Any] = {
|
||||
'elapsed_time': elapsed_time,
|
||||
'received_time': eventtime,
|
||||
'render_time': self.eventloop.get_loop_time(),
|
||||
'pressed': bool(pressed)
|
||||
}
|
||||
self.context['event'] = event_info
|
||||
try:
|
||||
await template.render_async(self.context)
|
||||
except Exception:
|
||||
action = "on_press" if pressed else "on_release"
|
||||
logging.exception(
|
||||
f"Button {self.name}: '{action}' template error")
|
||||
|
||||
def _on_gpio_error(self, message: str) -> None:
|
||||
self.server.add_warning(f"Button {self.name}: {message}")
|
||||
|
||||
def load_component(config: ConfigHelper) -> ButtonManager:
|
||||
return ButtonManager(config)
|
||||
@@ -0,0 +1,170 @@
|
||||
# Klipper data logging and storage storage
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Tuple,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
GCQueue = Deque[Dict[str, Any]]
|
||||
TempStore = Dict[str, Dict[str, Deque[float]]]
|
||||
|
||||
TEMP_UPDATE_TIME = 1.
|
||||
|
||||
class DataStore:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
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: Dict[str, Tuple[float, ...]] = {}
|
||||
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
|
||||
self.temperature_store: TempStore = {}
|
||||
eventloop = self.server.get_event_loop()
|
||||
self.temp_update_timer = eventloop.register_timer(
|
||||
self._update_temperature_store)
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self._update_gcode_store)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_sensors)
|
||||
self.server.register_event_handler(
|
||||
"klippy_connection:gcode_received", self._store_gcode_command
|
||||
)
|
||||
|
||||
# Register endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/temperature_store", ['GET'],
|
||||
self._handle_temp_store_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/gcode_store", ['GET'],
|
||||
self._handle_gcode_store_request)
|
||||
|
||||
async def _init_sensors(self) -> None:
|
||||
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
# Fetch sensors
|
||||
try:
|
||||
result: Dict[str, Any]
|
||||
result = await klippy_apis.query_objects({'heaters': None})
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error Configuring Sensors: {e}")
|
||||
return
|
||||
sensors: List[str]
|
||||
sensors = result.get("heaters", {}).get("available_sensors", [])
|
||||
|
||||
if sensors:
|
||||
# Add Subscription
|
||||
sub: Dict[str, Optional[List[str]]] = {s: None for s in sensors}
|
||||
try:
|
||||
status: Dict[str, Any]
|
||||
status = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to sensors: {e}")
|
||||
return
|
||||
logging.info(f"Configuring available sensors: {sensors}")
|
||||
new_store: TempStore = {}
|
||||
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=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., 0., 0.)
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
if sensor not in self.temperature_store:
|
||||
del self.last_temps[sensor]
|
||||
# Update initial temperatures
|
||||
self._set_current_temps(status)
|
||||
self.temp_update_timer.start()
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
self.last_temps = {}
|
||||
self.temperature_store = {}
|
||||
self.temp_update_timer.stop()
|
||||
|
||||
def _set_current_temps(self, data: Dict[str, Any]) -> None:
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
last_val = self.last_temps[sensor]
|
||||
self.last_temps[sensor] = (
|
||||
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, eventtime: float) -> float:
|
||||
# XXX - If klippy is not connected, set values to zero
|
||||
# as they are unknown?
|
||||
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)
|
||||
return eventtime + TEMP_UPDATE_TIME
|
||||
|
||||
async def _handle_temp_store_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, List[float]]]:
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
store[name] = {k: list(v) for k, v in sensor.items()}
|
||||
return store
|
||||
|
||||
async def close(self) -> None:
|
||||
self.temp_update_timer.stop()
|
||||
|
||||
def _update_gcode_store(self, response: str) -> None:
|
||||
curtime = time.time()
|
||||
self.gcode_queue.append(
|
||||
{'message': response, 'time': curtime, 'type': "response"})
|
||||
|
||||
def _store_gcode_command(self, script: str) -> None:
|
||||
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: WebRequest
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
count = web_request.get_int("count", None)
|
||||
if count is not None:
|
||||
gc_responses = list(self.gcode_queue)[-count:]
|
||||
else:
|
||||
gc_responses = list(self.gcode_queue)
|
||||
return {'gcode_store': gc_responses}
|
||||
|
||||
def load_component(config: ConfigHelper) -> DataStore:
|
||||
return DataStore(config)
|
||||
@@ -0,0 +1,942 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
import pathlib
|
||||
import json
|
||||
import struct
|
||||
import operator
|
||||
import logging
|
||||
from asyncio import Future, Task
|
||||
from io import BytesIO
|
||||
from functools import reduce
|
||||
from threading import Lock as ThreadLock
|
||||
import lmdb
|
||||
from ..utils import Sentinel, ServerError
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Mapping,
|
||||
TypeVar,
|
||||
Tuple,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
cast
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
DBRecord = Union[int, float, bool, str, List[Any], Dict[str, Any]]
|
||||
DBType = Optional[DBRecord]
|
||||
_T = TypeVar("_T")
|
||||
|
||||
DATABASE_VERSION = 1
|
||||
MAX_NAMESPACES = 100
|
||||
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.loads(bytes(x)),
|
||||
ord("{"): lambda x: json.loads(bytes(x)),
|
||||
}
|
||||
|
||||
def getitem_with_default(item: Dict, field: Any) -> Any:
|
||||
if not isinstance(item, Dict):
|
||||
raise ServerError(
|
||||
f"Cannot reduce a value of type {type(item)}")
|
||||
if field not in item:
|
||||
item[field] = {}
|
||||
return item[field]
|
||||
|
||||
|
||||
class MoonrakerDatabase:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
self.namespaces: Dict[str, object] = {}
|
||||
self.thread_lock = ThreadLock()
|
||||
app_args = self.server.get_app_args()
|
||||
dep_path = config.get("database_path", None, deprecate=True)
|
||||
db_path = pathlib.Path(app_args["data_path"]).joinpath("database")
|
||||
if (
|
||||
app_args["is_default_data_path"] and
|
||||
not db_path.joinpath("data.mdb").exists()
|
||||
):
|
||||
# Allow configured DB fallback
|
||||
dep_path = dep_path or "~/.moonraker_database"
|
||||
legacy_db = pathlib.Path(dep_path).expanduser().resolve()
|
||||
try:
|
||||
same = legacy_db.samefile(db_path)
|
||||
except Exception:
|
||||
same = False
|
||||
if not same and legacy_db.exists():
|
||||
logging.info(
|
||||
f"Reverting to legacy database path: {legacy_db}"
|
||||
)
|
||||
db_path = legacy_db
|
||||
if not db_path.is_dir():
|
||||
db_path.mkdir()
|
||||
self.database_path = str(db_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
|
||||
with txn.cursor() as cursor:
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
key = bytes(cursor.key())
|
||||
self.namespaces[key.decode()] = self.lmdb_env.open_db(
|
||||
key, txn)
|
||||
remaining = cursor.next()
|
||||
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)
|
||||
# Iterate through all records, checking for invalid keys
|
||||
for ns, db in self.namespaces.items():
|
||||
with txn.cursor(db=db) as cursor:
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
key_buf = cursor.key()
|
||||
try:
|
||||
decoded_key = bytes(key_buf).decode()
|
||||
except Exception:
|
||||
logging.info("Database Key Decode Error")
|
||||
decoded_key = ''
|
||||
if not decoded_key:
|
||||
hex_key = bytes(key_buf).hex()
|
||||
try:
|
||||
invalid_val = self._decode_value(cursor.value())
|
||||
except Exception:
|
||||
invalid_val = ""
|
||||
logging.info(
|
||||
f"Invalid Key '{hex_key}' found in namespace "
|
||||
f"'{ns}', dropping value: {repr(invalid_val)}")
|
||||
try:
|
||||
remaining = cursor.delete()
|
||||
except Exception:
|
||||
logging.exception("Error Deleting LMDB Key")
|
||||
else:
|
||||
continue
|
||||
remaining = cursor.next()
|
||||
|
||||
# Protected Namespaces have read-only API access. Write access can
|
||||
# be granted by enabling the debug option. Forbidden namespaces
|
||||
# have no API access. This cannot be overridden.
|
||||
self.protected_namespaces = set(self.get_item(
|
||||
"moonraker", "database.protected_namespaces",
|
||||
["moonraker"]).result())
|
||||
self.forbidden_namespaces = set(self.get_item(
|
||||
"moonraker", "database.forbidden_namespaces",
|
||||
[]).result())
|
||||
# Initialize Debug Counter
|
||||
config.getboolean("enable_database_debug", False, deprecate=True)
|
||||
self.debug_counter: Dict[str, int] = {"get": 0, "post": 0, "delete": 0}
|
||||
db_counter: Optional[Dict[str, int]] = self.get_item(
|
||||
"moonraker", "database.debug_counter", None
|
||||
).result()
|
||||
if isinstance(db_counter, dict):
|
||||
self.debug_counter.update(db_counter)
|
||||
self.server.add_log_rollover_item(
|
||||
"database_debug_counter",
|
||||
f"Database Debug Counter: {self.debug_counter}"
|
||||
)
|
||||
# Track unsafe shutdowns
|
||||
unsafe_shutdowns: int = self.get_item(
|
||||
"moonraker", "database.unsafe_shutdowns", 0).result()
|
||||
msg = f"Unsafe Shutdown Count: {unsafe_shutdowns}"
|
||||
self.server.add_log_rollover_item("database", msg)
|
||||
|
||||
# Increment unsafe shutdown counter. This will be reset if
|
||||
# moonraker is safely restarted
|
||||
self.insert_item("moonraker", "database.unsafe_shutdowns",
|
||||
unsafe_shutdowns + 1)
|
||||
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)
|
||||
self.server.register_debug_endpoint(
|
||||
"/debug/database/list", ['GET'], self._handle_list_request)
|
||||
self.server.register_debug_endpoint(
|
||||
"/debug/database/item", ["GET", "POST", "DELETE"],
|
||||
self._handle_item_request)
|
||||
|
||||
def get_database_path(self) -> str:
|
||||
return self.database_path
|
||||
|
||||
def _run_command(self,
|
||||
command_func: Callable[..., _T],
|
||||
*args
|
||||
) -> Future[_T]:
|
||||
def func_wrapper():
|
||||
with self.thread_lock:
|
||||
return command_func(*args)
|
||||
|
||||
if self.server.is_running():
|
||||
return cast(Future, self.eventloop.run_in_thread(func_wrapper))
|
||||
else:
|
||||
ret = func_wrapper()
|
||||
fut = self.eventloop.create_future()
|
||||
fut.set_result(ret)
|
||||
return fut
|
||||
|
||||
# *** Nested Database operations***
|
||||
# The insert_item(), delete_item(), and get_item() methods may operate on
|
||||
# nested objects within a namespace. Each operation takes a key argument
|
||||
# that may either be a string or a list of strings. If the argument is
|
||||
# a string nested keys may be delitmted by a "." by which the string
|
||||
# will be split into a list of strings. The first key in the list must
|
||||
# identify the database record. Subsequent keys are optional and are
|
||||
# used to access elements in the deserialized objects.
|
||||
|
||||
def insert_item(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._insert_impl, namespace, key, value)
|
||||
|
||||
def _insert_impl(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
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):
|
||||
prev_type = type(record)
|
||||
record = {}
|
||||
logging.info(
|
||||
f"Warning: Key {key_list[0]} contains a value of type "
|
||||
f"{prev_type}. Overwriting with an object.")
|
||||
item: Dict[str, Any] = reduce(
|
||||
getitem_with_default, key_list[1:-1], record)
|
||||
if not isinstance(item, dict):
|
||||
rpt_key = ".".join(key_list[:-1])
|
||||
raise self.server.error(
|
||||
f"Item at key '{rpt_key}' in namespace '{namespace}'is "
|
||||
"not a dictionary object, cannot insert"
|
||||
)
|
||||
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: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._update_impl, namespace, key, value)
|
||||
|
||||
def _update_impl(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
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:
|
||||
if value is None:
|
||||
raise self.server.error(
|
||||
f"Item at key '{key}', namespace '{namespace}': "
|
||||
"Cannot assign a record level null value")
|
||||
record = value
|
||||
else:
|
||||
try:
|
||||
assert isinstance(record, dict)
|
||||
item: Dict[str, Any] = reduce(
|
||||
operator.getitem, key_list[1:-1], record)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found",
|
||||
404)
|
||||
if not isinstance(item, dict) or key_list[-1] not in item:
|
||||
rpt_key = ".".join(key_list[:-1])
|
||||
raise self.server.error(
|
||||
f"Item at key '{rpt_key}' in namespace '{namespace}'is "
|
||||
"not a dictionary object, cannot update"
|
||||
)
|
||||
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: str,
|
||||
key: Union[List[str], str],
|
||||
drop_empty_db: bool = False
|
||||
) -> Future[Any]:
|
||||
return self._run_command(self._delete_impl, namespace, key,
|
||||
drop_empty_db)
|
||||
|
||||
def _delete_impl(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
drop_empty_db: bool = False
|
||||
) -> Any:
|
||||
key_list = self._process_key(key)
|
||||
val = record = self._get_record(namespace, key_list[0])
|
||||
remove_record = True
|
||||
if len(key_list) > 1:
|
||||
try:
|
||||
assert isinstance(record, dict)
|
||||
item: Dict[str, Any] = 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())
|
||||
with txn.cursor() as 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 "
|
||||
f"'{namespace}'")
|
||||
return val
|
||||
|
||||
def get_item(self,
|
||||
namespace: str,
|
||||
key: Optional[Union[List[str], str]] = None,
|
||||
default: Any = Sentinel.MISSING
|
||||
) -> Future[Any]:
|
||||
return self._run_command(self._get_impl, namespace, key, default)
|
||||
|
||||
def _get_impl(self,
|
||||
namespace: str,
|
||||
key: Optional[Union[List[str], str]] = None,
|
||||
default: Any = Sentinel.MISSING
|
||||
) -> Any:
|
||||
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, # type: ignore
|
||||
key_list[1:], ns)
|
||||
except Exception as e:
|
||||
if default is not Sentinel.MISSING:
|
||||
return default
|
||||
if isinstance(e, self.server.error):
|
||||
raise
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
return val
|
||||
|
||||
# *** Batch operations***
|
||||
# The insert_batch(), move_batch(), delete_batch(), and get_batch()
|
||||
# methods can be used to perform record level batch operations on
|
||||
# a namespace in a single transaction.
|
||||
|
||||
def insert_batch(self,
|
||||
namespace: str,
|
||||
records: Dict[str, Any]
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._insert_batch_impl, namespace, records)
|
||||
|
||||
def _insert_batch_impl(self,
|
||||
namespace: str,
|
||||
records: Dict[str, Any]
|
||||
) -> None:
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
namespace.encode())
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
for key, val in records.items():
|
||||
ret = txn.put(key.encode(), self._encode_value(val))
|
||||
if not ret:
|
||||
logging.info(f"Error inserting record {key} into "
|
||||
f"namespace {namespace}")
|
||||
|
||||
def move_batch(self,
|
||||
namespace: str,
|
||||
source_keys: List[str],
|
||||
dest_keys: List[str]
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._move_batch_impl, namespace,
|
||||
source_keys, dest_keys)
|
||||
|
||||
def _move_batch_impl(self,
|
||||
namespace: str,
|
||||
source_keys: List[str],
|
||||
dest_keys: List[str]
|
||||
) -> None:
|
||||
db = self._get_db(namespace)
|
||||
if len(source_keys) != len(dest_keys):
|
||||
raise self.server.error(
|
||||
"Source key list and destination key list must "
|
||||
"be of the same length")
|
||||
with self.lmdb_env.begin(write=True, db=db) as txn:
|
||||
for source, dest in zip(source_keys, dest_keys):
|
||||
val = txn.pop(source.encode())
|
||||
if val is not None:
|
||||
txn.put(dest.encode(), val)
|
||||
|
||||
def delete_batch(self,
|
||||
namespace: str,
|
||||
keys: List[str]
|
||||
) -> Future[Dict[str, Any]]:
|
||||
return self._run_command(self._del_batch_impl, namespace, keys)
|
||||
|
||||
def _del_batch_impl(self,
|
||||
namespace: str,
|
||||
keys: List[str]
|
||||
) -> Dict[str, Any]:
|
||||
db = self._get_db(namespace)
|
||||
result: Dict[str, Any] = {}
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
for key in keys:
|
||||
val = txn.pop(key.encode())
|
||||
if val is not None:
|
||||
result[key] = self._decode_value(val)
|
||||
return result
|
||||
|
||||
def get_batch(self,
|
||||
namespace: str,
|
||||
keys: List[str]
|
||||
) -> Future[Dict[str, Any]]:
|
||||
return self._run_command(self._get_batch_impl, namespace, keys)
|
||||
|
||||
def _get_batch_impl(self,
|
||||
namespace: str,
|
||||
keys: List[str]
|
||||
) -> Dict[str, Any]:
|
||||
db = self._get_db(namespace)
|
||||
result: Dict[str, Any] = {}
|
||||
encoded_keys: List[bytes] = [k.encode() for k in keys]
|
||||
with self.lmdb_env.begin(buffers=True, db=db) as txn:
|
||||
with txn.cursor() as cursor:
|
||||
vals = cursor.getmulti(encoded_keys)
|
||||
result = {bytes(k).decode(): self._decode_value(v)
|
||||
for k, v in vals}
|
||||
return result
|
||||
|
||||
# *** Namespace level operations***
|
||||
|
||||
def update_namespace(self,
|
||||
namespace: str,
|
||||
value: Mapping[str, DBRecord]
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._update_ns_impl, namespace, value)
|
||||
|
||||
def _update_ns_impl(self,
|
||||
namespace: str,
|
||||
value: Mapping[str, DBRecord]
|
||||
) -> None:
|
||||
if not value:
|
||||
return
|
||||
db = self._get_db(namespace)
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
# We only need to update the keys that changed
|
||||
for key, val in value.items():
|
||||
stored = txn.get(key.encode())
|
||||
if stored is not None:
|
||||
decoded = self._decode_value(stored)
|
||||
if val == decoded:
|
||||
continue
|
||||
ret = txn.put(key.encode(), self._encode_value(val))
|
||||
if not ret:
|
||||
logging.info(f"Error inserting key '{key}' "
|
||||
f"in namespace '{namespace}'")
|
||||
|
||||
def clear_namespace(self,
|
||||
namespace: str,
|
||||
drop_empty_db: bool = False
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._clear_ns_impl, namespace, drop_empty_db)
|
||||
|
||||
def _clear_ns_impl(self,
|
||||
namespace: str,
|
||||
drop_empty_db: bool = False
|
||||
) -> None:
|
||||
db = self._get_db(namespace)
|
||||
with self.lmdb_env.begin(write=True, db=db) as txn:
|
||||
txn.drop(db, delete=drop_empty_db)
|
||||
if drop_empty_db:
|
||||
del self.namespaces[namespace]
|
||||
|
||||
def sync_namespace(self,
|
||||
namespace: str,
|
||||
value: Mapping[str, DBRecord]
|
||||
) -> Future[None]:
|
||||
return self._run_command(self._sync_ns_impl, namespace, value)
|
||||
|
||||
def _sync_ns_impl(self,
|
||||
namespace: str,
|
||||
value: Mapping[str, DBRecord]
|
||||
) -> None:
|
||||
if not value:
|
||||
raise self.server.error("Cannot sync to an empty value")
|
||||
db = self._get_db(namespace)
|
||||
new_keys = set(value.keys())
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
with txn.cursor() as cursor:
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
bkey, bval = cursor.item()
|
||||
key = bytes(bkey).decode()
|
||||
if key not in value:
|
||||
remaining = cursor.delete()
|
||||
else:
|
||||
decoded = self._decode_value(bval)
|
||||
if decoded != value[key]:
|
||||
new_val = self._encode_value(value[key])
|
||||
txn.put(key.encode(), new_val)
|
||||
new_keys.remove(key)
|
||||
remaining = cursor.next()
|
||||
for key in new_keys:
|
||||
val = value[key]
|
||||
ret = txn.put(key.encode(), self._encode_value(val))
|
||||
if not ret:
|
||||
logging.info(f"Error inserting key '{key}' "
|
||||
f"in namespace '{namespace}'")
|
||||
|
||||
def ns_length(self, namespace: str) -> Future[int]:
|
||||
return self._run_command(self._ns_length_impl, namespace)
|
||||
|
||||
def _ns_length_impl(self, namespace: str) -> int:
|
||||
db = self._get_db(namespace)
|
||||
with self.lmdb_env.begin(db=db) as txn:
|
||||
stats = txn.stat(db)
|
||||
return stats['entries']
|
||||
|
||||
def ns_keys(self, namespace: str) -> Future[List[str]]:
|
||||
return self._run_command(self._ns_keys_impl, namespace)
|
||||
|
||||
def _ns_keys_impl(self, namespace: str) -> List[str]:
|
||||
keys: List[str] = []
|
||||
db = self._get_db(namespace)
|
||||
with self.lmdb_env.begin(db=db) as txn:
|
||||
with txn.cursor() as cursor:
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
keys.append(cursor.key().decode())
|
||||
remaining = cursor.next()
|
||||
return keys
|
||||
|
||||
def ns_values(self, namespace: str) -> Future[List[Any]]:
|
||||
return self._run_command(self._ns_values_impl, namespace)
|
||||
|
||||
def _ns_values_impl(self, namespace: str) -> List[Any]:
|
||||
values: List[Any] = []
|
||||
db = self._get_db(namespace)
|
||||
with self.lmdb_env.begin(db=db, buffers=True) as txn:
|
||||
with txn.cursor() as cursor:
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
values.append(self._decode_value(cursor.value()))
|
||||
remaining = cursor.next()
|
||||
return values
|
||||
|
||||
def ns_items(self, namespace: str) -> Future[List[Tuple[str, Any]]]:
|
||||
return self._run_command(self._ns_items_impl, namespace)
|
||||
|
||||
def _ns_items_impl(self, namespace: str) -> List[Tuple[str, Any]]:
|
||||
ns = self._get_namespace(namespace)
|
||||
return list(ns.items())
|
||||
|
||||
def ns_contains(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str]
|
||||
) -> Future[bool]:
|
||||
return self._run_command(self._ns_contains_impl, namespace, key)
|
||||
|
||||
def _ns_contains_impl(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str]
|
||||
) -> bool:
|
||||
self._get_db(namespace)
|
||||
try:
|
||||
key_list = self._process_key(key)
|
||||
record = self._get_record(namespace, key_list[0])
|
||||
if len(key_list) == 1:
|
||||
return True
|
||||
reduce(operator.getitem, # type: ignore
|
||||
key_list[1:], record)
|
||||
except Exception:
|
||||
return False
|
||||
return True
|
||||
|
||||
def register_local_namespace(self,
|
||||
namespace: str,
|
||||
forbidden: bool = False
|
||||
) -> None:
|
||||
if self.server.is_running():
|
||||
raise self.server.error(
|
||||
"Cannot register a namespace while the "
|
||||
"server is running")
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
namespace.encode())
|
||||
if forbidden:
|
||||
if namespace not in self.forbidden_namespaces:
|
||||
self.forbidden_namespaces.add(namespace)
|
||||
self.insert_item(
|
||||
"moonraker", "database.forbidden_namespaces",
|
||||
list(self.forbidden_namespaces))
|
||||
elif namespace not in self.protected_namespaces:
|
||||
self.protected_namespaces.add(namespace)
|
||||
self.insert_item("moonraker", "database.protected_namespaces",
|
||||
sorted(self.protected_namespaces))
|
||||
|
||||
def wrap_namespace(self,
|
||||
namespace: str,
|
||||
parse_keys: bool = True
|
||||
) -> NamespaceWrapper:
|
||||
if self.server.is_running():
|
||||
raise self.server.error(
|
||||
"Cannot wrap a namespace while the "
|
||||
"server is running")
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Namespace '{namespace}' not found", 404)
|
||||
return NamespaceWrapper(namespace, self, parse_keys)
|
||||
|
||||
def _get_db(self, namespace: str) -> object:
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(f"Namespace '{namespace}' not found", 404)
|
||||
return self.namespaces[namespace]
|
||||
|
||||
def _process_key(self, key: Union[List[str], str]) -> List[str]:
|
||||
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: str, key: str, val: DBType) -> bool:
|
||||
db = self._get_db(namespace)
|
||||
if val is None:
|
||||
return False
|
||||
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: str,
|
||||
key: str,
|
||||
force: bool = False
|
||||
) -> DBRecord:
|
||||
db = self._get_db(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: str) -> Dict[str, Any]:
|
||||
db = self._get_db(namespace)
|
||||
result = {}
|
||||
invalid_key_result = None
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
with txn.cursor() as cursor:
|
||||
has_remaining = cursor.first()
|
||||
while has_remaining:
|
||||
db_key, value = cursor.item()
|
||||
k = bytes(db_key).decode()
|
||||
if not k:
|
||||
invalid_key_result = self._decode_value(value)
|
||||
logging.info(
|
||||
f"Invalid Key '{db_key}' found in namespace "
|
||||
f"'{namespace}', dropping value: "
|
||||
f"{repr(invalid_key_result)}")
|
||||
try:
|
||||
has_remaining = cursor.delete()
|
||||
except Exception:
|
||||
logging.exception("Error Deleting LMDB Key")
|
||||
has_remaining = cursor.next()
|
||||
else:
|
||||
result[k] = self._decode_value(value)
|
||||
has_remaining = cursor.next()
|
||||
return result
|
||||
|
||||
def _encode_value(self, value: DBRecord) -> bytes:
|
||||
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: Union[bytes, memoryview]) -> DBRecord:
|
||||
fmt = bvalue[0]
|
||||
try:
|
||||
decode_func = RECORD_DECODE_FUNCS[fmt]
|
||||
return decode_func(bvalue)
|
||||
except Exception:
|
||||
val = bytes(bvalue).decode()
|
||||
raise self.server.error(
|
||||
f"Error decoding value {val}, format: {chr(fmt)}")
|
||||
|
||||
async def _handle_list_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, List[str]]:
|
||||
path = web_request.get_endpoint()
|
||||
await self.eventloop.run_in_thread(self.thread_lock.acquire)
|
||||
try:
|
||||
ns_list = set(self.namespaces.keys())
|
||||
if not path.startswith("/debug/"):
|
||||
ns_list -= self.forbidden_namespaces
|
||||
finally:
|
||||
self.thread_lock.release()
|
||||
return {'namespaces': list(ns_list)}
|
||||
|
||||
async def _handle_item_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
is_debug = web_request.get_endpoint().startswith("/debug/")
|
||||
namespace = web_request.get_str("namespace")
|
||||
if namespace in self.forbidden_namespaces and not is_debug:
|
||||
raise self.server.error(
|
||||
f"Read/Write access to namespace '{namespace}'"
|
||||
" is forbidden", 403)
|
||||
key: Any
|
||||
valid_types: Tuple[type, ...]
|
||||
if action != "GET":
|
||||
if namespace in self.protected_namespaces and not is_debug:
|
||||
raise self.server.error(
|
||||
f"Write access to namespace '{namespace}'"
|
||||
" is forbidden", 403)
|
||||
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 = await self.get_item(namespace, key)
|
||||
elif action == "POST":
|
||||
val = web_request.get("value")
|
||||
await self.insert_item(namespace, key, val)
|
||||
elif action == "DELETE":
|
||||
val = await self.delete_item(namespace, key, drop_empty_db=True)
|
||||
|
||||
if is_debug:
|
||||
self.debug_counter[action.lower()] += 1
|
||||
await self.insert_item(
|
||||
"moonraker", "database.debug_counter", self.debug_counter
|
||||
)
|
||||
self.server.add_log_rollover_item(
|
||||
"database_debug_counter",
|
||||
f"Database Debug Counter: {self.debug_counter}",
|
||||
log=False
|
||||
)
|
||||
return {'namespace': namespace, 'key': key, 'value': val}
|
||||
|
||||
async def close(self) -> None:
|
||||
# Decrement unsafe shutdown counter
|
||||
unsafe_shutdowns: int = await self.get_item(
|
||||
"moonraker", "database.unsafe_shutdowns", 0)
|
||||
await self.insert_item(
|
||||
"moonraker", "database.unsafe_shutdowns",
|
||||
unsafe_shutdowns - 1)
|
||||
await self.eventloop.run_in_thread(self.thread_lock.acquire)
|
||||
try:
|
||||
# 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()
|
||||
finally:
|
||||
self.thread_lock.release()
|
||||
|
||||
class NamespaceWrapper:
|
||||
def __init__(self,
|
||||
namespace: str,
|
||||
database: MoonrakerDatabase,
|
||||
parse_keys: bool
|
||||
) -> None:
|
||||
self.namespace = namespace
|
||||
self.db = database
|
||||
self.eventloop = database.eventloop
|
||||
self.server = database.server
|
||||
# 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: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> Awaitable[None]:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.insert_item(self.namespace, key, value)
|
||||
|
||||
def update_child(self,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> Awaitable[None]:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.update_item(self.namespace, key, value)
|
||||
|
||||
def update(self, value: Mapping[str, DBRecord]) -> Awaitable[None]:
|
||||
return self.db.update_namespace(self.namespace, value)
|
||||
|
||||
def sync(self, value: Mapping[str, DBRecord]) -> Awaitable[None]:
|
||||
return self.db.sync_namespace(self.namespace, value)
|
||||
|
||||
def get(self,
|
||||
key: Union[List[str], str],
|
||||
default: Any = None
|
||||
) -> Future[Any]:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.get_item(self.namespace, key, default)
|
||||
|
||||
def delete(self, key: Union[List[str], str]) -> Future[Any]:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.delete_item(self.namespace, key)
|
||||
|
||||
def insert_batch(self, records: Dict[str, Any]) -> Future[None]:
|
||||
return self.db.insert_batch(self.namespace, records)
|
||||
|
||||
def move_batch(self,
|
||||
source_keys: List[str],
|
||||
dest_keys: List[str]
|
||||
) -> Future[None]:
|
||||
return self.db.move_batch(self.namespace, source_keys, dest_keys)
|
||||
|
||||
def delete_batch(self, keys: List[str]) -> Future[Dict[str, Any]]:
|
||||
return self.db.delete_batch(self.namespace, keys)
|
||||
|
||||
def get_batch(self, keys: List[str]) -> Future[Dict[str, Any]]:
|
||||
return self.db.get_batch(self.namespace, keys)
|
||||
|
||||
def length(self) -> Future[int]:
|
||||
return self.db.ns_length(self.namespace)
|
||||
|
||||
def as_dict(self) -> Dict[str, Any]:
|
||||
self._check_sync_method("as_dict")
|
||||
return self.db._get_namespace(self.namespace)
|
||||
|
||||
def __getitem__(self, key: Union[List[str], str]) -> Future[Any]:
|
||||
return self.get(key, default=Sentinel.MISSING)
|
||||
|
||||
def __setitem__(self,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
self.insert(key, value)
|
||||
|
||||
def __delitem__(self, key: Union[List[str], str]):
|
||||
self.delete(key)
|
||||
|
||||
def __contains__(self, key: Union[List[str], str]) -> bool:
|
||||
self._check_sync_method("__contains__")
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.ns_contains(self.namespace, key).result()
|
||||
|
||||
def contains(self, key: Union[List[str], str]) -> Future[bool]:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.ns_contains(self.namespace, key)
|
||||
|
||||
def keys(self) -> Future[List[str]]:
|
||||
return self.db.ns_keys(self.namespace)
|
||||
|
||||
def values(self) -> Future[List[Any]]:
|
||||
return self.db.ns_values(self.namespace)
|
||||
|
||||
def items(self) -> Future[List[Tuple[str, Any]]]:
|
||||
return self.db.ns_items(self.namespace)
|
||||
|
||||
def pop(self,
|
||||
key: Union[List[str], str],
|
||||
default: Any = Sentinel.MISSING
|
||||
) -> Union[Future[Any], Task[Any]]:
|
||||
if not self.server.is_running():
|
||||
try:
|
||||
val = self.delete(key).result()
|
||||
except Exception:
|
||||
if default is Sentinel.MISSING:
|
||||
raise
|
||||
val = default
|
||||
fut = self.eventloop.create_future()
|
||||
fut.set_result(val)
|
||||
return fut
|
||||
|
||||
async def _do_pop() -> Any:
|
||||
try:
|
||||
val = await self.delete(key)
|
||||
except Exception:
|
||||
if default is Sentinel.MISSING:
|
||||
raise
|
||||
val = default
|
||||
return val
|
||||
return self.eventloop.create_task(_do_pop())
|
||||
|
||||
def clear(self) -> Awaitable[None]:
|
||||
return self.db.clear_namespace(self.namespace)
|
||||
|
||||
def _check_sync_method(self, func_name: str) -> None:
|
||||
if self.server.is_running():
|
||||
raise self.server.error(
|
||||
f"Cannot call method {func_name} while "
|
||||
"the eventloop is running")
|
||||
|
||||
def load_component(config: ConfigHelper) -> MoonrakerDatabase:
|
||||
return MoonrakerDatabase(config)
|
||||
@@ -0,0 +1,136 @@
|
||||
# DBus Connection Management
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
import dbus_next
|
||||
from dbus_next.aio import MessageBus, ProxyInterface
|
||||
from dbus_next.constants import BusType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
List,
|
||||
Optional,
|
||||
Any,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
|
||||
STAT_PATH = "/proc/self/stat"
|
||||
DOC_URL = (
|
||||
"https://moonraker.readthedocs.io/en/latest/"
|
||||
"installation/#policykit-permissions"
|
||||
)
|
||||
|
||||
class DbusManager:
|
||||
Variant = dbus_next.Variant
|
||||
DbusError = dbus_next.errors.DBusError
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.bus: Optional[MessageBus] = None
|
||||
self.polkit: Optional[ProxyInterface] = None
|
||||
self.warned: bool = False
|
||||
st_path = pathlib.Path(STAT_PATH)
|
||||
self.polkit_subject: List[Any] = []
|
||||
if not st_path.is_file():
|
||||
return
|
||||
proc_data = st_path.read_text()
|
||||
start_clk_ticks = int(proc_data.split()[21])
|
||||
self.polkit_subject = [
|
||||
"unix-process",
|
||||
{
|
||||
"pid": dbus_next.Variant("u", os.getpid()),
|
||||
"start-time": dbus_next.Variant("t", start_clk_ticks)
|
||||
}
|
||||
]
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
return self.bus is not None and self.bus.connected
|
||||
|
||||
async def component_init(self) -> None:
|
||||
try:
|
||||
self.bus = MessageBus(bus_type=BusType.SYSTEM)
|
||||
await self.bus.connect()
|
||||
except Exception:
|
||||
logging.info("Unable to Connect to D-Bus")
|
||||
return
|
||||
# Make sure that all required actions are register
|
||||
try:
|
||||
self.polkit = await self.get_interface(
|
||||
"org.freedesktop.PolicyKit1",
|
||||
"/org/freedesktop/PolicyKit1/Authority",
|
||||
"org.freedesktop.PolicyKit1.Authority")
|
||||
except self.DbusError:
|
||||
self.server.add_warning(
|
||||
"Unable to find DBus PolKit Interface, this suggests PolKit "
|
||||
"is not installed on your OS.")
|
||||
|
||||
async def check_permission(self,
|
||||
action: str,
|
||||
err_msg: str = ""
|
||||
) -> bool:
|
||||
if self.polkit is None:
|
||||
return False
|
||||
try:
|
||||
ret = await self.polkit.call_check_authorization( # type: ignore
|
||||
self.polkit_subject, action, {}, 0, "")
|
||||
except Exception as e:
|
||||
self._check_warned()
|
||||
self.server.add_warning(
|
||||
f"Error checking authorization for action [{action}]: {e}. "
|
||||
"This suggests that a dependency is not installed or "
|
||||
f"up to date. {err_msg}.")
|
||||
return False
|
||||
if not ret[0]:
|
||||
self._check_warned()
|
||||
self.server.add_warning(
|
||||
"Moonraker not authorized for PolicyKit action: "
|
||||
f"[{action}], {err_msg}")
|
||||
return ret[0]
|
||||
|
||||
def _check_warned(self):
|
||||
if not self.warned:
|
||||
self.server.add_warning(
|
||||
f"PolKit warnings detected. See {DOC_URL} for instructions "
|
||||
"on how to resolve.")
|
||||
self.warned = True
|
||||
|
||||
async def get_interface(self,
|
||||
bus_name: str,
|
||||
bus_path: str,
|
||||
interface_name: str
|
||||
) -> ProxyInterface:
|
||||
ret = await self.get_interfaces(bus_name, bus_path,
|
||||
[interface_name])
|
||||
return ret[0]
|
||||
|
||||
async def get_interfaces(self,
|
||||
bus_name: str,
|
||||
bus_path: str,
|
||||
interface_names: List[str]
|
||||
) -> List[ProxyInterface]:
|
||||
if self.bus is None:
|
||||
raise self.server.error("Bus not avaialable")
|
||||
interfaces: List[ProxyInterface] = []
|
||||
introspection = await self.bus.introspect(bus_name, bus_path)
|
||||
proxy_obj = self.bus.get_proxy_object(bus_name, bus_path,
|
||||
introspection)
|
||||
for ifname in interface_names:
|
||||
intf = proxy_obj.get_interface(ifname)
|
||||
interfaces.append(intf)
|
||||
return interfaces
|
||||
|
||||
async def close(self):
|
||||
if self.bus is not None and self.bus.connected:
|
||||
self.bus.disconnect()
|
||||
await self.bus.wait_for_disconnect()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> DbusManager:
|
||||
return DbusManager(config)
|
||||
@@ -0,0 +1,237 @@
|
||||
# Moonraker extension management
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import pathlib
|
||||
import logging
|
||||
import json
|
||||
from ..websockets import BaseSocketClient
|
||||
from ..utils import get_unix_peer_credentials
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Union,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..server import Server
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from ..klippy_connection import KlippyConnection as Klippy
|
||||
|
||||
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
|
||||
|
||||
class ExtensionManager:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.agents: Dict[str, BaseSocketClient] = {}
|
||||
self.uds_server: Optional[asyncio.AbstractServer] = None
|
||||
self.server.register_endpoint(
|
||||
"/connection/send_event", ["POST"], self._handle_agent_event,
|
||||
transports=["websocket"]
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/extensions/list", ["GET"], self._handle_list_extensions
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/extensions/request", ["POST"], self._handle_call_agent
|
||||
)
|
||||
|
||||
def register_agent(self, connection: BaseSocketClient) -> None:
|
||||
data = connection.client_data
|
||||
name = data["name"]
|
||||
client_type = data["type"]
|
||||
if client_type != "agent":
|
||||
raise self.server.error(
|
||||
f"Cannot register client type '{client_type}' as an agent"
|
||||
)
|
||||
if name in self.agents:
|
||||
raise self.server.error(
|
||||
f"Agent '{name}' already registered and connected'"
|
||||
)
|
||||
self.agents[name] = connection
|
||||
data = connection.client_data
|
||||
evt: Dict[str, Any] = {
|
||||
"agent": name, "event": "connected", "data": data
|
||||
}
|
||||
connection.send_notification("agent_event", [evt])
|
||||
|
||||
def remove_agent(self, connection: BaseSocketClient) -> None:
|
||||
name = connection.client_data["name"]
|
||||
if name in self.agents:
|
||||
del self.agents[name]
|
||||
evt: Dict[str, Any] = {"agent": name, "event": "disconnected"}
|
||||
connection.send_notification("agent_event", [evt])
|
||||
|
||||
async def _handle_agent_event(self, web_request: WebRequest) -> str:
|
||||
conn = web_request.get_client_connection()
|
||||
if conn is None:
|
||||
raise self.server.error("No connection detected")
|
||||
if conn.client_data["type"] != "agent":
|
||||
raise self.server.error(
|
||||
"Only connections of the 'agent' type can send events"
|
||||
)
|
||||
name = conn.client_data["name"]
|
||||
evt_name = web_request.get_str("event")
|
||||
if evt_name in ["connected", "disconnected"]:
|
||||
raise self.server.error(f"Event '{evt_name}' is reserved")
|
||||
data: Optional[Union[List, Dict[str, Any]]]
|
||||
data = web_request.get("data", None)
|
||||
evt: Dict[str, Any] = {"agent": name, "event": evt_name}
|
||||
if data is not None:
|
||||
evt["data"] = data
|
||||
conn.send_notification("agent_event", [evt])
|
||||
return "ok"
|
||||
|
||||
async def _handle_list_extensions(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
agents: List[Dict[str, Any]]
|
||||
agents = [agt.client_data for agt in self.agents.values()]
|
||||
return {"agents": agents}
|
||||
|
||||
async def _handle_call_agent(self, web_request: WebRequest) -> Any:
|
||||
agent = web_request.get_str("agent")
|
||||
method: str = web_request.get_str("method")
|
||||
args: Optional[Union[List, Dict[str, Any]]]
|
||||
args = web_request.get("arguments", None)
|
||||
if args is not None and not isinstance(args, (list, dict)):
|
||||
raise self.server.error(
|
||||
"The 'arguments' field must contain an object or a list"
|
||||
)
|
||||
if agent not in self.agents:
|
||||
raise self.server.error(f"Agent {agent} not connected")
|
||||
conn = self.agents[agent]
|
||||
return await conn.call_method(method, args)
|
||||
|
||||
async def start_unix_server(self) -> None:
|
||||
data_path = pathlib.Path(self.server.get_app_args()["data_path"])
|
||||
comms_path = data_path.joinpath("comms")
|
||||
if not comms_path.exists():
|
||||
comms_path.mkdir()
|
||||
sock_path = comms_path.joinpath("moonraker.sock")
|
||||
logging.info(f"Creating Unix Domain Socket at '{sock_path}'")
|
||||
self.uds_server = await asyncio.start_unix_server(
|
||||
self.on_unix_socket_connected, sock_path, limit=UNIX_BUFFER_LIMIT
|
||||
)
|
||||
|
||||
def on_unix_socket_connected(
|
||||
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
|
||||
) -> None:
|
||||
peercred = get_unix_peer_credentials(writer, "Unix Client Connection")
|
||||
UnixSocketClient(self.server, reader, writer, peercred)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.uds_server is not None:
|
||||
self.uds_server.close()
|
||||
await self.uds_server.wait_closed()
|
||||
self.uds_server = None
|
||||
|
||||
class UnixSocketClient(BaseSocketClient):
|
||||
def __init__(
|
||||
self,
|
||||
server: Server,
|
||||
reader: asyncio.StreamReader,
|
||||
writer: asyncio.StreamWriter,
|
||||
peercred: Dict[str, int]
|
||||
) -> None:
|
||||
self.on_create(server)
|
||||
self.writer = writer
|
||||
self._peer_cred = peercred
|
||||
self._connected_time = self.eventloop.get_loop_time()
|
||||
pid = self._peer_cred.get("process_id")
|
||||
uid = self._peer_cred.get("user_id")
|
||||
gid = self._peer_cred.get("group_id")
|
||||
self.wsm.add_client(self)
|
||||
logging.info(
|
||||
f"Unix Socket Opened - Client ID: {self.uid}, "
|
||||
f"Process ID: {pid}, User ID: {uid}, Group ID: {gid}"
|
||||
)
|
||||
self.eventloop.register_callback(self._read_messages, reader)
|
||||
|
||||
async def _read_messages(self, reader: asyncio.StreamReader) -> None:
|
||||
errors_remaining: int = 10
|
||||
while not reader.at_eof():
|
||||
try:
|
||||
data = await reader.readuntil(b'\x03')
|
||||
decoded = data[:-1].decode(encoding="utf-8")
|
||||
except (ConnectionError, asyncio.IncompleteReadError):
|
||||
break
|
||||
except asyncio.CancelledError:
|
||||
logging.exception("Unix Client Stream Read Cancelled")
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception("Unix Client Stream Read Error")
|
||||
errors_remaining -= 1
|
||||
if not errors_remaining or self.is_closed:
|
||||
break
|
||||
continue
|
||||
errors_remaining = 10
|
||||
self.eventloop.register_callback(self._process_message, decoded)
|
||||
logging.debug("Unix Socket Disconnection From _read_messages()")
|
||||
await self._on_close(reason="Read Exit")
|
||||
|
||||
async def write_to_socket(
|
||||
self, message: Union[str, Dict[str, Any]]
|
||||
) -> None:
|
||||
if isinstance(message, dict):
|
||||
data = json.dumps(message).encode() + b"\x03"
|
||||
else:
|
||||
data = message.encode() + b"\x03"
|
||||
try:
|
||||
self.writer.write(data)
|
||||
await self.writer.drain()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.debug("Unix Socket Disconnection From write_to_socket()")
|
||||
await self._on_close(reason="Write Exception")
|
||||
|
||||
async def _on_close(
|
||||
self,
|
||||
code: Optional[int] = None,
|
||||
reason: Optional[str] = None
|
||||
) -> None:
|
||||
if self.is_closed:
|
||||
return
|
||||
self.is_closed = True
|
||||
kconn: Klippy = self.server.lookup_component("klippy_connection")
|
||||
kconn.remove_subscription(self)
|
||||
if not self.writer.is_closing():
|
||||
self.writer.close()
|
||||
try:
|
||||
await self.writer.wait_closed()
|
||||
except Exception:
|
||||
pass
|
||||
self.message_buf = []
|
||||
for resp in self.pending_responses.values():
|
||||
resp.set_exception(
|
||||
self.server.error("Client Socket Disconnected", 500)
|
||||
)
|
||||
self.pending_responses = {}
|
||||
logging.info(
|
||||
f"Unix Socket Closed: ID: {self.uid}, "
|
||||
f"Close Code: {code}, "
|
||||
f"Close Reason: {reason}"
|
||||
)
|
||||
if self._client_data["type"] == "agent":
|
||||
extensions: ExtensionManager
|
||||
extensions = self.server.lookup_component("extensions")
|
||||
extensions.remove_agent(self)
|
||||
self.wsm.remove_client(self)
|
||||
|
||||
def close_socket(self, code: int, reason: str) -> None:
|
||||
if not self.is_closed:
|
||||
self.eventloop.register_callback(self._on_close, code, reason)
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> ExtensionManager:
|
||||
return ExtensionManager(config)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Package definition for the file_manager
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
from . import file_manager as fm
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
|
||||
def load_component(config: ConfigHelper) -> fm.FileManager:
|
||||
return fm.load_component(config)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,285 @@
|
||||
# GPIO Factory helper
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
from ..utils import load_system_module
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Dict,
|
||||
Optional
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..eventloop import EventLoop
|
||||
GPIO_CALLBACK = Callable[[float, float, int], Optional[Awaitable[None]]]
|
||||
|
||||
class GpioFactory:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.gpiod: Any = load_system_module("gpiod")
|
||||
GpioEvent.init_constants(self.gpiod)
|
||||
self.chips: Dict[str, Any] = {}
|
||||
self.reserved_gpios: Dict[str, GpioBase] = {}
|
||||
version: str = self.gpiod.version_string()
|
||||
self.gpiod_version = tuple(int(v) for v in version.split('.'))
|
||||
self.server.add_log_rollover_item(
|
||||
"gpiod_version", f"libgpiod version: {version}")
|
||||
|
||||
def _get_gpio_chip(self, chip_name) -> Any:
|
||||
if chip_name in self.chips:
|
||||
return self.chips[chip_name]
|
||||
chip = self.gpiod.Chip(chip_name, self.gpiod.Chip.OPEN_BY_NAME)
|
||||
self.chips[chip_name] = chip
|
||||
return chip
|
||||
|
||||
def setup_gpio_out(self,
|
||||
pin_name: str,
|
||||
initial_value: int = 0
|
||||
) -> GpioOutputPin:
|
||||
initial_value = int(not not initial_value)
|
||||
pparams = self._parse_pin(pin_name)
|
||||
pparams['initial_value'] = initial_value
|
||||
line = self._request_gpio(pparams)
|
||||
try:
|
||||
gpio_out = GpioOutputPin(line, pparams)
|
||||
except Exception:
|
||||
logging.exception("Error Instantiating GpioOutputPin")
|
||||
line.release()
|
||||
raise
|
||||
full_name = pparams['full_name']
|
||||
self.reserved_gpios[full_name] = gpio_out
|
||||
return gpio_out
|
||||
|
||||
def register_gpio_event(self,
|
||||
pin_name: str,
|
||||
callback: GPIO_CALLBACK
|
||||
) -> GpioEvent:
|
||||
pin_params = self._parse_pin(pin_name, type="event")
|
||||
line = self._request_gpio(pin_params)
|
||||
event_loop = self.server.get_event_loop()
|
||||
try:
|
||||
gpio_event = GpioEvent(event_loop, line, pin_params, callback)
|
||||
except Exception:
|
||||
logging.exception("Error Instantiating GpioEvent")
|
||||
line.release()
|
||||
raise
|
||||
full_name = pin_params['full_name']
|
||||
self.reserved_gpios[full_name] = gpio_event
|
||||
return gpio_event
|
||||
|
||||
def _request_gpio(self, pin_params: Dict[str, Any]) -> Any:
|
||||
full_name = pin_params['full_name']
|
||||
if full_name in self.reserved_gpios:
|
||||
raise self.server.error(f"GPIO {full_name} already reserved")
|
||||
try:
|
||||
chip = self._get_gpio_chip(pin_params['chip_id'])
|
||||
line = chip.get_line(pin_params['pin_id'])
|
||||
args: Dict[str, Any] = {
|
||||
'consumer': "moonraker",
|
||||
'type': pin_params['request_type']
|
||||
}
|
||||
if 'flags' in pin_params:
|
||||
args['flags'] = pin_params['flags']
|
||||
if 'initial_value' in pin_params:
|
||||
if self.gpiod_version < (1, 3):
|
||||
args['default_vals'] = [pin_params['initial_value']]
|
||||
else:
|
||||
args['default_val'] = pin_params['initial_value']
|
||||
line.request(**args)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Unable to init {full_name}. Make sure the gpio is not in "
|
||||
"use by another program or exported by sysfs.")
|
||||
raise
|
||||
return line
|
||||
|
||||
def _parse_pin(self,
|
||||
pin_name: str,
|
||||
type: str = "out"
|
||||
) -> Dict[str, Any]:
|
||||
params: Dict[str, Any] = {
|
||||
'orig': pin_name,
|
||||
'invert': False,
|
||||
}
|
||||
pin = pin_name
|
||||
if type == "event":
|
||||
params['request_type'] = self.gpiod.LINE_REQ_EV_BOTH_EDGES
|
||||
flag: str = "disable"
|
||||
if pin[0] == "^":
|
||||
pin = pin[1:]
|
||||
flag = "pullup"
|
||||
elif pin[0] == "~":
|
||||
pin = pin[1:]
|
||||
flag = "pulldown"
|
||||
if self.gpiod_version >= (1, 5):
|
||||
flag_to_enum = {
|
||||
"disable": self.gpiod.LINE_REQ_FLAG_BIAS_DISABLE,
|
||||
"pullup": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_UP,
|
||||
"pulldown": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_DOWN
|
||||
}
|
||||
params['flags'] = flag_to_enum[flag]
|
||||
elif flag != "disable":
|
||||
raise self.server.error(
|
||||
f"Flag {flag} configured for event GPIO '{pin_name}'"
|
||||
" requires libgpiod version 1.5 or later. "
|
||||
f"Current Version: {self.gpiod.version_string()}")
|
||||
elif type == "out":
|
||||
params['request_type'] = self.gpiod.LINE_REQ_DIR_OUT
|
||||
if pin[0] == "!":
|
||||
pin = pin[1:]
|
||||
params['invert'] = True
|
||||
if 'flags' in params:
|
||||
params['flags'] |= self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
|
||||
else:
|
||||
params['flags'] = self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
|
||||
chip_id: str = "gpiochip0"
|
||||
pin_parts = pin.split("/")
|
||||
if len(pin_parts) == 2:
|
||||
chip_id, pin = pin_parts
|
||||
elif len(pin_parts) == 1:
|
||||
pin = pin_parts[0]
|
||||
# Verify pin
|
||||
if not chip_id.startswith("gpiochip") or \
|
||||
not chip_id[-1].isdigit() or \
|
||||
not pin.startswith("gpio") or \
|
||||
not pin[4:].isdigit():
|
||||
raise self.server.error(
|
||||
f"Invalid Gpio Pin: {pin_name}")
|
||||
pin_id = int(pin[4:])
|
||||
params['pin_id'] = pin_id
|
||||
params['chip_id'] = chip_id
|
||||
params['full_name'] = f"{chip_id}:{pin}"
|
||||
return params
|
||||
|
||||
def close(self) -> None:
|
||||
for line in self.reserved_gpios.values():
|
||||
line.release()
|
||||
for chip in self.chips.values():
|
||||
chip.close()
|
||||
|
||||
class GpioBase:
|
||||
def __init__(self,
|
||||
line: Any,
|
||||
pin_params: Dict[str, Any]
|
||||
) -> None:
|
||||
self.orig: str = pin_params['orig']
|
||||
self.name: str = pin_params['full_name']
|
||||
self.inverted: bool = pin_params['invert']
|
||||
self.line: Any = line
|
||||
self.value: int = pin_params.get('initial_value', 0)
|
||||
|
||||
def release(self) -> None:
|
||||
self.line.release()
|
||||
|
||||
def is_inverted(self) -> bool:
|
||||
return self.inverted
|
||||
|
||||
def get_value(self) -> int:
|
||||
return self.value
|
||||
|
||||
def get_name(self) -> str:
|
||||
return self.name
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.orig
|
||||
|
||||
class GpioOutputPin(GpioBase):
|
||||
def write(self, value: int) -> None:
|
||||
self.value = int(not not value)
|
||||
self.line.set_value(self.value)
|
||||
|
||||
|
||||
MAX_ERRORS = 50
|
||||
ERROR_RESET_TIME = 5.
|
||||
|
||||
class GpioEvent(GpioBase):
|
||||
EVENT_FALLING_EDGE = 0
|
||||
EVENT_RISING_EDGE = 1
|
||||
def __init__(self,
|
||||
event_loop: EventLoop,
|
||||
line: Any,
|
||||
pin_params: Dict[str, Any],
|
||||
callback: GPIO_CALLBACK
|
||||
) -> None:
|
||||
super().__init__(line, pin_params)
|
||||
self.event_loop = event_loop
|
||||
self.fd = line.event_get_fd()
|
||||
self.callback = callback
|
||||
self.on_error: Optional[Callable[[str], None]] = None
|
||||
self.min_evt_time = 0.
|
||||
self.last_event_time = 0.
|
||||
self.error_count = 0
|
||||
self.last_error_reset = 0.
|
||||
self.started = False
|
||||
|
||||
@classmethod
|
||||
def init_constants(cls, gpiod: Any) -> None:
|
||||
cls.EVENT_RISING_EDGE = gpiod.LineEvent.RISING_EDGE
|
||||
cls.EVENT_FALLING_EDGE = gpiod.LineEvent.FALLING_EDGE
|
||||
|
||||
def setup_debounce(self,
|
||||
min_evt_time: float,
|
||||
err_callback: Optional[Callable[[str], None]]
|
||||
) -> None:
|
||||
self.min_evt_time = max(min_evt_time, 0.)
|
||||
self.on_error = err_callback
|
||||
|
||||
def start(self) -> None:
|
||||
if not self.started:
|
||||
self.value = self.line.get_value()
|
||||
self.last_event_time = self.event_loop.get_loop_time()
|
||||
self.event_loop.add_reader(self.fd, self._on_event_trigger)
|
||||
self.started = True
|
||||
logging.debug(f"GPIO {self.name}: Listening for events, "
|
||||
f"current state: {self.value}")
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.started:
|
||||
self.event_loop.remove_reader(self.fd)
|
||||
self.started = False
|
||||
|
||||
def release(self) -> None:
|
||||
self.stop()
|
||||
self.line.release()
|
||||
|
||||
def _on_event_trigger(self) -> None:
|
||||
evt = self.line.event_read()
|
||||
last_val = self.value
|
||||
if evt.type == self.EVENT_RISING_EDGE:
|
||||
self.value = 1
|
||||
elif evt.type == self.EVENT_FALLING_EDGE:
|
||||
self.value = 0
|
||||
eventtime = self.event_loop.get_loop_time()
|
||||
evt_duration = eventtime - self.last_event_time
|
||||
if last_val == self.value or evt_duration < self.min_evt_time:
|
||||
self._increment_error(eventtime)
|
||||
return
|
||||
self.last_event_time = eventtime
|
||||
self.error_count = 0
|
||||
ret = self.callback(eventtime, evt_duration, self.value)
|
||||
if ret is not None:
|
||||
self.event_loop.create_task(ret) # type: ignore
|
||||
|
||||
def _increment_error(self, eventtime: float) -> None:
|
||||
if eventtime - self.last_error_reset > ERROR_RESET_TIME:
|
||||
self.error_count = 0
|
||||
self.last_error_reset = eventtime
|
||||
self.error_count += 1
|
||||
if self.error_count >= MAX_ERRORS:
|
||||
self.stop()
|
||||
if self.on_error is not None:
|
||||
self.on_error("Too Many Consecutive Errors, "
|
||||
f"GPIO Event Disabled on {self.name}")
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> GpioFactory:
|
||||
return GpioFactory(config)
|
||||
@@ -0,0 +1,401 @@
|
||||
# History cache for printer jobs
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import time
|
||||
import logging
|
||||
from asyncio import Lock
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .database import MoonrakerDatabase as DBComp
|
||||
from .job_state import JobState
|
||||
from .file_manager.file_manager import FileManager
|
||||
|
||||
HIST_NAMESPACE = "history"
|
||||
MAX_JOBS = 10000
|
||||
|
||||
class History:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.file_manager: FileManager = self.server.lookup_component(
|
||||
'file_manager')
|
||||
self.request_lock = Lock()
|
||||
database: DBComp = self.server.lookup_component("database")
|
||||
self.job_totals: Dict[str, float] = 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.
|
||||
}).result()
|
||||
|
||||
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_event_handler(
|
||||
"job_state:started", self._on_job_started)
|
||||
self.server.register_event_handler(
|
||||
"job_state:complete", self._on_job_complete)
|
||||
self.server.register_event_handler(
|
||||
"job_state:cancelled", self._on_job_cancelled)
|
||||
self.server.register_event_handler(
|
||||
"job_state:standby", self._on_job_standby)
|
||||
self.server.register_event_handler(
|
||||
"job_state:error", self._on_job_error)
|
||||
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)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/reset_totals", ['POST'],
|
||||
self._handle_job_total_reset)
|
||||
|
||||
database.register_local_namespace(HIST_NAMESPACE)
|
||||
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
|
||||
parse_keys=False)
|
||||
|
||||
self.current_job: Optional[PrinterJob] = None
|
||||
self.current_job_id: Optional[str] = None
|
||||
self.next_job_id: int = 0
|
||||
self.cached_job_ids = self.history_ns.keys().result()
|
||||
if self.cached_job_ids:
|
||||
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
|
||||
|
||||
async def _handle_job_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
async with self.request_lock:
|
||||
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 = await 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]}
|
||||
raise self.server.error("Invalid Request Method")
|
||||
|
||||
async def _handle_jobs_list(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
async with self.request_lock:
|
||||
i = 0
|
||||
count = 0
|
||||
end_num = len(self.cached_job_ids)
|
||||
jobs: List[Dict[str, Any]] = []
|
||||
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)
|
||||
order = web_request.get_str("order", "desc")
|
||||
|
||||
if order not in ["asc", "desc"]:
|
||||
raise self.server.error(f"Invalid `order` value: {order}", 400)
|
||||
|
||||
reverse_order = (order == "desc")
|
||||
|
||||
# cached jobs is asc order, find lower and upper boundary
|
||||
if since != -1:
|
||||
while start_num < end_num:
|
||||
job_id = self.cached_job_ids[start_num]
|
||||
job: Dict[str, Any] = await self.history_ns[job_id]
|
||||
if job['start_time'] > since:
|
||||
break
|
||||
start_num += 1
|
||||
|
||||
if before != -1:
|
||||
while end_num > 0:
|
||||
job_id = self.cached_job_ids[end_num-1]
|
||||
job = await self.history_ns[job_id]
|
||||
if job['end_time'] < before:
|
||||
break
|
||||
end_num -= 1
|
||||
|
||||
if start_num >= end_num or end_num == 0:
|
||||
return {"count": 0, "jobs": []}
|
||||
|
||||
i = start
|
||||
count = end_num - start_num
|
||||
|
||||
if limit == 0:
|
||||
limit = MAX_JOBS
|
||||
|
||||
while i < count and len(jobs) < limit:
|
||||
if reverse_order:
|
||||
job_id = self.cached_job_ids[end_num - i - 1]
|
||||
else:
|
||||
job_id = self.cached_job_ids[start_num + i]
|
||||
job = await self.history_ns[job_id]
|
||||
jobs.append(self._prep_requested_job(job, job_id))
|
||||
i += 1
|
||||
|
||||
return {"count": count, "jobs": jobs}
|
||||
|
||||
async def _handle_job_totals(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, float]]:
|
||||
return {'job_totals': self.job_totals}
|
||||
|
||||
async def _handle_job_total_reset(self,
|
||||
web_request: WebRequest,
|
||||
) -> Dict[str, Dict[str, float]]:
|
||||
if self.current_job is not None:
|
||||
raise self.server.error(
|
||||
"Job in progress, cannot reset totals")
|
||||
last_totals = dict(self.job_totals)
|
||||
self.job_totals = {
|
||||
'total_jobs': 0,
|
||||
'total_time': 0.,
|
||||
'total_print_time': 0.,
|
||||
'total_filament_used': 0.,
|
||||
'longest_job': 0.,
|
||||
'longest_print': 0.
|
||||
}
|
||||
database: DBComp = self.server.lookup_component("database")
|
||||
await database.insert_item(
|
||||
"moonraker", "history.job_totals", self.job_totals)
|
||||
return {'last_totals': last_totals}
|
||||
|
||||
def _on_job_started(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
if self.current_job is not None:
|
||||
# Finish with the previous state
|
||||
self.finish_job("cancelled", prev_stats)
|
||||
self.add_job(PrinterJob(new_stats))
|
||||
|
||||
def _on_job_complete(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
self.finish_job("completed", new_stats)
|
||||
|
||||
def _on_job_cancelled(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
self.finish_job("cancelled", new_stats)
|
||||
|
||||
def _on_job_error(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
self.finish_job("error", new_stats)
|
||||
|
||||
def _on_job_standby(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
# Backward compatibility with
|
||||
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
|
||||
self.finish_job("cancelled", prev_stats)
|
||||
|
||||
def _handle_shutdown(self) -> None:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
self.finish_job("klippy_shutdown", last_ps)
|
||||
|
||||
def _handle_disconnect(self) -> None:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
self.finish_job("klippy_disconnect", last_ps)
|
||||
|
||||
def add_job(self, job: PrinterJob) -> None:
|
||||
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
|
||||
logging.debug(
|
||||
f"History Job Added - Id: {job_id}, File: {job.filename}"
|
||||
)
|
||||
self.send_history_event("added")
|
||||
|
||||
def delete_job(self, job_id: Union[int, str]) -> None:
|
||||
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: str, pstats: Dict[str, Any]) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
cj = self.current_job
|
||||
if (
|
||||
pstats.get('filename') != cj.get('filename') or
|
||||
pstats.get('total_duration', 0.) < cj.get('total_duration')
|
||||
):
|
||||
# Print stats have been reset, do not update this job with them
|
||||
pstats = {}
|
||||
|
||||
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()
|
||||
logging.debug(
|
||||
f"History Job Finished - Id: {self.current_job_id}, "
|
||||
f"File: {self.current_job.filename}, "
|
||||
f"Status: {status}"
|
||||
)
|
||||
self.send_history_event("finished")
|
||||
self.current_job = None
|
||||
self.current_job_id = None
|
||||
|
||||
async def get_job(self,
|
||||
job_id: Union[int, str]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if isinstance(job_id, int):
|
||||
job_id = f"{job_id:06X}"
|
||||
return await self.history_ns.get(job_id, None)
|
||||
|
||||
def grab_job_metadata(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
filename: str = self.current_job.get("filename")
|
||||
mdst = self.file_manager.get_metadata_storage()
|
||||
metadata: Dict[str, Any] = mdst.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
|
||||
})
|
||||
mdst.insert(filename, metadata.copy())
|
||||
# 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:
|
||||
thumb: Dict[str, Any]
|
||||
for thumb in metadata['thumbnails']:
|
||||
thumb.pop('data', None)
|
||||
self.current_job.set("metadata", metadata)
|
||||
|
||||
def save_current_job(self) -> None:
|
||||
if self.current_job is None or self.current_job_id is None:
|
||||
return
|
||||
self.history_ns[self.current_job_id] = self.current_job.get_stats()
|
||||
|
||||
def _update_job_totals(self) -> None:
|
||||
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: DBComp = self.server.lookup_component("database")
|
||||
database.insert_item(
|
||||
"moonraker", "history.job_totals", self.job_totals)
|
||||
|
||||
def send_history_event(self, evt_action: str) -> None:
|
||||
if self.current_job is None or self.current_job_id is None:
|
||||
return
|
||||
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: Dict[str, Any],
|
||||
job_id: str
|
||||
) -> Dict[str, Any]:
|
||||
job['job_id'] = job_id
|
||||
job['exists'] = self.file_manager.check_file_exists(
|
||||
"gcodes", job['filename'])
|
||||
return job
|
||||
|
||||
def on_exit(self) -> None:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
self.finish_job("server_exit", last_ps)
|
||||
|
||||
class PrinterJob:
|
||||
def __init__(self, data: Dict[str, Any] = {}) -> None:
|
||||
self.end_time: Optional[float] = None
|
||||
self.filament_used: float = 0
|
||||
self.filename: Optional[str] = None
|
||||
self.metadata: Optional[Dict[str, Any]] = None
|
||||
self.print_duration: float = 0.
|
||||
self.status: str = "in_progress"
|
||||
self.start_time = time.time()
|
||||
self.total_duration: float = 0.
|
||||
self.update_from_ps(data)
|
||||
|
||||
def finish(self,
|
||||
status: str,
|
||||
print_stats: Dict[str, Any] = {}
|
||||
) -> None:
|
||||
self.end_time = time.time()
|
||||
self.status = status
|
||||
self.update_from_ps(print_stats)
|
||||
|
||||
def get(self, name: str) -> Any:
|
||||
if not hasattr(self, name):
|
||||
return None
|
||||
return getattr(self, name)
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
return self.__dict__.copy()
|
||||
|
||||
def set(self, name: str, val: Any) -> None:
|
||||
if not hasattr(self, name):
|
||||
return
|
||||
setattr(self, name, val)
|
||||
|
||||
def update_from_ps(self, data: Dict[str, Any]) -> None:
|
||||
for i in data:
|
||||
if hasattr(self, i):
|
||||
setattr(self, i, data[i])
|
||||
|
||||
def load_component(config: ConfigHelper) -> History:
|
||||
return History(config)
|
||||
@@ -0,0 +1,470 @@
|
||||
# Wrapper around Tornado's HTTP Client with a "requests-like" interface
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
import pathlib
|
||||
import tempfile
|
||||
import logging
|
||||
from ..utils import ServerError
|
||||
from tornado.escape import url_escape, url_unescape
|
||||
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError
|
||||
from tornado.httputil import HTTPHeaders
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Callable,
|
||||
Optional,
|
||||
Tuple,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
Any
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..server import Server
|
||||
from ..confighelper import ConfigHelper
|
||||
from io import BufferedWriter
|
||||
StrOrPath = Union[str, pathlib.Path]
|
||||
|
||||
MAX_BODY_SIZE = 512 * 1024 * 1024
|
||||
AsyncHTTPClient.configure(
|
||||
None, defaults=dict(user_agent="Moonraker"),
|
||||
max_body_size=MAX_BODY_SIZE
|
||||
)
|
||||
|
||||
GITHUB_PREFIX = "https://api.github.com/"
|
||||
|
||||
class HttpClient:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.client = AsyncHTTPClient()
|
||||
self.response_cache: Dict[str, HttpResponse] = {}
|
||||
|
||||
self.gh_rate_limit: Optional[int] = None
|
||||
self.gh_limit_remaining: Optional[int] = None
|
||||
self.gh_limit_reset_time: Optional[float] = None
|
||||
|
||||
def register_cached_url(
|
||||
self,
|
||||
url: str,
|
||||
etag: Optional[str] = None,
|
||||
last_modified: Optional[str] = None
|
||||
) -> None:
|
||||
headers = HTTPHeaders()
|
||||
if etag is not None:
|
||||
headers["etag"] = etag
|
||||
if last_modified is not None:
|
||||
headers["last-modified"] = last_modified
|
||||
if len(headers) == 0:
|
||||
raise self.server.error(
|
||||
"Either an Etag or Last Modified Date must be specified")
|
||||
empty_resp = HttpResponse(url, url, 200, b"", headers, None)
|
||||
self.response_cache[url] = empty_resp
|
||||
|
||||
async def request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
body: Optional[Union[str, List[Any], Dict[str, Any]]] = None,
|
||||
headers: Optional[Dict[str, Any]] = None,
|
||||
connect_timeout: float = 5.,
|
||||
request_timeout: float = 10.,
|
||||
attempts: int = 1,
|
||||
retry_pause_time: float = .1,
|
||||
enable_cache: bool = False,
|
||||
send_etag: bool = True,
|
||||
send_if_modified_since: bool = True
|
||||
) -> HttpResponse:
|
||||
cache_key = url.split("?", 1)[0]
|
||||
method = method.upper()
|
||||
# prepare the body if required
|
||||
req_headers: Dict[str, Any] = {}
|
||||
if isinstance(body, (list, dict)):
|
||||
body = json.dumps(body)
|
||||
req_headers["Content-Type"] = "application/json"
|
||||
cached: Optional[HttpResponse] = None
|
||||
if enable_cache:
|
||||
cached = self.response_cache.get(cache_key)
|
||||
if cached is not None and send_etag:
|
||||
if cached.etag is not None and send_etag:
|
||||
req_headers["If-None-Match"] = cached.etag
|
||||
if cached.last_modified and send_if_modified_since:
|
||||
req_headers["If-Modified-Since"] = cached.last_modified
|
||||
if headers is not None:
|
||||
headers.update(req_headers)
|
||||
elif req_headers:
|
||||
headers = req_headers
|
||||
|
||||
timeout = 1 + connect_timeout + request_timeout
|
||||
request = HTTPRequest(url, method, headers, body=body,
|
||||
request_timeout=request_timeout,
|
||||
connect_timeout=connect_timeout)
|
||||
err: Optional[BaseException] = None
|
||||
for i in range(attempts):
|
||||
if i:
|
||||
await asyncio.sleep(retry_pause_time)
|
||||
try:
|
||||
fut = self.client.fetch(request, raise_error=False)
|
||||
resp = await asyncio.wait_for(fut, timeout)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
err = e
|
||||
else:
|
||||
err = resp.error
|
||||
if resp.code == 304:
|
||||
err = None
|
||||
if cached is None:
|
||||
if enable_cache:
|
||||
logging.info(
|
||||
"Request returned 304, however no cached "
|
||||
"item was found")
|
||||
result = b""
|
||||
else:
|
||||
logging.debug(f"Request returned from cache: {url}")
|
||||
result = cached.content
|
||||
elif resp.error is not None and attempts - i != 1:
|
||||
continue
|
||||
else:
|
||||
result = resp.body
|
||||
ret = HttpResponse(
|
||||
url, resp.effective_url, resp.code, result,
|
||||
resp.headers, err
|
||||
)
|
||||
break
|
||||
else:
|
||||
ret = HttpResponse(url, url, 500, b"", HTTPHeaders(), err)
|
||||
if enable_cache and ret.is_cachable():
|
||||
logging.debug(f"Caching HTTP Response: {url}")
|
||||
self.response_cache[cache_key] = ret
|
||||
else:
|
||||
self.response_cache.pop(cache_key, None)
|
||||
return ret
|
||||
|
||||
async def get(
|
||||
self, url: str, headers: Optional[Dict[str, Any]] = None, **kwargs
|
||||
) -> HttpResponse:
|
||||
if "enable_cache" not in kwargs:
|
||||
kwargs["enable_cache"] = True
|
||||
return await self.request("GET", url, None, headers, **kwargs)
|
||||
|
||||
async def post(
|
||||
self,
|
||||
url: str,
|
||||
body: Union[str, List[Any], Dict[str, Any]] = "",
|
||||
headers: Optional[Dict[str, Any]] = None,
|
||||
**kwargs
|
||||
) -> HttpResponse:
|
||||
return await self.request("POST", url, body, headers, **kwargs)
|
||||
|
||||
async def delete(
|
||||
self,
|
||||
url: str,
|
||||
headers: Optional[Dict[str, Any]] = None,
|
||||
**kwargs
|
||||
) -> HttpResponse:
|
||||
return await self.request("DELETE", url, None, headers, **kwargs)
|
||||
|
||||
async def github_api_request(
|
||||
self,
|
||||
resource: str,
|
||||
attempts: int = 1,
|
||||
retry_pause_time: float = .1
|
||||
) -> HttpResponse:
|
||||
url = f"{GITHUB_PREFIX}{resource.strip('/')}"
|
||||
if (
|
||||
self.gh_limit_reset_time is not None and
|
||||
self.gh_limit_remaining == 0
|
||||
):
|
||||
curtime = time.time()
|
||||
if curtime < self.gh_limit_reset_time:
|
||||
reset_time = time.ctime(self.gh_limit_reset_time)
|
||||
raise self.server.error(
|
||||
f"GitHub Rate Limit Reached\n"
|
||||
f"Request: {url}\n"
|
||||
f"Limit Reset Time: {reset_time}"
|
||||
)
|
||||
headers = {"Accept": "application/vnd.github.v3+json"}
|
||||
resp = await self.get(
|
||||
url, headers, attempts=attempts,
|
||||
retry_pause_time=retry_pause_time)
|
||||
resp_hdrs = resp.headers
|
||||
if 'X-Ratelimit-Limit' in resp_hdrs:
|
||||
self.gh_rate_limit = int(resp_hdrs['X-Ratelimit-Limit'])
|
||||
self.gh_limit_remaining = int(
|
||||
resp_hdrs['X-Ratelimit-Remaining'])
|
||||
self.gh_limit_reset_time = float(
|
||||
resp_hdrs['X-Ratelimit-Reset'])
|
||||
return resp
|
||||
|
||||
def github_api_stats(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'github_rate_limit': self.gh_rate_limit,
|
||||
'github_requests_remaining': self.gh_limit_remaining,
|
||||
'github_limit_reset_time': self.gh_limit_reset_time,
|
||||
}
|
||||
|
||||
async def get_file(
|
||||
self,
|
||||
url: str,
|
||||
content_type: str,
|
||||
connect_timeout: float = 5.,
|
||||
request_timeout: float = 180.,
|
||||
attempts: int = 1,
|
||||
retry_pause_time: float = .1,
|
||||
enable_cache: bool = False,
|
||||
) -> bytes:
|
||||
headers = {"Accept": content_type}
|
||||
resp = await self.get(
|
||||
url, headers, connect_timeout=connect_timeout,
|
||||
request_timeout=request_timeout, attempts=attempts,
|
||||
retry_pause_time=retry_pause_time, enable_cache=enable_cache
|
||||
)
|
||||
resp.raise_for_status()
|
||||
return resp.content
|
||||
|
||||
async def download_file(
|
||||
self,
|
||||
url: str,
|
||||
content_type: str,
|
||||
destination_path: Optional[StrOrPath] = None,
|
||||
download_size: int = -1,
|
||||
progress_callback: Optional[Callable[[int, int, int], None]] = None,
|
||||
connect_timeout: float = 5.,
|
||||
request_timeout: float = 180.,
|
||||
attempts: int = 1,
|
||||
retry_pause_time: float = 1.
|
||||
) -> pathlib.Path:
|
||||
for i in range(attempts):
|
||||
dl = StreamingDownload(
|
||||
self.server, destination_path, download_size,
|
||||
progress_callback)
|
||||
try:
|
||||
fut = self.client.fetch(
|
||||
url, headers={"Accept": content_type},
|
||||
connect_timeout=connect_timeout,
|
||||
request_timeout=request_timeout,
|
||||
streaming_callback=dl.on_chunk_recd,
|
||||
header_callback=dl.on_headers_recd)
|
||||
timeout = connect_timeout + request_timeout + 1.
|
||||
resp = await asyncio.wait_for(fut, timeout)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
if i + 1 == attempts:
|
||||
raise
|
||||
await asyncio.sleep(retry_pause_time)
|
||||
continue
|
||||
finally:
|
||||
await dl.close()
|
||||
if resp.code < 400:
|
||||
return dl.dest_file
|
||||
raise self.server.error(f"Retries exceeded for request: {url}")
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
class HttpResponse:
|
||||
def __init__(self,
|
||||
url: str,
|
||||
final_url: str,
|
||||
code: int,
|
||||
result: bytes,
|
||||
response_headers: HTTPHeaders,
|
||||
error: Optional[BaseException]
|
||||
) -> None:
|
||||
self._url = url
|
||||
self._final_url = final_url
|
||||
self._code = code
|
||||
self._result: bytes = result
|
||||
self._encoding: str = "utf-8"
|
||||
self._response_headers: HTTPHeaders = response_headers
|
||||
self._etag: Optional[str] = response_headers.get("etag", None)
|
||||
self._error = error
|
||||
self._last_modified: Optional[str] = response_headers.get(
|
||||
"last-modified", None)
|
||||
|
||||
def json(self, **kwargs) -> Union[List[Any], Dict[str, Any]]:
|
||||
return json.loads(self._result, **kwargs)
|
||||
|
||||
def is_cachable(self) -> bool:
|
||||
return self._last_modified is not None or self._etag is not None
|
||||
|
||||
def has_error(self) -> bool:
|
||||
return self._error is not None
|
||||
|
||||
def raise_for_status(self, message: Optional[str] = None) -> None:
|
||||
if self._error is not None:
|
||||
code = 500
|
||||
msg = f"HTTP Request Error: {self.url}"
|
||||
if isinstance(self._error, HTTPError):
|
||||
code = self._code
|
||||
if self._error.message is not None:
|
||||
msg = self._error.message
|
||||
if message is not None:
|
||||
msg = message
|
||||
raise ServerError(msg, code) from self._error
|
||||
|
||||
@property
|
||||
def encoding(self) -> str:
|
||||
return self._encoding
|
||||
|
||||
@encoding.setter
|
||||
def encoding(self, new_enc: str) -> None:
|
||||
self._encoding = new_enc
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self._result.decode(encoding=self._encoding)
|
||||
|
||||
@property
|
||||
def content(self) -> bytes:
|
||||
return self._result
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return self._url
|
||||
|
||||
@property
|
||||
def final_url(self) -> str:
|
||||
return self._final_url
|
||||
|
||||
@property
|
||||
def status_code(self) -> int:
|
||||
return self._code
|
||||
|
||||
@property
|
||||
def headers(self) -> HTTPHeaders:
|
||||
return self._response_headers
|
||||
|
||||
@property
|
||||
def last_modified(self) -> Optional[str]:
|
||||
return self._last_modified
|
||||
|
||||
@property
|
||||
def etag(self) -> Optional[str]:
|
||||
return self._etag
|
||||
|
||||
@property
|
||||
def error(self) -> Optional[BaseException]:
|
||||
return self._error
|
||||
|
||||
class StreamingDownload:
|
||||
def __init__(
|
||||
self,
|
||||
server: Server,
|
||||
dest_path: Optional[StrOrPath],
|
||||
download_size: int,
|
||||
progress_callback: Optional[Callable[[int, int, int], None]]
|
||||
) -> None:
|
||||
self.server = server
|
||||
self.event_loop = server.get_event_loop()
|
||||
self.need_content_length: bool = True
|
||||
self.need_content_disposition: bool = False
|
||||
self.request_ok: bool = False
|
||||
if dest_path is None:
|
||||
# If no destination is provided initialize to a procedurally
|
||||
# generated temp file. We will attempt to extract the filename
|
||||
# from the Content-Disposition Header
|
||||
tmp_dir = tempfile.gettempdir()
|
||||
loop_time = int(self.event_loop.get_loop_time())
|
||||
tmp_fname = f"moonraker.download-{loop_time}.mrd"
|
||||
self.dest_file = pathlib.Path(tmp_dir).joinpath(tmp_fname)
|
||||
self.need_content_disposition = True
|
||||
elif isinstance(dest_path, str):
|
||||
self.dest_file = pathlib.Path(dest_path)
|
||||
else:
|
||||
self.dest_file = dest_path
|
||||
self.filename = self.dest_file.name
|
||||
self.file_hdl: Optional[BufferedWriter] = None
|
||||
self.total_recd: int = 0
|
||||
self.download_size: int = download_size
|
||||
self.pct_done: int = 0
|
||||
self.chunk_buffer: List[bytes] = []
|
||||
self.progress_callback = progress_callback
|
||||
self.busy_evt: asyncio.Event = asyncio.Event()
|
||||
self.busy_evt.set()
|
||||
|
||||
def on_headers_recd(self, line: str) -> None:
|
||||
if not self.need_content_length and not self.need_content_disposition:
|
||||
return
|
||||
line = line.strip()
|
||||
rc_match = re.match(r"HTTP/\d.?\d? (\d+)", line)
|
||||
if rc_match is not None:
|
||||
self.request_ok = rc_match.group(1) == "200"
|
||||
return
|
||||
if not self.request_ok:
|
||||
return
|
||||
parts = line.split(":", 1)
|
||||
if len(parts) < 2:
|
||||
return
|
||||
hname = parts[0].strip().lower()
|
||||
hval = parts[1].strip()
|
||||
if hname == "content-length" and self.need_content_length:
|
||||
self.download_size = int(hval)
|
||||
self.need_content_length = False
|
||||
logging.debug(
|
||||
f"Content-Length header received: "
|
||||
f"size = {self.download_size}")
|
||||
elif (
|
||||
hname == "content-disposition" and
|
||||
self.need_content_disposition
|
||||
):
|
||||
fnr = r"filename[^;\n=]*=(['\"])?(utf-8\'\')?([^\n;]*)(?(1)\1|)"
|
||||
matches: List[Tuple[str, str, str]] = re.findall(fnr, hval)
|
||||
is_utf8 = False
|
||||
for (_, encoding, fname) in matches:
|
||||
if encoding.startswith("utf-8"):
|
||||
# Prefer the utf8 filename if included
|
||||
self.filename = url_unescape(
|
||||
fname, encoding="utf-8", plus=False)
|
||||
is_utf8 = True
|
||||
break
|
||||
self.filename = fname
|
||||
self.need_content_disposition = False
|
||||
# Use the filename extracted from the content-disposition header
|
||||
self.dest_file = self.dest_file.parent.joinpath(self.filename)
|
||||
logging.debug(
|
||||
"Content-Disposition header received: filename = "
|
||||
f"{self.filename}, utf8: {is_utf8}")
|
||||
|
||||
def on_chunk_recd(self, chunk: bytes) -> None:
|
||||
if not chunk:
|
||||
return
|
||||
self.chunk_buffer.append(chunk)
|
||||
if not self.busy_evt.is_set():
|
||||
return
|
||||
self.busy_evt.clear()
|
||||
self.event_loop.register_callback(self._process_buffer)
|
||||
|
||||
async def close(self):
|
||||
await self.busy_evt.wait()
|
||||
if self.file_hdl is not None:
|
||||
await self.event_loop.run_in_thread(self.file_hdl.close)
|
||||
|
||||
async def _process_buffer(self):
|
||||
if self.file_hdl is None:
|
||||
self.file_hdl = await self.event_loop.run_in_thread(
|
||||
self.dest_file.open, "wb")
|
||||
while self.chunk_buffer:
|
||||
chunk = self.chunk_buffer.pop(0)
|
||||
await self.event_loop.run_in_thread(self.file_hdl.write, chunk)
|
||||
self.total_recd += len(chunk)
|
||||
if self.download_size > 0 and self.progress_callback is not None:
|
||||
pct = int(self.total_recd / self.download_size * 100 + .5)
|
||||
pct = min(100, pct)
|
||||
if pct != self.pct_done:
|
||||
self.pct_done = pct
|
||||
self.progress_callback(
|
||||
pct, self.download_size, self.total_recd)
|
||||
self.busy_evt.set()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> HttpClient:
|
||||
return HttpClient(config)
|
||||
@@ -0,0 +1,337 @@
|
||||
# Print Job Queue Implementation
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import time
|
||||
import logging
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Union,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .klippy_apis import KlippyAPI
|
||||
from .file_manager.file_manager import FileManager
|
||||
|
||||
class JobQueue:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.queued_jobs: Dict[str, QueuedJob] = {}
|
||||
self.lock = asyncio.Lock()
|
||||
self.load_on_start = config.getboolean("load_on_startup", False)
|
||||
self.automatic = config.getboolean("automatic_transition", False)
|
||||
self.queue_state: str = "ready" if self.automatic else "paused"
|
||||
self.job_delay = config.getfloat("job_transition_delay", 0.01)
|
||||
if self.job_delay <= 0.:
|
||||
raise config.error(
|
||||
"Value for option 'job_transition_delay' in section [job_queue]"
|
||||
" must be above 0.0")
|
||||
self.job_transition_gcode = config.get(
|
||||
"job_transition_gcode", "").strip()
|
||||
self.pop_queue_handle: Optional[asyncio.TimerHandle] = None
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._handle_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_shutdown)
|
||||
self.server.register_event_handler(
|
||||
"job_state:complete", self._on_job_complete)
|
||||
self.server.register_event_handler(
|
||||
"job_state:error", self._on_job_abort)
|
||||
self.server.register_event_handler(
|
||||
"job_state:cancelled", self._on_job_abort)
|
||||
|
||||
self.server.register_notification("job_queue:job_queue_changed")
|
||||
self.server.register_remote_method("pause_job_queue", self.pause_queue)
|
||||
self.server.register_remote_method("start_job_queue",
|
||||
self.start_queue)
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/job", ['POST', 'DELETE'],
|
||||
self._handle_job_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/pause", ['POST'], self._handle_pause_queue)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/start", ['POST'], self._handle_start_queue)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/status", ['GET'], self._handle_queue_status)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/jump", ['POST'], self._handle_jump)
|
||||
|
||||
async def _handle_ready(self) -> None:
|
||||
async with self.lock:
|
||||
if not self.load_on_start or not self.queued_jobs:
|
||||
return
|
||||
# start a queued print
|
||||
if self.queue_state in ['ready', 'paused']:
|
||||
event_loop = self.server.get_event_loop()
|
||||
self._set_queue_state("loading")
|
||||
self.pop_queue_handle = event_loop.delay_callback(
|
||||
1., self._pop_job, False)
|
||||
|
||||
async def _handle_shutdown(self) -> None:
|
||||
await self.pause_queue()
|
||||
if not self.queued_jobs and self.automatic:
|
||||
self._set_queue_state("ready")
|
||||
|
||||
async def _on_job_complete(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
async with self.lock:
|
||||
# Transition to the next job in the queue
|
||||
if self.queue_state == "ready" and self.queued_jobs:
|
||||
event_loop = self.server.get_event_loop()
|
||||
self._set_queue_state("loading")
|
||||
self.pop_queue_handle = event_loop.delay_callback(
|
||||
self.job_delay, self._pop_job)
|
||||
|
||||
async def _on_job_abort(self,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
async with self.lock:
|
||||
if self.queued_jobs:
|
||||
self._set_queue_state("paused")
|
||||
|
||||
async def _pop_job(self, need_transition: bool = True) -> None:
|
||||
self.pop_queue_handle = None
|
||||
async with self.lock:
|
||||
if self.queue_state == "paused":
|
||||
return
|
||||
if not self.queued_jobs:
|
||||
qs = "ready" if self.automatic else "paused"
|
||||
self._set_queue_state(qs)
|
||||
return
|
||||
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
|
||||
uid, job = list(self.queued_jobs.items())[0]
|
||||
filename = str(job)
|
||||
can_print = await self._check_can_print()
|
||||
if not can_print or self.queue_state != "loading":
|
||||
self._set_queue_state("paused")
|
||||
return
|
||||
try:
|
||||
if self.job_transition_gcode and need_transition:
|
||||
await kapis.run_gcode(self.job_transition_gcode)
|
||||
# Check to see if the queue was paused while running
|
||||
# the job transition gcode
|
||||
if self.queue_state != "loading":
|
||||
raise self.server.error(
|
||||
"Queue State Changed during Transition Gcode")
|
||||
self._set_queue_state("starting")
|
||||
await kapis.start_print(filename, wait_klippy_started=True)
|
||||
except self.server.error:
|
||||
logging.exception(f"Error Loading print: {filename}")
|
||||
self._set_queue_state("paused")
|
||||
else:
|
||||
self.queued_jobs.pop(uid, None)
|
||||
if self.queue_state == "starting":
|
||||
# If the queue was not paused while starting the print,
|
||||
set_ready = not self.queued_jobs or self.automatic
|
||||
self.queue_state = "ready" if set_ready else "paused"
|
||||
self._send_queue_event(action="job_loaded")
|
||||
|
||||
async def _check_can_print(self) -> bool:
|
||||
# Query the latest stats
|
||||
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
|
||||
try:
|
||||
result = await kapis.query_objects({"print_stats": None})
|
||||
except Exception:
|
||||
# Klippy not connected
|
||||
return False
|
||||
if 'print_stats' not in result:
|
||||
return False
|
||||
state: str = result['print_stats']['state']
|
||||
if state in ["printing", "paused"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def queue_job(self,
|
||||
filenames: Union[str, List[str]],
|
||||
check_exists: bool = True,
|
||||
reset: bool = False
|
||||
) -> None:
|
||||
async with self.lock:
|
||||
# Make sure that the file exists
|
||||
if isinstance(filenames, str):
|
||||
filenames = [filenames]
|
||||
if check_exists:
|
||||
# Make sure all files exist before adding them to the queue
|
||||
for fname in filenames:
|
||||
self._check_job_file(fname)
|
||||
if reset:
|
||||
self.queued_jobs.clear()
|
||||
for fname in filenames:
|
||||
queued_job = QueuedJob(fname)
|
||||
self.queued_jobs[queued_job.job_id] = queued_job
|
||||
self._send_queue_event(action="jobs_added")
|
||||
|
||||
async def delete_job(self,
|
||||
job_ids: Union[str, List[str]],
|
||||
all: bool = False
|
||||
) -> None:
|
||||
async with self.lock:
|
||||
if not self.queued_jobs:
|
||||
# No jobs in queue, nothing to delete
|
||||
return
|
||||
if all:
|
||||
self.queued_jobs.clear()
|
||||
elif job_ids:
|
||||
if isinstance(job_ids, str):
|
||||
job_ids = [job_ids]
|
||||
for uid in job_ids:
|
||||
self.queued_jobs.pop(uid, None)
|
||||
else:
|
||||
# Don't notify, nothing was deleted
|
||||
return
|
||||
self._send_queue_event(action="jobs_removed")
|
||||
|
||||
async def pause_queue(self) -> None:
|
||||
self._set_queue_state("paused")
|
||||
if self.pop_queue_handle is not None:
|
||||
self.pop_queue_handle.cancel()
|
||||
self.pop_queue_handle = None
|
||||
# Acquire the lock to wait for any pending operations to
|
||||
# complete
|
||||
await self.lock.acquire()
|
||||
self.lock.release()
|
||||
|
||||
async def start_queue(self) -> None:
|
||||
async with self.lock:
|
||||
if self.queue_state != "loading":
|
||||
if self.queued_jobs and await self._check_can_print():
|
||||
self._set_queue_state("loading")
|
||||
event_loop = self.server.get_event_loop()
|
||||
self.pop_queue_handle = event_loop.delay_callback(
|
||||
0.01, self._pop_job)
|
||||
else:
|
||||
self._set_queue_state("ready")
|
||||
def _job_map_to_list(self) -> List[Dict[str, Any]]:
|
||||
cur_time = time.time()
|
||||
return [job.as_dict(cur_time) for
|
||||
job in self.queued_jobs.values()]
|
||||
|
||||
def _check_job_file(self, job_name: str) -> None:
|
||||
fm: FileManager = self.server.lookup_component('file_manager')
|
||||
if not fm.check_file_exists("gcodes", job_name):
|
||||
raise self.server.error(
|
||||
f"G-Code File {job_name} does not exist")
|
||||
|
||||
def _set_queue_state(self, new_state: str) -> None:
|
||||
if new_state != self.queue_state:
|
||||
self.queue_state = new_state
|
||||
self._send_queue_event()
|
||||
|
||||
def _send_queue_event(self, action: str = "state_changed"):
|
||||
updated_queue: Optional[List[Dict[str, Any]]] = None
|
||||
if action != "state_changed":
|
||||
updated_queue = self._job_map_to_list()
|
||||
event_loop = self.server.get_event_loop()
|
||||
event_loop.delay_callback(
|
||||
.05, self.server.send_event, "job_queue:job_queue_changed",
|
||||
{
|
||||
'action': action,
|
||||
'updated_queue': updated_queue,
|
||||
'queue_state': self.queue_state
|
||||
})
|
||||
|
||||
async def _handle_job_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
if action == "POST":
|
||||
files: Union[List[str], str] = web_request.get('filenames')
|
||||
reset = web_request.get_boolean("reset", False)
|
||||
if isinstance(files, str):
|
||||
files = [f.strip() for f in files.split(',') if f.strip()]
|
||||
# Validate that all files exist before queueing
|
||||
await self.queue_job(files, reset=reset)
|
||||
elif action == "DELETE":
|
||||
if web_request.get_boolean("all", False):
|
||||
await self.delete_job([], all=True)
|
||||
else:
|
||||
job_ids: Union[List[str], str] = web_request.get('job_ids')
|
||||
if isinstance(job_ids, str):
|
||||
job_ids = [f.strip() for f in job_ids.split(',')
|
||||
if f.strip()]
|
||||
await self.delete_job(job_ids)
|
||||
else:
|
||||
raise self.server.error(f"Invalid action: {action}")
|
||||
return {
|
||||
'queued_jobs': self._job_map_to_list(),
|
||||
'queue_state': self.queue_state
|
||||
}
|
||||
|
||||
async def _handle_pause_queue(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
await self.pause_queue()
|
||||
return {
|
||||
'queued_jobs': self._job_map_to_list(),
|
||||
'queue_state': self.queue_state
|
||||
}
|
||||
|
||||
async def _handle_start_queue(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
await self.start_queue()
|
||||
return {
|
||||
'queued_jobs': self._job_map_to_list(),
|
||||
'queue_state': self.queue_state
|
||||
}
|
||||
|
||||
async def _handle_queue_status(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {
|
||||
'queued_jobs': self._job_map_to_list(),
|
||||
'queue_state': self.queue_state
|
||||
}
|
||||
|
||||
async def _handle_jump(self, web_request: WebRequest) -> Dict[str, Any]:
|
||||
job_id: str = web_request.get("job_id")
|
||||
async with self.lock:
|
||||
job = self.queued_jobs.pop(job_id, None)
|
||||
if job is None:
|
||||
raise self.server.error(f"Invalid job id: {job_id}")
|
||||
new_queue = {job_id: job}
|
||||
new_queue.update(self.queued_jobs)
|
||||
self.queued_jobs = new_queue
|
||||
return {
|
||||
'queued_jobs': self._job_map_to_list(),
|
||||
'queue_state': self.queue_state
|
||||
}
|
||||
|
||||
async def close(self):
|
||||
await self.pause_queue()
|
||||
|
||||
class QueuedJob:
|
||||
def __init__(self, filename: str) -> None:
|
||||
self.filename = filename
|
||||
self.job_id = f"{id(self):016X}"
|
||||
self.time_added = time.time()
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.filename
|
||||
|
||||
def as_dict(self, cur_time: float) -> Dict[str, Any]:
|
||||
return {
|
||||
'filename': self.filename,
|
||||
'job_id': self.job_id,
|
||||
'time_added': self.time_added,
|
||||
'time_in_queue': cur_time - self.time_added
|
||||
}
|
||||
|
||||
def load_component(config: ConfigHelper) -> JobQueue:
|
||||
return JobQueue(config)
|
||||
@@ -0,0 +1,95 @@
|
||||
# Klippy job state event handlers
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .klippy_apis import KlippyAPI
|
||||
|
||||
class JobState:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.last_print_stats: Dict[str, Any] = {}
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_started", self._handle_started)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._status_update)
|
||||
|
||||
async def _handle_started(self, state: str) -> None:
|
||||
if state != "ready":
|
||||
return
|
||||
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
|
||||
sub: Dict[str, Optional[List[str]]] = {"print_stats": None}
|
||||
try:
|
||||
result = await kapis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to print_stats")
|
||||
self.last_print_stats = result.get("print_stats", {})
|
||||
if "state" in self.last_print_stats:
|
||||
state = self.last_print_stats["state"]
|
||||
logging.info(f"Job state initialized: {state}")
|
||||
|
||||
async def _status_update(self, data: Dict[str, Any]) -> None:
|
||||
if 'print_stats' not in data:
|
||||
return
|
||||
ps = data['print_stats']
|
||||
if "state" in ps:
|
||||
prev_ps = dict(self.last_print_stats)
|
||||
old_state: str = prev_ps['state']
|
||||
new_state: str = ps['state']
|
||||
new_ps = dict(self.last_print_stats)
|
||||
new_ps.update(ps)
|
||||
if new_state is not old_state:
|
||||
if new_state == "printing":
|
||||
# The "printing" state needs some special handling
|
||||
# to detect "resets" and a transition from pause to resume
|
||||
if self._check_resumed(prev_ps, new_ps):
|
||||
new_state = "resumed"
|
||||
else:
|
||||
logging.info(
|
||||
f"Job Started: {new_ps['filename']}"
|
||||
)
|
||||
new_state = "started"
|
||||
logging.debug(
|
||||
f"Job State Changed - Prev State: {old_state}, "
|
||||
f"New State: {new_state}"
|
||||
)
|
||||
self.server.send_event(
|
||||
f"job_state:{new_state}", prev_ps, new_ps)
|
||||
if "info" in ps:
|
||||
cur_layer: Optional[int] = ps["info"].get("current_layer")
|
||||
if cur_layer is not None:
|
||||
total: int = ps["info"].get("total_layer", 0)
|
||||
self.server.send_event(
|
||||
"job_state:layer_changed", cur_layer, total
|
||||
)
|
||||
self.last_print_stats.update(ps)
|
||||
|
||||
def _check_resumed(self,
|
||||
prev_ps: Dict[str, Any],
|
||||
new_ps: Dict[str, Any]
|
||||
) -> bool:
|
||||
return (
|
||||
prev_ps['state'] == "paused" and
|
||||
prev_ps['filename'] == new_ps['filename'] and
|
||||
prev_ps['total_duration'] < new_ps['total_duration']
|
||||
)
|
||||
|
||||
def get_last_stats(self) -> Dict[str, Any]:
|
||||
return dict(self.last_print_stats)
|
||||
|
||||
def load_component(config: ConfigHelper) -> JobState:
|
||||
return JobState(config)
|
||||
@@ -0,0 +1,242 @@
|
||||
# Helper for Moonraker to Klippy API calls.
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
from ..utils import Sentinel
|
||||
from ..websockets import WebRequest, Subscribable
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
TypeVar,
|
||||
Mapping,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from ..klippy_connection import KlippyConnection as Klippy
|
||||
Subscription = Dict[str, Optional[List[Any]]]
|
||||
_T = TypeVar("_T")
|
||||
|
||||
INFO_ENDPOINT = "info"
|
||||
ESTOP_ENDPOINT = "emergency_stop"
|
||||
LIST_EPS_ENDPOINT = "list_endpoints"
|
||||
GC_OUTPUT_ENDPOINT = "gcode/subscribe_output"
|
||||
GCODE_ENDPOINT = "gcode/script"
|
||||
SUBSCRIPTION_ENDPOINT = "objects/subscribe"
|
||||
STATUS_ENDPOINT = "objects/query"
|
||||
OBJ_LIST_ENDPOINT = "objects/list"
|
||||
REG_METHOD_ENDPOINT = "register_remote_method"
|
||||
|
||||
class KlippyAPI(Subscribable):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
|
||||
app_args = self.server.get_app_args()
|
||||
self.version = app_args.get('software_version')
|
||||
# Maintain a subscription for all moonraker requests, as
|
||||
# we do not want to overwrite them
|
||||
self.host_subscription: Subscription = {}
|
||||
|
||||
# Register GCode Aliases
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/pause", ['POST'], self._gcode_pause)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", ['POST'], self._gcode_resume)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", ['POST'], self._gcode_cancel)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", ['POST'], self._gcode_start_print)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", ['POST'], self._gcode_restart)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
|
||||
|
||||
async def _gcode_pause(self, web_request: WebRequest) -> str:
|
||||
return await self.pause_print()
|
||||
|
||||
async def _gcode_resume(self, web_request: WebRequest) -> str:
|
||||
return await self.resume_print()
|
||||
|
||||
async def _gcode_cancel(self, web_request: WebRequest) -> str:
|
||||
return await self.cancel_print()
|
||||
|
||||
async def _gcode_start_print(self, web_request: WebRequest) -> str:
|
||||
filename: str = web_request.get_str('filename')
|
||||
return await self.start_print(filename)
|
||||
|
||||
async def _gcode_restart(self, web_request: WebRequest) -> str:
|
||||
return await self.do_restart("RESTART")
|
||||
|
||||
async def _gcode_firmware_restart(self, web_request: WebRequest) -> str:
|
||||
return await self.do_restart("FIRMWARE_RESTART")
|
||||
|
||||
async def _send_klippy_request(
|
||||
self,
|
||||
method: str,
|
||||
params: Dict[str, Any],
|
||||
default: Any = Sentinel.MISSING
|
||||
) -> Any:
|
||||
try:
|
||||
req = WebRequest(method, params, conn=self)
|
||||
result = await self.klippy.request(req)
|
||||
except self.server.error:
|
||||
if default is Sentinel.MISSING:
|
||||
raise
|
||||
result = default
|
||||
return result
|
||||
|
||||
async def run_gcode(self,
|
||||
script: str,
|
||||
default: Any = Sentinel.MISSING
|
||||
) -> str:
|
||||
params = {'script': script}
|
||||
result = await self._send_klippy_request(
|
||||
GCODE_ENDPOINT, params, default)
|
||||
return result
|
||||
|
||||
async def start_print(
|
||||
self, filename: str, wait_klippy_started: bool = False
|
||||
) -> str:
|
||||
# WARNING: Do not call this method from within the following
|
||||
# event handlers when "wait_klippy_started" is set to True:
|
||||
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
|
||||
# Doing so will result in "wait_started" blocking for the specifed
|
||||
# timeout (default 20s) and returning False.
|
||||
# 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}"'
|
||||
if wait_klippy_started:
|
||||
await self.klippy.wait_started()
|
||||
return await self.run_gcode(script)
|
||||
|
||||
async def pause_print(
|
||||
self, default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, str]:
|
||||
self.server.send_event("klippy_apis:pause_requested")
|
||||
return await self._send_klippy_request(
|
||||
"pause_resume/pause", {}, default)
|
||||
|
||||
async def resume_print(
|
||||
self, default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, str]:
|
||||
self.server.send_event("klippy_apis:resume_requested")
|
||||
return await self._send_klippy_request(
|
||||
"pause_resume/resume", {}, default)
|
||||
|
||||
async def cancel_print(
|
||||
self, default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, str]:
|
||||
self.server.send_event("klippy_apis:cancel_requested")
|
||||
return await self._send_klippy_request(
|
||||
"pause_resume/cancel", {}, default)
|
||||
|
||||
async def do_restart(
|
||||
self, gc: str, wait_klippy_started: bool = False
|
||||
) -> str:
|
||||
# WARNING: Do not call this method from within the following
|
||||
# event handlers when "wait_klippy_started" is set to True:
|
||||
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
|
||||
# Doing so will result in "wait_started" blocking for the specifed
|
||||
# timeout (default 20s) and returning False.
|
||||
if wait_klippy_started:
|
||||
await self.klippy.wait_started()
|
||||
try:
|
||||
result = await self.run_gcode(gc)
|
||||
except self.server.error as e:
|
||||
if str(e) == "Klippy Disconnected":
|
||||
result = "ok"
|
||||
else:
|
||||
raise
|
||||
return result
|
||||
|
||||
async def list_endpoints(self,
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, Dict[str, List[str]]]:
|
||||
return await self._send_klippy_request(
|
||||
LIST_EPS_ENDPOINT, {}, default)
|
||||
|
||||
async def emergency_stop(self) -> str:
|
||||
return await self._send_klippy_request(ESTOP_ENDPOINT, {})
|
||||
|
||||
async def get_klippy_info(self,
|
||||
send_id: bool = False,
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
params = {}
|
||||
if send_id:
|
||||
ver = self.version
|
||||
params = {'client_info': {'program': "Moonraker", 'version': ver}}
|
||||
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
|
||||
|
||||
async def get_object_list(self,
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, List[str]]:
|
||||
result = await self._send_klippy_request(
|
||||
OBJ_LIST_ENDPOINT, {}, default)
|
||||
if isinstance(result, dict) and 'objects' in result:
|
||||
return result['objects']
|
||||
return result
|
||||
|
||||
async def query_objects(self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
params = {'objects': objects}
|
||||
result = await self._send_klippy_request(
|
||||
STATUS_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and 'status' in result:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_objects(self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
for obj, items in objects.items():
|
||||
if obj in self.host_subscription:
|
||||
prev = self.host_subscription[obj]
|
||||
if items is None or prev is None:
|
||||
self.host_subscription[obj] = None
|
||||
else:
|
||||
uitems = list(set(prev) | set(items))
|
||||
self.host_subscription[obj] = uitems
|
||||
else:
|
||||
self.host_subscription[obj] = items
|
||||
params = {'objects': self.host_subscription}
|
||||
result = await self._send_klippy_request(
|
||||
SUBSCRIPTION_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and 'status' in result:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_gcode_output(self) -> str:
|
||||
template = {'response_template':
|
||||
{'method': "process_gcode_response"}}
|
||||
return await self._send_klippy_request(GC_OUTPUT_ENDPOINT, template)
|
||||
|
||||
async def register_method(self, method_name: str) -> str:
|
||||
return await self._send_klippy_request(
|
||||
REG_METHOD_ENDPOINT,
|
||||
{'response_template': {"method": method_name},
|
||||
'remote_method': method_name})
|
||||
|
||||
def send_status(self,
|
||||
status: Dict[str, Any],
|
||||
eventtime: float
|
||||
) -> None:
|
||||
self.server.send_event("server:status_update", status)
|
||||
|
||||
def load_component(config: ConfigHelper) -> KlippyAPI:
|
||||
return KlippyAPI(config)
|
||||
@@ -0,0 +1,129 @@
|
||||
# LDAP authentication for Moonraker
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
# Copyright (C) 2022 Luca Schöneberg <luca-schoeneberg@outlook.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import ldap3
|
||||
from ldap3.core.exceptions import LDAPExceptionError
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Optional
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ldap3.abstract.entry import Entry
|
||||
|
||||
class MoonrakerLDAP:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.ldap_host = config.get('ldap_host')
|
||||
self.ldap_port = config.getint("ldap_port", None)
|
||||
self.ldap_secure = config.getboolean("ldap_secure", False)
|
||||
base_dn_template = config.gettemplate('base_dn')
|
||||
self.base_dn = base_dn_template.render()
|
||||
self.group_dn: Optional[str] = None
|
||||
group_dn_template = config.gettemplate("group_dn", None)
|
||||
if group_dn_template is not None:
|
||||
self.group_dn = group_dn_template.render()
|
||||
self.active_directory = config.getboolean('is_active_directory', False)
|
||||
self.bind_dn: Optional[str] = None
|
||||
self.bind_password: Optional[str] = None
|
||||
bind_dn_template = config.gettemplate('bind_dn', None)
|
||||
bind_pass_template = config.gettemplate('bind_password', None)
|
||||
if bind_dn_template is not None:
|
||||
self.bind_dn = bind_dn_template.render()
|
||||
if bind_pass_template is None:
|
||||
raise config.error(
|
||||
"Section [ldap]: Option 'bind_password' is "
|
||||
"required when 'bind_dn' is provided"
|
||||
)
|
||||
self.bind_password = bind_pass_template.render()
|
||||
self.user_filter: Optional[str] = None
|
||||
user_filter_template = config.gettemplate('user_filter', None)
|
||||
if user_filter_template is not None:
|
||||
self.user_filter = user_filter_template.render()
|
||||
if "USERNAME" not in self.user_filter:
|
||||
raise config.error(
|
||||
"Section [ldap]: Option 'user_filter' is "
|
||||
"is missing required token USERNAME"
|
||||
)
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
async def authenticate_ldap_user(self, username, password) -> None:
|
||||
eventloop = self.server.get_event_loop()
|
||||
async with self.lock:
|
||||
await eventloop.run_in_thread(
|
||||
self._perform_ldap_auth, username, password
|
||||
)
|
||||
|
||||
def _perform_ldap_auth(self, username, password) -> None:
|
||||
server = ldap3.Server(
|
||||
self.ldap_host, self.ldap_port, use_ssl=self.ldap_secure,
|
||||
connect_timeout=10.
|
||||
)
|
||||
conn_args = {
|
||||
"user": self.bind_dn,
|
||||
"password": self.bind_password,
|
||||
"auto_bind": ldap3.AUTO_BIND_NO_TLS,
|
||||
}
|
||||
attr_name = "sAMAccountName" if self.active_directory else "uid"
|
||||
ldfilt = f"(&(objectClass=Person)({attr_name}={username}))"
|
||||
if self.user_filter:
|
||||
ldfilt = self.user_filter.replace("USERNAME", username)
|
||||
try:
|
||||
with ldap3.Connection(server, **conn_args) as conn:
|
||||
ret = conn.search(
|
||||
self.base_dn, ldfilt, attributes=["memberOf"]
|
||||
)
|
||||
if not ret:
|
||||
raise self.server.error(
|
||||
f"LDAP User '{username}' Not Found", 401
|
||||
)
|
||||
user: Entry = conn.entries[0]
|
||||
rebind_success = conn.rebind(user.entry_dn, password)
|
||||
if not rebind_success:
|
||||
# Server may not allow rebinding, attempt to start
|
||||
# a new connection to validate credentials
|
||||
logging.debug(
|
||||
"LDAP Rebind failed, attempting to validate credentials "
|
||||
"with new connection."
|
||||
)
|
||||
conn_args["user"] = user.entry_dn
|
||||
conn_args["password"] = password
|
||||
with ldap3.Connection(server, **conn_args) as conn:
|
||||
if self._validate_group(username, user):
|
||||
return
|
||||
elif self._validate_group(username, user):
|
||||
return
|
||||
except LDAPExceptionError:
|
||||
err_msg = "LDAP authentication failed"
|
||||
else:
|
||||
err_msg = "Invalid LDAP Username or Password"
|
||||
raise self.server.error(err_msg, 401)
|
||||
|
||||
def _validate_group(self, username: str, user: Entry) -> bool:
|
||||
if self.group_dn is None:
|
||||
logging.debug(f"LDAP User {username} login successful")
|
||||
return True
|
||||
if not hasattr(user, "memberOf"):
|
||||
return False
|
||||
for group in user.memberOf.values:
|
||||
if group == self.group_dn:
|
||||
logging.debug(
|
||||
f"LDAP User {username} group match success, "
|
||||
"login successful"
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> MoonrakerLDAP:
|
||||
return MoonrakerLDAP(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,786 @@
|
||||
# MQTT client implementation for Moonraker
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import socket
|
||||
import asyncio
|
||||
import logging
|
||||
import json
|
||||
import pathlib
|
||||
import ssl
|
||||
from collections import deque
|
||||
import paho.mqtt.client as paho_mqtt
|
||||
from ..websockets import Subscribable, WebRequest, JsonRPC, APITransport
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
List,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Union,
|
||||
Tuple,
|
||||
Awaitable,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..app import APIDefinition
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..klippy_connection import KlippyConnection as Klippy
|
||||
FlexCallback = Callable[[bytes], Optional[Coroutine]]
|
||||
RPCCallback = Callable[..., Coroutine]
|
||||
|
||||
DUP_API_REQ_CODE = -10000
|
||||
MQTT_PROTOCOLS = {
|
||||
'v3.1': paho_mqtt.MQTTv31,
|
||||
'v3.1.1': paho_mqtt.MQTTv311,
|
||||
'v5': paho_mqtt.MQTTv5
|
||||
}
|
||||
|
||||
class ExtPahoClient(paho_mqtt.Client):
|
||||
# Override reconnection to take a connected socket. This allows Moonraker
|
||||
# create the socket connection asynchronously
|
||||
def reconnect(self, sock: Optional[socket.socket] = None):
|
||||
"""Reconnect the client after a disconnect. Can only be called after
|
||||
connect()/connect_async()."""
|
||||
if len(self._host) == 0:
|
||||
raise ValueError('Invalid host.')
|
||||
if self._port <= 0:
|
||||
raise ValueError('Invalid port number.')
|
||||
|
||||
if hasattr(self, "_out_packet_mutex"):
|
||||
# Paho Mqtt Version < 1.6.x
|
||||
self._in_packet = {
|
||||
"command": 0,
|
||||
"have_remaining": 0,
|
||||
"remaining_count": [],
|
||||
"remaining_mult": 1,
|
||||
"remaining_length": 0,
|
||||
"packet": b"",
|
||||
"to_process": 0,
|
||||
"pos": 0
|
||||
}
|
||||
with self._out_packet_mutex:
|
||||
self._out_packet = deque() # type: ignore
|
||||
|
||||
with self._current_out_packet_mutex:
|
||||
self._current_out_packet = None
|
||||
else:
|
||||
self._in_packet = {
|
||||
"command": 0,
|
||||
"have_remaining": 0,
|
||||
"remaining_count": [],
|
||||
"remaining_mult": 1,
|
||||
"remaining_length": 0,
|
||||
"packet": bytearray(b""),
|
||||
"to_process": 0,
|
||||
"pos": 0
|
||||
}
|
||||
self._out_packet = deque() # type: ignore
|
||||
|
||||
with self._msgtime_mutex:
|
||||
self._last_msg_in = paho_mqtt.time_func()
|
||||
self._last_msg_out = paho_mqtt.time_func()
|
||||
|
||||
self._ping_t = 0
|
||||
self._state = paho_mqtt.mqtt_cs_new
|
||||
|
||||
self._sock_close()
|
||||
|
||||
# Put messages in progress in a valid state.
|
||||
self._messages_reconnect_reset()
|
||||
|
||||
if sock is None:
|
||||
sock = self._create_socket_connection()
|
||||
|
||||
if self._ssl:
|
||||
# SSL is only supported when SSLContext is available
|
||||
# (implies Python >= 2.7.9 or >= 3.2)
|
||||
|
||||
verify_host = not self._tls_insecure
|
||||
try:
|
||||
# Try with server_hostname, even it's not supported in
|
||||
# certain scenarios
|
||||
sock = self._ssl_context.wrap_socket(
|
||||
sock,
|
||||
server_hostname=self._host,
|
||||
do_handshake_on_connect=False,
|
||||
)
|
||||
except ssl.CertificateError:
|
||||
# CertificateError is derived from ValueError
|
||||
raise
|
||||
except ValueError:
|
||||
# Python version requires SNI in order to handle
|
||||
# server_hostname, but SNI is not available
|
||||
sock = self._ssl_context.wrap_socket(
|
||||
sock,
|
||||
do_handshake_on_connect=False,
|
||||
)
|
||||
else:
|
||||
# If SSL context has already checked hostname, then don't need
|
||||
# to do it again
|
||||
if (hasattr(self._ssl_context, 'check_hostname') and
|
||||
self._ssl_context.check_hostname):
|
||||
verify_host = False
|
||||
|
||||
assert isinstance(sock, ssl.SSLSocket)
|
||||
sock.settimeout(self._keepalive)
|
||||
sock.do_handshake()
|
||||
|
||||
if verify_host:
|
||||
ssl.match_hostname(sock.getpeercert(), self._host)
|
||||
|
||||
if self._transport == "websockets":
|
||||
sock.settimeout(self._keepalive)
|
||||
sock = paho_mqtt.WebsocketWrapper(
|
||||
sock, self._host, self._port, self._ssl,
|
||||
self._websocket_path, self._websocket_extra_headers
|
||||
)
|
||||
|
||||
self._sock = sock
|
||||
assert self._sock is not None
|
||||
self._sock.setblocking(False)
|
||||
self._registered_write = False
|
||||
self._call_socket_open()
|
||||
|
||||
return self._send_connect(self._keepalive)
|
||||
|
||||
class SubscriptionHandle:
|
||||
def __init__(self, topic: str, callback: FlexCallback) -> None:
|
||||
self.callback = callback
|
||||
self.topic = topic
|
||||
|
||||
class BrokerAckLogger:
|
||||
def __init__(self, topics: List[str], action: str) -> None:
|
||||
self.topics = topics
|
||||
self.action = action
|
||||
|
||||
def __call__(self, fut: asyncio.Future) -> None:
|
||||
if self.action == "subscribe":
|
||||
res: Union[List[int], List[paho_mqtt.ReasonCodes]]
|
||||
res = fut.result()
|
||||
log_msg = "MQTT Subscriptions Acknowledged"
|
||||
if len(res) != len(self.topics):
|
||||
log_msg += "\nTopic / QOS count mismatch, " \
|
||||
f"\nTopics: {self.topics} " \
|
||||
f"\nQoS responses: {res}"
|
||||
else:
|
||||
for topic, qos in zip(self.topics, res):
|
||||
log_msg += f"\n Topic: {topic} | "
|
||||
if isinstance(qos, paho_mqtt.ReasonCodes):
|
||||
log_msg += qos.getName()
|
||||
else:
|
||||
log_msg += f"Granted QoS {qos}"
|
||||
elif self.action == "unsubscribe":
|
||||
log_msg = "MQTT Unsubscribe Acknowledged"
|
||||
for topic in self.topics:
|
||||
log_msg += f"\n Topic: {topic}"
|
||||
else:
|
||||
log_msg = f"Unknown action: {self.action}"
|
||||
logging.debug(log_msg)
|
||||
|
||||
|
||||
SubscribedDict = Dict[str, Tuple[int, List[SubscriptionHandle]]]
|
||||
|
||||
class AIOHelper:
|
||||
def __init__(self, client: paho_mqtt.Client) -> None:
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.client = client
|
||||
self.client.on_socket_open = self._on_socket_open
|
||||
self.client.on_socket_close = self._on_socket_close
|
||||
self.client._on_socket_register_write = self._on_socket_register_write
|
||||
self.client._on_socket_unregister_write = \
|
||||
self._on_socket_unregister_write
|
||||
self.misc_task: Optional[asyncio.Task] = None
|
||||
|
||||
def _on_socket_open(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
logging.info("MQTT Socket Opened")
|
||||
self.loop.add_reader(sock, client.loop_read)
|
||||
self.misc_task = self.loop.create_task(self.misc_loop())
|
||||
|
||||
def _on_socket_close(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
logging.info("MQTT Socket Closed")
|
||||
self.loop.remove_reader(sock)
|
||||
if self.misc_task is not None:
|
||||
self.misc_task.cancel()
|
||||
|
||||
def _on_socket_register_write(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
self.loop.add_writer(sock, client.loop_write)
|
||||
|
||||
def _on_socket_unregister_write(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
self.loop.remove_writer(sock)
|
||||
|
||||
async def misc_loop(self) -> None:
|
||||
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
|
||||
try:
|
||||
await asyncio.sleep(1)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
logging.info("MQTT Misc Loop Complete")
|
||||
|
||||
|
||||
class MQTTClient(APITransport, Subscribable):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.event_loop = self.server.get_event_loop()
|
||||
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
|
||||
self.address: str = config.get('address')
|
||||
self.port: int = config.getint('port', 1883)
|
||||
user = config.gettemplate('username', None)
|
||||
self.user_name: Optional[str] = None
|
||||
if user:
|
||||
self.user_name = user.render()
|
||||
pw_file_path = config.get('password_file', None, deprecate=True)
|
||||
pw_template = config.gettemplate('password', None)
|
||||
self.password: Optional[str] = None
|
||||
if pw_file_path is not None:
|
||||
pw_file = pathlib.Path(pw_file_path).expanduser().absolute()
|
||||
if not pw_file.exists():
|
||||
raise config.error(
|
||||
f"Password file '{pw_file}' does not exist")
|
||||
self.password = pw_file.read_text().strip()
|
||||
if pw_template is not None:
|
||||
self.password = pw_template.render()
|
||||
protocol = config.get('mqtt_protocol', "v3.1.1")
|
||||
self.protocol = MQTT_PROTOCOLS.get(protocol, None)
|
||||
if self.protocol is None:
|
||||
raise config.error(
|
||||
f"Invalid value '{protocol}' for option 'mqtt_protocol' "
|
||||
"in section [mqtt]. Must be one of "
|
||||
f"{MQTT_PROTOCOLS.values()}")
|
||||
self.instance_name = config.get('instance_name', socket.gethostname())
|
||||
if '+' in self.instance_name or '#' in self.instance_name:
|
||||
raise config.error(
|
||||
"Option 'instance_name' in section [mqtt] cannot "
|
||||
"contain a wildcard.")
|
||||
self.qos = config.getint("default_qos", 0)
|
||||
if self.qos > 2 or self.qos < 0:
|
||||
raise config.error(
|
||||
"Option 'default_qos' in section [mqtt] must be "
|
||||
"between 0 and 2")
|
||||
self.publish_split_status = \
|
||||
config.getboolean("publish_split_status", False)
|
||||
self.client = ExtPahoClient(protocol=self.protocol)
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.on_message = self._on_message
|
||||
self.client.on_disconnect = self._on_disconnect
|
||||
self.client.on_publish = self._on_publish
|
||||
self.client.on_subscribe = self._on_subscribe
|
||||
self.client.on_unsubscribe = self._on_unsubscribe
|
||||
self.connect_evt: asyncio.Event = asyncio.Event()
|
||||
self.disconnect_evt: Optional[asyncio.Event] = None
|
||||
self.connect_task: Optional[asyncio.Task] = None
|
||||
self.subscribed_topics: SubscribedDict = {}
|
||||
self.pending_responses: List[asyncio.Future] = []
|
||||
self.pending_acks: Dict[int, asyncio.Future] = {}
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/publish", ["POST"],
|
||||
self._handle_publish_request,
|
||||
transports=["http", "websocket", "internal"])
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/subscribe", ["POST"],
|
||||
self._handle_subscription_request,
|
||||
transports=["http", "websocket", "internal"])
|
||||
|
||||
# Subscribe to API requests
|
||||
self.json_rpc = JsonRPC(self.server, transport="MQTT")
|
||||
self.api_request_topic = f"{self.instance_name}/moonraker/api/request"
|
||||
self.api_resp_topic = f"{self.instance_name}/moonraker/api/response"
|
||||
self.klipper_status_topic = f"{self.instance_name}/klipper/status"
|
||||
self.klipper_state_prefix = f"{self.instance_name}/klipper/state"
|
||||
self.moonraker_status_topic = f"{self.instance_name}/moonraker/status"
|
||||
status_cfg: Dict[str, Any] = config.getdict("status_objects", {},
|
||||
allow_empty_fields=True)
|
||||
self.status_objs: Dict[str, Any] = {}
|
||||
for key, val in status_cfg.items():
|
||||
if val is not None:
|
||||
self.status_objs[key] = [v.strip() for v in val.split(',')
|
||||
if v.strip()]
|
||||
else:
|
||||
self.status_objs[key] = None
|
||||
if status_cfg:
|
||||
logging.debug(f"MQTT: Status Objects Set: {self.status_objs}")
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_started", self._handle_klippy_started
|
||||
)
|
||||
|
||||
self.timestamp_deque: Deque = deque(maxlen=20)
|
||||
self.api_qos = config.getint('api_qos', self.qos)
|
||||
if config.getboolean("enable_moonraker_api", True):
|
||||
api_cache = self.server.register_api_transport("mqtt", self)
|
||||
for api_def in api_cache.values():
|
||||
if "mqtt" in api_def.supported_transports:
|
||||
self.register_api_handler(api_def)
|
||||
self.subscribe_topic(self.api_request_topic,
|
||||
self._process_api_request,
|
||||
self.api_qos)
|
||||
|
||||
self.server.register_remote_method("publish_mqtt_topic",
|
||||
self._publish_from_klipper)
|
||||
logging.info(
|
||||
f"\nReserved MQTT topics:\n"
|
||||
f"API Request: {self.api_request_topic}\n"
|
||||
f"API Response: {self.api_resp_topic}\n"
|
||||
f"Moonraker Status: {self.moonraker_status_topic}\n"
|
||||
f"Klipper Status: {self.klipper_status_topic}")
|
||||
|
||||
async def component_init(self) -> None:
|
||||
# We must wait for the IOLoop (asyncio event loop) to start
|
||||
# prior to retrieving it
|
||||
self.helper = AIOHelper(self.client)
|
||||
if self.user_name is not None:
|
||||
self.client.username_pw_set(self.user_name, self.password)
|
||||
self.client.will_set(self.moonraker_status_topic,
|
||||
payload=json.dumps({'server': 'offline'}),
|
||||
qos=self.qos, retain=True)
|
||||
self.client.connect_async(self.address, self.port)
|
||||
self.connect_task = self.event_loop.create_task(
|
||||
self._do_reconnect(first=True)
|
||||
)
|
||||
|
||||
async def _handle_klippy_started(self, state: str) -> None:
|
||||
if self.status_objs:
|
||||
args = {'objects': self.status_objs}
|
||||
try:
|
||||
await self.klippy.request(
|
||||
WebRequest("objects/subscribe", args, conn=self))
|
||||
except self.server.error:
|
||||
pass
|
||||
|
||||
def _on_message(self,
|
||||
client: str,
|
||||
user_data: Any,
|
||||
message: paho_mqtt.MQTTMessage
|
||||
) -> None:
|
||||
topic = message.topic
|
||||
if topic in self.subscribed_topics:
|
||||
cb_hdls = self.subscribed_topics[topic][1]
|
||||
for hdl in cb_hdls:
|
||||
self.event_loop.register_callback(
|
||||
hdl.callback, message.payload)
|
||||
else:
|
||||
logging.debug(
|
||||
f"Unregistered MQTT Topic Received: {topic}, "
|
||||
f"payload: {message.payload.decode()}")
|
||||
|
||||
def _on_connect(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
flags: Dict[str, Any],
|
||||
reason_code: Union[int, paho_mqtt.ReasonCodes],
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
logging.info("MQTT Client Connected")
|
||||
if reason_code == 0:
|
||||
self.publish_topic(self.moonraker_status_topic,
|
||||
{'server': 'online'}, retain=True)
|
||||
subs = [(k, v[0]) for k, v in self.subscribed_topics.items()]
|
||||
if subs:
|
||||
res, msg_id = client.subscribe(subs)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = asyncio.Future()
|
||||
topics = list(self.subscribed_topics.keys())
|
||||
sub_fut.add_done_callback(
|
||||
BrokerAckLogger(topics, "subscribe"))
|
||||
self.pending_acks[msg_id] = sub_fut
|
||||
self.connect_evt.set()
|
||||
self.server.send_event("mqtt:connected")
|
||||
else:
|
||||
if isinstance(reason_code, int):
|
||||
err_str = paho_mqtt.connack_string(reason_code)
|
||||
else:
|
||||
err_str = reason_code.getName()
|
||||
self.server.set_failed_component("mqtt")
|
||||
self.server.add_warning(f"MQTT Connection Failed: {err_str}")
|
||||
|
||||
def _on_disconnect(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
reason_code: int,
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
if self.disconnect_evt is not None:
|
||||
self.disconnect_evt.set()
|
||||
elif self.is_connected():
|
||||
# The server connection was dropped, attempt to reconnect
|
||||
logging.info("MQTT Server Disconnected, reason: "
|
||||
f"{paho_mqtt.error_string(reason_code)}")
|
||||
if self.connect_task is None:
|
||||
self.connect_task = asyncio.create_task(self._do_reconnect())
|
||||
self.server.send_event("mqtt:disconnected")
|
||||
self.connect_evt.clear()
|
||||
|
||||
def _on_publish(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int
|
||||
) -> None:
|
||||
pub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if pub_fut is not None and not pub_fut.done():
|
||||
pub_fut.set_result(None)
|
||||
|
||||
def _on_subscribe(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int,
|
||||
flex: Union[List[int], List[paho_mqtt.ReasonCodes]],
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
sub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if sub_fut is not None and not sub_fut.done():
|
||||
sub_fut.set_result(flex)
|
||||
|
||||
def _on_unsubscribe(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int,
|
||||
properties: Optional[paho_mqtt.Properties] = None,
|
||||
reasoncodes: Optional[paho_mqtt.ReasonCodes] = None
|
||||
) -> None:
|
||||
unsub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if unsub_fut is not None and not unsub_fut.done():
|
||||
unsub_fut.set_result(None)
|
||||
|
||||
async def _do_reconnect(self, first: bool = False) -> None:
|
||||
logging.info("Attempting MQTT Connect/Reconnect")
|
||||
last_err: Exception = Exception()
|
||||
while True:
|
||||
if not first:
|
||||
try:
|
||||
await asyncio.sleep(2.)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
first = False
|
||||
try:
|
||||
sock = await self.event_loop.create_socket_connection(
|
||||
(self.address, self.port), timeout=10
|
||||
)
|
||||
self.client.reconnect(sock)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
if type(last_err) != type(e) or last_err.args != e.args:
|
||||
logging.exception("MQTT Connection Error")
|
||||
last_err = e
|
||||
continue
|
||||
self.client.socket().setsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
break
|
||||
self.connect_task = None
|
||||
|
||||
async def wait_connection(self, timeout: Optional[float] = None) -> bool:
|
||||
try:
|
||||
await asyncio.wait_for(self.connect_evt.wait(), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
return self.connect_evt.is_set()
|
||||
|
||||
def subscribe_topic(self,
|
||||
topic: str,
|
||||
callback: FlexCallback,
|
||||
qos: Optional[int] = None
|
||||
) -> SubscriptionHandle:
|
||||
if '#' in topic or '+' in topic:
|
||||
raise self.server.error("Wildcards may not be used")
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
hdl = SubscriptionHandle(topic, callback)
|
||||
sub_handles = [hdl]
|
||||
need_sub = True
|
||||
if topic in self.subscribed_topics:
|
||||
prev_qos, sub_handles = self.subscribed_topics[topic]
|
||||
qos = max(qos, prev_qos)
|
||||
sub_handles.append(hdl)
|
||||
need_sub = qos != prev_qos
|
||||
self.subscribed_topics[topic] = (qos, sub_handles)
|
||||
if self.is_connected() and need_sub:
|
||||
res, msg_id = self.client.subscribe(topic, qos)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = asyncio.Future()
|
||||
sub_fut.add_done_callback(
|
||||
BrokerAckLogger([topic], "subscribe"))
|
||||
self.pending_acks[msg_id] = sub_fut
|
||||
return hdl
|
||||
|
||||
def unsubscribe(self, hdl: SubscriptionHandle) -> None:
|
||||
topic = hdl.topic
|
||||
if topic in self.subscribed_topics:
|
||||
sub_hdls = self.subscribed_topics[topic][1]
|
||||
try:
|
||||
sub_hdls.remove(hdl)
|
||||
except Exception:
|
||||
pass
|
||||
if not sub_hdls:
|
||||
del self.subscribed_topics[topic]
|
||||
res, msg_id = self.client.unsubscribe(topic)
|
||||
if msg_id is not None:
|
||||
unsub_fut: asyncio.Future = asyncio.Future()
|
||||
unsub_fut.add_done_callback(
|
||||
BrokerAckLogger([topic], "unsubscribe"))
|
||||
self.pending_acks[msg_id] = unsub_fut
|
||||
|
||||
def publish_topic(self,
|
||||
topic: str,
|
||||
payload: Any = None,
|
||||
qos: Optional[int] = None,
|
||||
retain: bool = False
|
||||
) -> Awaitable[None]:
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
pub_fut: asyncio.Future = asyncio.Future()
|
||||
if isinstance(payload, (dict, list)):
|
||||
try:
|
||||
payload = json.dumps(payload)
|
||||
except json.JSONDecodeError:
|
||||
raise self.server.error(
|
||||
"Dict or List is not json encodable") from None
|
||||
elif isinstance(payload, bool):
|
||||
payload = str(payload).lower()
|
||||
try:
|
||||
msg_info = self.client.publish(topic, payload, qos, retain)
|
||||
if msg_info.is_published():
|
||||
pub_fut.set_result(None)
|
||||
else:
|
||||
if qos == 0:
|
||||
# There is no delivery guarantee for qos == 0, so
|
||||
# it is possible that the on_publish event will
|
||||
# not be called if paho mqtt encounters an error
|
||||
# during publication. Return immediately as
|
||||
# a workaround.
|
||||
if msg_info.rc != paho_mqtt.MQTT_ERR_SUCCESS:
|
||||
err_str = paho_mqtt.error_string(msg_info.rc)
|
||||
pub_fut.set_exception(self.server.error(
|
||||
f"MQTT Publish Error: {err_str}", 503))
|
||||
else:
|
||||
pub_fut.set_result(None)
|
||||
return pub_fut
|
||||
self.pending_acks[msg_info.mid] = pub_fut
|
||||
except ValueError:
|
||||
pub_fut.set_exception(self.server.error(
|
||||
"MQTT Message Queue Full", 529))
|
||||
except Exception as e:
|
||||
pub_fut.set_exception(self.server.error(
|
||||
f"MQTT Publish Error: {e}", 503))
|
||||
return pub_fut
|
||||
|
||||
async def publish_topic_with_response(self,
|
||||
topic: str,
|
||||
response_topic: str,
|
||||
payload: Any = None,
|
||||
qos: Optional[int] = None,
|
||||
retain: bool = False,
|
||||
timeout: Optional[float] = None
|
||||
) -> bytes:
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
resp_fut: asyncio.Future = asyncio.Future()
|
||||
resp_hdl = self.subscribe_topic(
|
||||
response_topic, resp_fut.set_result, qos)
|
||||
self.pending_responses.append(resp_fut)
|
||||
try:
|
||||
await asyncio.wait_for(self.publish_topic(
|
||||
topic, payload, qos, retain), timeout)
|
||||
await asyncio.wait_for(resp_fut, timeout)
|
||||
except asyncio.TimeoutError:
|
||||
logging.info(f"Response to request {topic} timed out")
|
||||
raise self.server.error("MQTT Request Timed Out", 504)
|
||||
finally:
|
||||
try:
|
||||
self.pending_responses.remove(resp_fut)
|
||||
except Exception:
|
||||
pass
|
||||
self.unsubscribe(resp_hdl)
|
||||
return resp_fut.result()
|
||||
|
||||
async def _handle_publish_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
topic: str = web_request.get_str("topic")
|
||||
payload: Any = web_request.get("payload", None)
|
||||
qos: int = web_request.get_int("qos", self.qos)
|
||||
retain: bool = web_request.get_boolean("retain", False)
|
||||
timeout: Optional[float] = web_request.get_float('timeout', None)
|
||||
try:
|
||||
await asyncio.wait_for(self.publish_topic(
|
||||
topic, payload, qos, retain), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
raise self.server.error("MQTT Publish Timed Out", 504)
|
||||
return {
|
||||
"topic": topic
|
||||
}
|
||||
|
||||
async def _handle_subscription_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
topic: str = web_request.get_str("topic")
|
||||
qos: int = web_request.get_int("qos", self.qos)
|
||||
timeout: Optional[float] = web_request.get_float('timeout', None)
|
||||
resp: asyncio.Future = asyncio.Future()
|
||||
hdl: Optional[SubscriptionHandle] = None
|
||||
try:
|
||||
hdl = self.subscribe_topic(topic, resp.set_result, qos)
|
||||
self.pending_responses.append(resp)
|
||||
await asyncio.wait_for(resp, timeout)
|
||||
ret: bytes = resp.result()
|
||||
except asyncio.TimeoutError:
|
||||
raise self.server.error("MQTT Subscribe Timed Out", 504)
|
||||
finally:
|
||||
try:
|
||||
self.pending_responses.remove(resp)
|
||||
except Exception:
|
||||
pass
|
||||
if hdl is not None:
|
||||
self.unsubscribe(hdl)
|
||||
try:
|
||||
payload = json.loads(ret)
|
||||
except json.JSONDecodeError:
|
||||
payload = ret.decode()
|
||||
return {
|
||||
'topic': topic,
|
||||
'payload': payload
|
||||
}
|
||||
|
||||
async def _process_api_request(self, payload: bytes) -> None:
|
||||
response = await self.json_rpc.dispatch(payload.decode())
|
||||
if response is not None:
|
||||
await self.publish_topic(self.api_resp_topic, response,
|
||||
self.api_qos)
|
||||
|
||||
def register_api_handler(self, api_def: APIDefinition) -> None:
|
||||
if api_def.callback is None:
|
||||
# Remote API, uses RPC to reach out to Klippy
|
||||
mqtt_method = api_def.jrpc_methods[0]
|
||||
rpc_cb = self._generate_remote_callback(api_def.endpoint)
|
||||
self.json_rpc.register_method(mqtt_method, rpc_cb)
|
||||
else:
|
||||
# Local API, uses local callback
|
||||
for mqtt_method, req_method in \
|
||||
zip(api_def.jrpc_methods, api_def.request_methods):
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, req_method, api_def.callback)
|
||||
self.json_rpc.register_method(mqtt_method, rpc_cb)
|
||||
logging.info(
|
||||
"Registering MQTT JSON-RPC methods: "
|
||||
f"{', '.join(api_def.jrpc_methods)}")
|
||||
|
||||
def remove_api_handler(self, api_def: APIDefinition) -> None:
|
||||
for jrpc_method in api_def.jrpc_methods:
|
||||
self.json_rpc.remove_method(jrpc_method)
|
||||
|
||||
def _generate_local_callback(self,
|
||||
endpoint: str,
|
||||
request_method: str,
|
||||
callback: Callable[[WebRequest], Coroutine]
|
||||
) -> RPCCallback:
|
||||
async def func(args: Dict[str, Any]) -> Any:
|
||||
self._check_timestamp(args)
|
||||
result = await callback(WebRequest(endpoint, args, request_method))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
|
||||
async def func(args: Dict[str, Any]) -> Any:
|
||||
self._check_timestamp(args)
|
||||
result = await self.klippy.request(WebRequest(endpoint, args))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _check_timestamp(self, args: Dict[str, Any]) -> None:
|
||||
ts = args.pop("mqtt_timestamp", None)
|
||||
if ts is not None:
|
||||
if ts in self.timestamp_deque:
|
||||
logging.debug("Duplicate MQTT API request received")
|
||||
raise self.server.error(
|
||||
"Duplicate MQTT Request", DUP_API_REQ_CODE)
|
||||
else:
|
||||
self.timestamp_deque.append(ts)
|
||||
|
||||
def send_status(self,
|
||||
status: Dict[str, Any],
|
||||
eventtime: float
|
||||
) -> None:
|
||||
if not status or not self.is_connected():
|
||||
return
|
||||
if self.publish_split_status:
|
||||
for objkey in status:
|
||||
objval = status[objkey]
|
||||
for statekey in objval:
|
||||
payload = {'eventtime': eventtime,
|
||||
'value': objval[statekey]}
|
||||
self.publish_topic(
|
||||
f"{self.klipper_state_prefix}/{objkey}/{statekey}",
|
||||
payload, retain=True)
|
||||
else:
|
||||
payload = {'eventtime': eventtime, 'status': status}
|
||||
self.publish_topic(self.klipper_status_topic, payload)
|
||||
|
||||
|
||||
def get_instance_name(self) -> str:
|
||||
return self.instance_name
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.connect_task is not None:
|
||||
self.connect_task.cancel()
|
||||
self.connect_task = None
|
||||
if not self.is_connected():
|
||||
return
|
||||
await self.publish_topic(self.moonraker_status_topic,
|
||||
{'server': 'offline'},
|
||||
retain=True)
|
||||
self.disconnect_evt = asyncio.Event()
|
||||
self.client.disconnect()
|
||||
try:
|
||||
await asyncio.wait_for(self.disconnect_evt.wait(), 2.)
|
||||
except asyncio.TimeoutError:
|
||||
logging.info("MQTT Disconnect Timeout")
|
||||
futs = list(self.pending_acks.values())
|
||||
futs.extend(self.pending_responses)
|
||||
for fut in futs:
|
||||
if fut.done():
|
||||
continue
|
||||
fut.set_exception(
|
||||
self.server.error("Moonraker Shutdown", 503))
|
||||
|
||||
async def _publish_from_klipper(self,
|
||||
topic: str,
|
||||
payload: Any = None,
|
||||
qos: Optional[int] = None,
|
||||
retain: bool = False,
|
||||
use_prefix: bool = False
|
||||
) -> None:
|
||||
if use_prefix:
|
||||
topic = f"{self.instance_name}/{topic.lstrip('/')}"
|
||||
await self.publish_topic(topic, payload, qos, retain)
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> MQTTClient:
|
||||
return MQTTClient(config)
|
||||
@@ -0,0 +1,247 @@
|
||||
# Notifier
|
||||
#
|
||||
# Copyright (C) 2022 Pataar <me@pataar.nl>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import apprise
|
||||
import logging
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict,
|
||||
Any,
|
||||
List,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .http_client import HttpClient
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
|
||||
class Notifier:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.notifiers: Dict[str, NotifierInstance] = {}
|
||||
self.events: Dict[str, NotifierEvent] = {}
|
||||
prefix_sections = config.get_prefix_sections("notifier")
|
||||
|
||||
self.register_events(config)
|
||||
self.register_remote_actions()
|
||||
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
try:
|
||||
notifier = NotifierInstance(cfg)
|
||||
|
||||
for event in self.events:
|
||||
if event in notifier.events or "*" in notifier.events:
|
||||
self.events[event].register_notifier(notifier)
|
||||
|
||||
logging.info(f"Registered notifier: '{notifier.get_name()}'")
|
||||
|
||||
except Exception as e:
|
||||
msg = f"Failed to load notifier[{cfg.get_name()}]\n{e}"
|
||||
self.server.add_warning(msg)
|
||||
continue
|
||||
self.notifiers[notifier.get_name()] = notifier
|
||||
|
||||
self.register_endpoints(config)
|
||||
|
||||
def register_remote_actions(self):
|
||||
self.server.register_remote_method("notify", self.notify_action)
|
||||
|
||||
async def notify_action(self, name: str, message: str = ""):
|
||||
if name not in self.notifiers:
|
||||
raise self.server.error(f"Notifier '{name}' not found", 404)
|
||||
notifier = self.notifiers[name]
|
||||
|
||||
await notifier.notify("remote_action", [], message)
|
||||
|
||||
def register_events(self, config: ConfigHelper):
|
||||
|
||||
self.events["started"] = NotifierEvent(
|
||||
"started",
|
||||
"job_state:started",
|
||||
config)
|
||||
|
||||
self.events["complete"] = NotifierEvent(
|
||||
"complete",
|
||||
"job_state:complete",
|
||||
config)
|
||||
|
||||
self.events["error"] = NotifierEvent(
|
||||
"error",
|
||||
"job_state:error",
|
||||
config)
|
||||
|
||||
self.events["cancelled"] = NotifierEvent(
|
||||
"cancelled",
|
||||
"job_state:cancelled",
|
||||
config)
|
||||
|
||||
self.events["paused"] = NotifierEvent(
|
||||
"paused",
|
||||
"job_state:paused",
|
||||
config)
|
||||
|
||||
self.events["resumed"] = NotifierEvent(
|
||||
"resumed",
|
||||
"job_state:resumed",
|
||||
config)
|
||||
|
||||
def register_endpoints(self, config: ConfigHelper):
|
||||
self.server.register_endpoint(
|
||||
"/server/notifiers/list", ["GET"], self._handle_notifier_list
|
||||
)
|
||||
self.server.register_debug_endpoint(
|
||||
"/debug/notifiers/test", ["POST"], self._handle_notifier_test
|
||||
)
|
||||
|
||||
async def _handle_notifier_list(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {"notifiers": self._list_notifiers()}
|
||||
|
||||
def _list_notifiers(self) -> List[Dict[str, Any]]:
|
||||
return [notifier.as_dict() for notifier in self.notifiers.values()]
|
||||
|
||||
async def _handle_notifier_test(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
|
||||
name = web_request.get_str("name")
|
||||
if name not in self.notifiers:
|
||||
raise self.server.error(f"Notifier '{name}' not found", 404)
|
||||
client: HttpClient = self.server.lookup_component("http_client")
|
||||
notifier = self.notifiers[name]
|
||||
|
||||
kapis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
result: Dict[str, Any] = await kapis.query_objects(
|
||||
{'print_stats': None}, default={})
|
||||
print_stats = result.get('print_stats', {})
|
||||
print_stats["filename"] = "notifier_test.gcode" # Mock the filename
|
||||
|
||||
await notifier.notify(notifier.events[0], [print_stats, print_stats])
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"stats": print_stats
|
||||
}
|
||||
|
||||
|
||||
class NotifierEvent:
|
||||
def __init__(self, identifier: str, event_name: str, config: ConfigHelper):
|
||||
self.identifier = identifier
|
||||
self.event_name = event_name
|
||||
self.server = config.get_server()
|
||||
self.notifiers: Dict[str, NotifierInstance] = {}
|
||||
self.config = config
|
||||
|
||||
self.server.register_event_handler(self.event_name, self._handle)
|
||||
|
||||
def register_notifier(self, notifier: NotifierInstance):
|
||||
self.notifiers[notifier.get_name()] = notifier
|
||||
|
||||
async def _handle(self, *args) -> None:
|
||||
logging.info(f"'{self.identifier}' notifier event triggered'")
|
||||
await self.invoke_notifiers(args)
|
||||
|
||||
async def invoke_notifiers(self, args):
|
||||
for notifier_name in self.notifiers:
|
||||
try:
|
||||
notifier = self.notifiers[notifier_name]
|
||||
await notifier.notify(self.identifier, args)
|
||||
except Exception as e:
|
||||
logging.info(f"Failed to notify [{notifier_name}]\n{e}")
|
||||
continue
|
||||
|
||||
|
||||
class NotifierInstance:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
|
||||
self.config = 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.apprise = apprise.Apprise()
|
||||
self.warned = False
|
||||
|
||||
self.attach_requires_file_system_check = True
|
||||
self.attach = config.get("attach", None)
|
||||
if self.attach is None or \
|
||||
(self.attach.startswith("http://") or
|
||||
self.attach.startswith("https://")):
|
||||
self.attach_requires_file_system_check = False
|
||||
|
||||
url_template = config.gettemplate('url')
|
||||
self.url = url_template.render()
|
||||
|
||||
if len(self.url) < 2:
|
||||
raise config.error(f"Invalid url for: {config.get_name()}")
|
||||
|
||||
self.title = config.gettemplate('title', None)
|
||||
self.body = config.gettemplate("body", None)
|
||||
|
||||
self.events: List[str] = config.getlist("events", separator=",")
|
||||
|
||||
self.apprise.add(self.url)
|
||||
|
||||
def as_dict(self):
|
||||
return {
|
||||
"name": self.name,
|
||||
"url": self.config.get("url"),
|
||||
"title": self.config.get("title", None),
|
||||
"body": self.config.get("body", None),
|
||||
"events": self.events,
|
||||
"attach": self.attach
|
||||
}
|
||||
|
||||
async def notify(
|
||||
self, event_name: str, event_args: List, message: str = ""
|
||||
) -> None:
|
||||
|
||||
context = {
|
||||
"event_name": event_name,
|
||||
"event_args": event_args,
|
||||
"event_message": message
|
||||
}
|
||||
|
||||
rendered_title = (
|
||||
'' if self.title is None else self.title.render(context)
|
||||
)
|
||||
rendered_body = (
|
||||
event_name if self.body is None else self.body.render(context)
|
||||
)
|
||||
|
||||
# Verify the attachment
|
||||
if self.attach_requires_file_system_check and self.attach is not None:
|
||||
fm = self.server.lookup_component("file_manager")
|
||||
if not fm.can_access_path(self.attach):
|
||||
if not self.warned:
|
||||
self.server.add_warning(
|
||||
f"Attachment of notifier '{self.name}' is not "
|
||||
"valid. The location of the "
|
||||
"attachment is not "
|
||||
"accessible.")
|
||||
self.warned = True
|
||||
self.attach = None
|
||||
|
||||
await self.apprise.async_notify(
|
||||
rendered_body.strip(),
|
||||
rendered_title.strip(),
|
||||
attach=self.attach
|
||||
)
|
||||
|
||||
def get_name(self) -> str:
|
||||
return self.name
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Notifier:
|
||||
return Notifier(config)
|
||||
@@ -0,0 +1,400 @@
|
||||
# OctoPrint API compatibility
|
||||
#
|
||||
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
from .file_manager.file_manager import FileManager
|
||||
from .job_queue import JobQueue
|
||||
|
||||
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: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.software_version = self.server.get_app_args().get(
|
||||
'software_version')
|
||||
self.enable_ufp: bool = config.getboolean('enable_ufp', True)
|
||||
|
||||
# Get webcam settings from config
|
||||
self.webcam: Dict[str, Any] = {
|
||||
'flipH': config.getboolean('flip_h', False),
|
||||
'flipV': config.getboolean('flip_v', False),
|
||||
'rotate90': config.getboolean('rotate_90', False),
|
||||
'streamUrl': config.get('stream_url', '/webcam/?action=stream'),
|
||||
'webcamEnabled': config.getboolean('webcam_enabled', True),
|
||||
}
|
||||
|
||||
# Local variables
|
||||
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
self.heaters: Dict[str, Dict[str, Any]] = {}
|
||||
self.last_print_stats: Dict[str, Any] = {}
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
'server:klippy_ready', self._init)
|
||||
self.server.register_event_handler(
|
||||
'server:status_update', self._handle_status_update)
|
||||
|
||||
# Version & Server information
|
||||
self.server.register_endpoint(
|
||||
'/api/version', ['GET'], self._get_version,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/server', ['GET'], self._get_server,
|
||||
transports=['http'], wrap_result=False)
|
||||
|
||||
# Login, User & Settings
|
||||
self.server.register_endpoint(
|
||||
'/api/login', ['POST'], self._post_login_user,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/currentuser', ['GET'], self._post_login_user,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/settings', ['GET'], self._get_settings,
|
||||
transports=['http'], 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,
|
||||
transports=['http'], wrap_result=False)
|
||||
# TODO: start/cancel/restart/pause jobs
|
||||
|
||||
# Printer operations
|
||||
self.server.register_endpoint(
|
||||
'/api/printer', ['GET'], self._get_printer,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/printer/command', ['POST'], self._post_command,
|
||||
transports=['http'], wrap_result=False)
|
||||
# TODO: head/tool/bed/chamber specific read/issue
|
||||
|
||||
# Printer profiles
|
||||
self.server.register_endpoint(
|
||||
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
|
||||
transports=['http'], wrap_result=False)
|
||||
|
||||
# Upload Handlers
|
||||
self.server.register_upload_handler(
|
||||
"/api/files/local", location_prefix="api/files/moonraker")
|
||||
self.server.register_endpoint(
|
||||
"/api/files/moonraker/(?P<relative_path>.+)", ['POST'],
|
||||
self._select_file, transports=['http'], wrap_result=False)
|
||||
|
||||
# System
|
||||
# TODO: shutdown/reboot/restart operations
|
||||
|
||||
async def _init(self) -> None:
|
||||
self.heaters = {}
|
||||
# Fetch heaters
|
||||
try:
|
||||
result: Dict[str, Any]
|
||||
sensors: List[str]
|
||||
result = await self.klippy_apis.query_objects({'heaters': None})
|
||||
sensors = result.get('heaters', {}).get('available_sensors', [])
|
||||
except self.server.error as e:
|
||||
logging.info(f'Error Configuring heaters: {e}')
|
||||
sensors = []
|
||||
# subscribe objects
|
||||
sub: Dict[str, Any] = {s: None for s in sensors}
|
||||
sub['print_stats'] = None
|
||||
result = await self.klippy_apis.subscribe_objects(sub)
|
||||
self.last_print_stats = result.get('print_stats', {})
|
||||
if sensors:
|
||||
self.heaters = {name: result.get(name, {}) for name in sensors}
|
||||
|
||||
def _handle_status_update(self, status: Dict[str, Any]) -> None:
|
||||
if 'print_stats' in status:
|
||||
self.last_print_stats.update(status['print_stats'])
|
||||
for heater_name, data in self.heaters.items():
|
||||
if heater_name in status:
|
||||
data.update(status[heater_name])
|
||||
|
||||
def printer_state(self) -> str:
|
||||
klippy_state = self.server.get_klippy_state()
|
||||
if klippy_state in ["disconnected", "startup"]:
|
||||
return 'Offline'
|
||||
elif klippy_state != 'ready':
|
||||
return 'Error'
|
||||
return {
|
||||
'standby': 'Operational',
|
||||
'printing': 'Printing',
|
||||
'paused': 'Paused',
|
||||
'complete': 'Operational'
|
||||
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
|
||||
|
||||
def printer_temps(self) -> Dict[str, Any]:
|
||||
temps: Dict[str, Any] = {}
|
||||
for heater, data in self.heaters.items():
|
||||
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: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Version information
|
||||
"""
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'api': '0.1',
|
||||
'text': f'OctoPrint (Moonraker {self.software_version})',
|
||||
}
|
||||
|
||||
async def _get_server(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Server status
|
||||
"""
|
||||
klippy_state = self.server.get_klippy_state()
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'safemode': (
|
||||
None if klippy_state == 'ready' else 'settings')
|
||||
}
|
||||
|
||||
async def _post_login_user(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Used to parse OctoPrint capabilities
|
||||
"""
|
||||
settings = {
|
||||
'plugins': {},
|
||||
'feature': {
|
||||
'sdSupport': False,
|
||||
'temperatureGraph': False
|
||||
},
|
||||
'webcam': self.webcam,
|
||||
}
|
||||
if self.enable_ufp:
|
||||
settings['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,
|
||||
},
|
||||
}
|
||||
return settings
|
||||
|
||||
async def _get_job(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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': self.printer_state()
|
||||
}
|
||||
|
||||
async def _get_printer(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get Printer status
|
||||
"""
|
||||
state = self.printer_state()
|
||||
return {
|
||||
'temperature': 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: WebRequest
|
||||
) -> Dict:
|
||||
"""
|
||||
Request to run some gcode command
|
||||
"""
|
||||
commands: List[str] = 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: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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,
|
||||
'axes': {
|
||||
'x': {
|
||||
'speed': 6000.,
|
||||
'inverted': False
|
||||
},
|
||||
'y': {
|
||||
'speed': 6000.,
|
||||
'inverted': False
|
||||
},
|
||||
'z': {
|
||||
'speed': 6000.,
|
||||
'inverted': False
|
||||
},
|
||||
'e': {
|
||||
'speed': 300.,
|
||||
'inverted': False
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async def _select_file(self,
|
||||
web_request: WebRequest
|
||||
) -> None:
|
||||
command: str = web_request.get('command')
|
||||
rel_path: str = web_request.get('relative_path')
|
||||
root, filename = rel_path.strip("/").split("/", 1)
|
||||
fmgr: FileManager = self.server.lookup_component('file_manager')
|
||||
if command == "select":
|
||||
start_print: bool = web_request.get('print', False)
|
||||
if not start_print:
|
||||
# No-op, selecting a file has no meaning in Moonraker
|
||||
return
|
||||
if root != "gcodes":
|
||||
raise self.server.error(
|
||||
"File must be located in the 'gcodes' root", 400)
|
||||
if not fmgr.check_file_exists(root, filename):
|
||||
raise self.server.error("File does not exist")
|
||||
try:
|
||||
ret = await self.klippy_apis.query_objects(
|
||||
{'print_stats': None})
|
||||
pstate: str = ret['print_stats']['state']
|
||||
except self.server.error:
|
||||
pstate = "not_avail"
|
||||
started: bool = False
|
||||
if pstate not in ["printing", "paused", "not_avail"]:
|
||||
try:
|
||||
await self.klippy_apis.start_print(filename)
|
||||
except self.server.error:
|
||||
started = False
|
||||
else:
|
||||
logging.debug(f"Job '{filename}' started via OctoPrint API")
|
||||
started = True
|
||||
if not started:
|
||||
if fmgr.upload_queue_enabled():
|
||||
job_queue: JobQueue = self.server.lookup_component(
|
||||
'job_queue')
|
||||
await job_queue.queue_job(filename, check_exists=False)
|
||||
logging.debug(f"Job '{filename}' queued via OctoPrint API")
|
||||
else:
|
||||
raise self.server.error("Conflict", 409)
|
||||
else:
|
||||
raise self.server.error(f"Unsupported Command: {command}")
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> OctoPrintCompat:
|
||||
return OctoPrintCompat(config)
|
||||
@@ -0,0 +1,839 @@
|
||||
# PanelDue LCD display support
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import serial
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from ..utils import ServerError
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Deque,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Callable,
|
||||
Coroutine,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
from .file_manager.file_manager import FileManager as FMComp
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
|
||||
MIN_EST_TIME = 10.
|
||||
INITIALIZE_TIMEOUT = 10.
|
||||
|
||||
class PanelDueError(ServerError):
|
||||
pass
|
||||
|
||||
|
||||
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
|
||||
|
||||
class SerialConnection:
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
paneldue: PanelDue
|
||||
) -> None:
|
||||
self.event_loop = config.get_server().get_event_loop()
|
||||
self.paneldue = paneldue
|
||||
self.port: str = config.get('serial')
|
||||
self.baud = config.getint('baud', 57600)
|
||||
self.partial_input: bytes = b""
|
||||
self.ser: Optional[serial.Serial] = None
|
||||
self.fd: Optional[int] = None
|
||||
self.connected: bool = False
|
||||
self.send_busy: bool = False
|
||||
self.send_buffer: bytes = b""
|
||||
self.attempting_connect: bool = True
|
||||
|
||||
def disconnect(self, reconnect: bool = False) -> None:
|
||||
if self.connected:
|
||||
if self.fd is not None:
|
||||
self.event_loop.remove_reader(self.fd)
|
||||
self.fd = None
|
||||
self.connected = False
|
||||
if self.ser is not None:
|
||||
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.event_loop.delay_callback(1., self.connect)
|
||||
|
||||
async def connect(self) -> None:
|
||||
self.attempting_connect = True
|
||||
start_time = connect_time = time.time()
|
||||
while not self.connected:
|
||||
if connect_time > start_time + 30.:
|
||||
logging.info("Unable to connect, aborting")
|
||||
break
|
||||
logging.info(f"Attempting to connect to: {self.port}")
|
||||
try:
|
||||
# XXX - sometimes the port cannot be exclusively locked, this
|
||||
# would likely be due to a restart where the serial port was
|
||||
# not correctly closed. Maybe don't use exclusive mode?
|
||||
self.ser = serial.Serial(
|
||||
self.port, self.baud, timeout=0, exclusive=True)
|
||||
except (OSError, IOError, serial.SerialException):
|
||||
logging.exception(f"Unable to open port: {self.port}")
|
||||
await asyncio.sleep(2.)
|
||||
connect_time += time.time()
|
||||
continue
|
||||
self.fd = self.ser.fileno()
|
||||
fd = self.fd = self.ser.fileno()
|
||||
os.set_blocking(fd, False)
|
||||
self.event_loop.add_reader(fd, self._handle_incoming)
|
||||
self.connected = True
|
||||
logging.info("PanelDue Connected")
|
||||
self.attempting_connect = False
|
||||
|
||||
def _handle_incoming(self) -> None:
|
||||
# Process incoming data using same method as gcode.py
|
||||
if self.fd is None:
|
||||
return
|
||||
try:
|
||||
data = os.read(self.fd, 4096)
|
||||
except os.error:
|
||||
return
|
||||
|
||||
if not data:
|
||||
# possibly an error, disconnect
|
||||
self.disconnect(reconnect=True)
|
||||
logging.info("serial_display: No data received, disconnecting")
|
||||
return
|
||||
|
||||
# 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:
|
||||
try:
|
||||
decoded_line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(decoded_line)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
f"GCode Processing Error: {decoded_line}")
|
||||
self.paneldue.handle_gcode_response(
|
||||
f"!! GCode Processing Error: {decoded_line}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
|
||||
def send(self, data: bytes) -> None:
|
||||
self.send_buffer += data
|
||||
if not self.send_busy:
|
||||
self.send_busy = True
|
||||
self.event_loop.register_callback(self._do_send)
|
||||
|
||||
async def _do_send(self) -> None:
|
||||
assert self.fd is not None
|
||||
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 asyncio.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: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.event_loop = self.server.get_event_loop()
|
||||
self.file_manager: FMComp = \
|
||||
self.server.lookup_component('file_manager')
|
||||
self.klippy_apis: APIComp = \
|
||||
self.server.lookup_component('klippy_apis')
|
||||
self.kinematics: str = "none"
|
||||
self.machine_name = config.get('machine_name', "Klipper")
|
||||
self.firmware_name: str = "Repetier | Klipper"
|
||||
self.last_message: Optional[str] = None
|
||||
self.last_gcode_response: Optional[str] = None
|
||||
self.current_file: str = ""
|
||||
self.file_metadata: Dict[str, Any] = {}
|
||||
self.enable_checksum = config.getboolean('enable_checksum', True)
|
||||
self.debug_queue: Deque[str] = deque(maxlen=100)
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state: Dict[str, Dict[str, Any]] = {
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
self.extruder_count: int = 0
|
||||
self.heaters: List[str] = []
|
||||
self.is_ready: bool = False
|
||||
self.is_shutdown: bool = False
|
||||
self.initialized: bool = False
|
||||
self.cq_busy: bool = False
|
||||
self.gq_busy: bool = False
|
||||
self.command_queue: List[Tuple[FlexCallback, Any, Any]] = []
|
||||
self.gc_queue: List[str] = []
|
||||
self.last_printer_state: str = 'O'
|
||||
self.last_update_time: float = 0.
|
||||
|
||||
# Set up macros
|
||||
self.confirmed_gcode: str = ""
|
||||
self.mbox_sequence: int = 0
|
||||
self.available_macros: Dict[str, str] = {}
|
||||
self.confirmed_macros = {
|
||||
"RESTART": "RESTART",
|
||||
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
|
||||
macros = config.getlist('macros', None)
|
||||
if macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
conf_macros = config.getlist('confirmed_macros', None)
|
||||
if conf_macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
|
||||
self.available_macros.update(self.confirmed_macros)
|
||||
|
||||
self.non_trivial_keys = config.getlist('non_trivial_keys',
|
||||
["Klipper state"])
|
||||
self.ser_conn = SerialConnection(config, self)
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
# Register server events
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._process_klippy_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._process_klippy_shutdown)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._process_klippy_disconnect)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self.handle_status_update)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self.handle_gcode_response)
|
||||
|
||||
self.server.register_remote_method(
|
||||
"paneldue_beep", self.paneldue_beep)
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# make a request to Klippy
|
||||
self.direct_gcodes: Dict[str, FlexCallback] = {
|
||||
'M20': self._run_paneldue_M20,
|
||||
'M30': self._run_paneldue_M30,
|
||||
'M36': self._run_paneldue_M36,
|
||||
'M408': self._run_paneldue_M408
|
||||
}
|
||||
|
||||
# These gcodes require special parsing or handling prior to being
|
||||
# sent via Klippy's "gcode/script" api command.
|
||||
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
|
||||
'M0': lambda args: "CANCEL_PRINT",
|
||||
'M23': self._prepare_M23,
|
||||
'M24': lambda args: "RESUME",
|
||||
'M25': lambda args: "PAUSE",
|
||||
'M32': self._prepare_M32,
|
||||
'M98': self._prepare_M98,
|
||||
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
|
||||
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
|
||||
'M290': self._prepare_M290,
|
||||
'M292': self._prepare_M292,
|
||||
'M999': lambda args: "FIRMWARE_RESTART"
|
||||
}
|
||||
|
||||
async def component_init(self) -> None:
|
||||
await self.ser_conn.connect()
|
||||
|
||||
async def _process_klippy_ready(self) -> None:
|
||||
# Request "info" and "configfile" status
|
||||
retries = 10
|
||||
printer_info: Dict[str, Any] = {}
|
||||
cfg_status: Dict[str, Any] = {}
|
||||
while retries:
|
||||
try:
|
||||
printer_info = await self.klippy_apis.get_klippy_info()
|
||||
cfg_status = await self.klippy_apis.query_objects(
|
||||
{'configfile': None})
|
||||
except self.server.error:
|
||||
logging.exception("PanelDue initialization request failed")
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise
|
||||
await asyncio.sleep(1.)
|
||||
continue
|
||||
break
|
||||
|
||||
self.firmware_name = "Repetier | Klipper " + \
|
||||
printer_info['software_version']
|
||||
config: Dict[str, Any] = cfg_status.get(
|
||||
'configfile', {}).get('config', {})
|
||||
printer_cfg: Dict[str, Any] = config.get('printer', {})
|
||||
self.kinematics = printer_cfg.get('kinematics', "none")
|
||||
|
||||
logging.info(
|
||||
f"PanelDue Config Received:\n"
|
||||
f"Firmware Name: {self.firmware_name}\n"
|
||||
f"Kinematics: {self.kinematics}\n"
|
||||
f"Printer Config: {config}\n")
|
||||
|
||||
# Initalize printer state and make subscription request
|
||||
self.printer_state = {
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
sub_args = {k: None for k in self.printer_state.keys()}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
extruders = []
|
||||
for cfg in config:
|
||||
if cfg.startswith("extruder"):
|
||||
self.extruder_count += 1
|
||||
self.printer_state[cfg] = {}
|
||||
extruders.append(cfg)
|
||||
sub_args[cfg] = None
|
||||
elif cfg == "heater_bed":
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = None
|
||||
extruders.sort()
|
||||
self.heaters.extend(extruders)
|
||||
try:
|
||||
status: Dict[str, Any]
|
||||
status = await self.klippy_apis.subscribe_objects(sub_args)
|
||||
except self.server.error:
|
||||
logging.exception("Unable to complete subscription request")
|
||||
else:
|
||||
self.printer_state.update(status)
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
def _process_klippy_shutdown(self) -> None:
|
||||
self.is_shutdown = True
|
||||
|
||||
def _process_klippy_disconnect(self) -> None:
|
||||
# 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
|
||||
|
||||
def handle_status_update(self, status: Dict[str, Any]) -> None:
|
||||
for obj, items in status.items():
|
||||
if obj in self.printer_state:
|
||||
self.printer_state[obj].update(items)
|
||||
else:
|
||||
self.printer_state[obj] = items
|
||||
|
||||
def paneldue_beep(self, frequency: int, duration: float) -> None:
|
||||
duration = int(duration * 1000.)
|
||||
self.write_response(
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
def process_line(self, line: str) -> None:
|
||||
self.debug_queue.append(line)
|
||||
# If we find M112 in the line then skip verification
|
||||
if "M112" in line.upper():
|
||||
self.event_loop.register_callback(self.klippy_apis.emergency_stop)
|
||||
return
|
||||
|
||||
if self.enable_checksum:
|
||||
# Get line number
|
||||
line_index = line.find(' ')
|
||||
try:
|
||||
line_no: Optional[int] = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
|
||||
# Verify checksum
|
||||
cs_index = line.rfind('*')
|
||||
try:
|
||||
checksum = int(line[cs_index+1:])
|
||||
except Exception:
|
||||
# Invalid checksum, do not process
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.exception("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
# Checksum is calculated by XORing every byte in the line other
|
||||
# than the checksum itself
|
||||
calculated_cs = 0
|
||||
for c in line[:cs_index]:
|
||||
calculated_cs ^= ord(c)
|
||||
if calculated_cs & 0xFF != checksum:
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg += f" Line Number: {line_no}"
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
script = line[line_index+1:cs_index]
|
||||
else:
|
||||
script = line
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
# require special handling
|
||||
parts = script.split()
|
||||
cmd = parts[0].strip()
|
||||
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
|
||||
arg = script[len(cmd):].strip()
|
||||
parts = [cmd, arg]
|
||||
|
||||
# Check for commands that query state and require immediate response
|
||||
if cmd in self.direct_gcodes:
|
||||
params: Dict[str, Any] = {}
|
||||
for p in parts[1:]:
|
||||
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(" \"\t\n")
|
||||
except Exception:
|
||||
msg = f"paneldue: Error parsing direct gcode {script}"
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
return
|
||||
params[f"arg_{arg}"] = val
|
||||
func = self.direct_gcodes[cmd]
|
||||
self.queue_command(func, **params)
|
||||
return
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
if cmd in self.special_gcodes:
|
||||
sgc_func = self.special_gcodes[cmd]
|
||||
script = sgc_func(parts[1:])
|
||||
|
||||
if not script:
|
||||
return
|
||||
self.queue_gcode(script)
|
||||
|
||||
def queue_gcode(self, script: str) -> None:
|
||||
self.gc_queue.append(script)
|
||||
if not self.gq_busy:
|
||||
self.gq_busy = True
|
||||
self.event_loop.register_callback(self._process_gcode_queue)
|
||||
|
||||
async def _process_gcode_queue(self) -> None:
|
||||
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: FlexCallback, *args, **kwargs) -> None:
|
||||
self.command_queue.append((cmd, args, kwargs))
|
||||
if not self.cq_busy:
|
||||
self.cq_busy = True
|
||||
self.event_loop.register_callback(self._process_command_queue)
|
||||
|
||||
async def _process_command_queue(self) -> None:
|
||||
while self.command_queue:
|
||||
cmd, args, kwargs = self.command_queue.pop(0)
|
||||
try:
|
||||
ret = cmd(*args, **kwargs)
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception("Error processing command")
|
||||
self.cq_busy = False
|
||||
|
||||
def _clean_filename(self, filename: str) -> str:
|
||||
# Remove quotes and whitespace
|
||||
filename.strip(" \"\t\n")
|
||||
# Remove drive number
|
||||
if filename.startswith("0:/"):
|
||||
filename = filename[3:]
|
||||
# Remove initial "gcodes" folder. This is necessary
|
||||
# due to the HACK in the paneldue_M20 gcode.
|
||||
if filename.startswith("gcodes/"):
|
||||
filename = filename[6:]
|
||||
elif filename.startswith("/gcodes/"):
|
||||
filename = filename[7:]
|
||||
# Start with a "/" so the gcode parser can correctly
|
||||
# handle files that begin with digits or special chars
|
||||
if filename[0] != "/":
|
||||
filename = "/" + filename
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args: List[str]) -> str:
|
||||
filename = self._clean_filename(args[0])
|
||||
return f"M23 {filename}"
|
||||
|
||||
def _prepare_M32(self, args: List[str]) -> str:
|
||||
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: List[str]) -> str:
|
||||
macro = args[0][1:].strip(" \"\t\n")
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
cmd = self.available_macros.get(macro)
|
||||
if cmd is None:
|
||||
raise PanelDueError(f"Macro {macro} invalid")
|
||||
if macro in self.confirmed_macros:
|
||||
self._create_confirmation(macro, cmd)
|
||||
cmd = ""
|
||||
return cmd
|
||||
|
||||
def _prepare_M290(self, args: List[str]) -> str:
|
||||
# args should in in the format Z0.02
|
||||
offset = args[0][1:].strip()
|
||||
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
|
||||
|
||||
def _prepare_M292(self, args: List[str]) -> str:
|
||||
p_val = int(args[0][1])
|
||||
if p_val == 0:
|
||||
cmd = self.confirmed_gcode
|
||||
self.confirmed_gcode = ""
|
||||
return cmd
|
||||
return ""
|
||||
|
||||
def _create_confirmation(self, name: str, gcode: str) -> None:
|
||||
self.mbox_sequence += 1
|
||||
self.confirmed_gcode = gcode
|
||||
title = "Confirmation Dialog"
|
||||
msg = f"Please confirm your intent to run {name}." \
|
||||
" Press OK to continue, or CANCEL to abort."
|
||||
mbox: Dict[str, Any] = {}
|
||||
mbox['msgBox.mode'] = 3
|
||||
mbox['msgBox.msg'] = msg
|
||||
mbox['msgBox.seq'] = self.mbox_sequence
|
||||
mbox['msgBox.title'] = title
|
||||
mbox['msgBox.controls'] = 0
|
||||
mbox['msgBox.timeout'] = 0
|
||||
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
|
||||
self.write_response(mbox)
|
||||
|
||||
def handle_gcode_response(self, response: str) -> None:
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
# moment we'll handle state changes and errors
|
||||
if "Klipper state" in response \
|
||||
or response.startswith('!!'):
|
||||
self.last_gcode_response = response
|
||||
else:
|
||||
for key in self.non_trivial_keys:
|
||||
if key in response:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
def write_response(self, response: Dict[str, Any]) -> None:
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
self.ser_conn.send(byte_resp.encode())
|
||||
|
||||
def _get_printer_status(self) -> str:
|
||||
# PanelDue States applicable to Klipper:
|
||||
# I = idle, P = printing from SD, S = stopped (shutdown),
|
||||
# C = starting up (not ready), A = paused, D = pausing,
|
||||
# B = busy
|
||||
if self.is_shutdown:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
sd_state: str
|
||||
sd_state = printer_state['print_stats'].get('state', "standby")
|
||||
if sd_state == "printing":
|
||||
if self.last_printer_state == 'A':
|
||||
# Resuming
|
||||
return 'R'
|
||||
# Printing
|
||||
return 'P'
|
||||
elif sd_state == "paused":
|
||||
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'
|
||||
|
||||
return 'I'
|
||||
|
||||
def _run_paneldue_M408(self,
|
||||
arg_r: Optional[int] = None,
|
||||
arg_s: int = 1
|
||||
) -> None:
|
||||
response: Dict[str, Any] = {}
|
||||
sequence = arg_r
|
||||
response_type = arg_s
|
||||
|
||||
curtime = self.event_loop.get_loop_time()
|
||||
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
|
||||
self.initialized = False
|
||||
self.last_update_time = curtime
|
||||
|
||||
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
|
||||
response['firmwareName'] = self.firmware_name
|
||||
response['numTools'] = self.extruder_count
|
||||
response['geometry'] = self.kinematics
|
||||
response['axes'] = 3
|
||||
|
||||
p_state = self.printer_state
|
||||
self.last_printer_state = self._get_printer_status()
|
||||
response['status'] = self.last_printer_state
|
||||
response['babystep'] = round(p_state['gcode_move'].get(
|
||||
'homing_origin', [0., 0., 0., 0.])[2], 3)
|
||||
|
||||
# Current position
|
||||
pos: List[float]
|
||||
homed_pos: str
|
||||
sfactor: float
|
||||
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
|
||||
response['pos'] = [round(p, 2) for p in pos[:3]]
|
||||
homed_pos = p_state['toolhead'].get('homed_axes', "")
|
||||
response['homed'] = [int(a in homed_pos) for a in "xyz"]
|
||||
sfactor = round(p_state['gcode_move'].get('speed_factor', 1.) * 100, 2)
|
||||
response['sfactor'] = sfactor
|
||||
|
||||
# Print Progress Tracking
|
||||
sd_status = p_state['virtual_sdcard']
|
||||
print_stats = p_state['print_stats']
|
||||
fname: str = print_stats.get('filename', "")
|
||||
sd_print_state: Optional[str] = print_stats.get('state')
|
||||
if sd_print_state in ['printing', 'paused']:
|
||||
# We know a file has been loaded, initialize metadata
|
||||
if self.current_file != fname:
|
||||
self.current_file = fname
|
||||
self.file_metadata = self.file_manager.get_file_metadata(fname)
|
||||
progress: float = sd_status.get('progress', 0)
|
||||
# progress and print tracking
|
||||
if progress:
|
||||
response['fraction_printed'] = round(progress, 3)
|
||||
est_time: float = self.file_metadata.get('estimated_time', 0)
|
||||
if est_time > MIN_EST_TIME:
|
||||
# file read estimate
|
||||
times_left = [int(est_time - est_time * progress)]
|
||||
# filament estimate
|
||||
est_total_fil: Optional[float]
|
||||
est_total_fil = self.file_metadata.get('filament_total')
|
||||
if est_total_fil:
|
||||
cur_filament: float = print_stats.get(
|
||||
'filament_used', 0.)
|
||||
fpct = min(1., cur_filament / est_total_fil)
|
||||
times_left.append(int(est_time - est_time * fpct))
|
||||
# object height estimate
|
||||
obj_height: Optional[float]
|
||||
obj_height = self.file_metadata.get('object_height')
|
||||
if obj_height:
|
||||
cur_height: float = p_state['gcode_move'].get(
|
||||
'gcode_position', [0., 0., 0., 0.])[2]
|
||||
hpct = min(1., cur_height / obj_height)
|
||||
times_left.append(int(est_time - est_time * hpct))
|
||||
else:
|
||||
# The estimated time is not in the metadata, however we
|
||||
# can still provide an estimate based on file progress
|
||||
duration: float = print_stats.get('print_duration', 0.)
|
||||
times_left = [int(duration / progress - duration)]
|
||||
response['timesLeft'] = times_left
|
||||
else:
|
||||
# clear filename and metadata
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
|
||||
fan_speed: Optional[float] = p_state['fan'].get('speed')
|
||||
if fan_speed is not None:
|
||||
response['fanPercent'] = [round(fan_speed * 100, 1)]
|
||||
|
||||
extruder_name: str = ""
|
||||
if self.extruder_count > 0:
|
||||
extruder_name = p_state['toolhead'].get('extruder', "")
|
||||
if extruder_name:
|
||||
tool = 0
|
||||
if extruder_name != "extruder":
|
||||
tool = int(extruder_name[-1])
|
||||
response['tool'] = tool
|
||||
|
||||
# Report Heater Status
|
||||
efactor: float = round(p_state['gcode_move'].get(
|
||||
'extrude_factor', 1.) * 100., 2)
|
||||
|
||||
for name in self.heaters:
|
||||
temp: float = round(p_state[name].get('temperature', 0.0), 1)
|
||||
target: float = round(p_state[name].get('target', 0.0), 1)
|
||||
response.setdefault('heaters', []).append(temp)
|
||||
response.setdefault('active', []).append(target)
|
||||
response.setdefault('standby', []).append(target)
|
||||
if name.startswith('extruder'):
|
||||
a_stat = 2 if name == extruder_name else 1
|
||||
response.setdefault('hstat', []).append(a_stat if target else 0)
|
||||
response.setdefault('efactor', []).append(efactor)
|
||||
response.setdefault('extr', []).append(round(pos[3], 2))
|
||||
else:
|
||||
response.setdefault('hstat', []).append(2 if target else 0)
|
||||
|
||||
# Display message (via M117)
|
||||
msg: str = p_state['display_status'].get('message', "")
|
||||
if msg and msg != self.last_message:
|
||||
response['message'] = msg
|
||||
# reset the message so it only shows once. The paneldue
|
||||
# is strange about this, and displays it as a full screen
|
||||
# notification
|
||||
self.last_message = msg
|
||||
self.write_response(response)
|
||||
|
||||
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
f"Cannot process response type {response_type} in M20")
|
||||
return
|
||||
path = arg_p
|
||||
|
||||
# Strip quotes if they exist
|
||||
path = path.strip('\"')
|
||||
|
||||
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
|
||||
# repetier compatibility enabled, the default folder is root,
|
||||
# ie. "0:/"
|
||||
if path.startswith("0:/"):
|
||||
path = path[2:]
|
||||
response: Dict[str, Any] = {'dir': path}
|
||||
response['files'] = []
|
||||
|
||||
if path == "/macros":
|
||||
response['files'] = list(self.available_macros.keys())
|
||||
else:
|
||||
# HACK: The PanelDue has a bug where it does not correctly detect
|
||||
# subdirectories if we return the root as "/". Moonraker can
|
||||
# support a "gcodes" directory, however we must choose between this
|
||||
# support or disabling RRF specific gcodes (this is done by
|
||||
# identifying as Repetier).
|
||||
# The workaround below converts both "/" and "/gcodes" paths to
|
||||
# "gcodes".
|
||||
if path == "/":
|
||||
response['dir'] = "/gcodes"
|
||||
path = "gcodes"
|
||||
elif path.startswith("/gcodes"):
|
||||
path = path[1:]
|
||||
|
||||
flist = self.file_manager.list_dir(path, simple_format=True)
|
||||
if flist:
|
||||
response['files'] = flist
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p: str = "") -> None:
|
||||
# Delete a file. Clean up the file name and make sure
|
||||
# it is relative to the "gcodes" root.
|
||||
path = arg_p
|
||||
path = path.strip('\"')
|
||||
if path.startswith("0:/"):
|
||||
path = path[3:]
|
||||
elif path[0] == "/":
|
||||
path = path[1:]
|
||||
|
||||
if not path.startswith("gcodes/"):
|
||||
path = "gcodes/" + path
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
def _run_paneldue_M36(self, arg_p: Optional[str] = None) -> None:
|
||||
response: Dict[str, Any] = {}
|
||||
filename: Optional[str] = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
print_stats = self.printer_state.get('print_stats', {})
|
||||
if filename is None:
|
||||
# PanelDue is requesting file information on a
|
||||
# currently printed file
|
||||
active = False
|
||||
if sd_status and print_stats:
|
||||
filename = print_stats['filename']
|
||||
active = sd_status['is_active']
|
||||
if not filename or not active:
|
||||
# Either no file printing or no virtual_sdcard
|
||||
response['err'] = 1
|
||||
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
|
||||
|
||||
metadata: Dict[str, Any] = \
|
||||
self.file_manager.get_file_metadata(filename)
|
||||
if metadata:
|
||||
response['err'] = 0
|
||||
response['size'] = metadata['size']
|
||||
# workaround for PanelDue replacing the first "T" found
|
||||
response['lastModified'] = "T" + time.ctime(metadata['modified'])
|
||||
slicer: Optional[str] = metadata.get('slicer')
|
||||
if slicer is not None:
|
||||
response['generatedBy'] = slicer
|
||||
height: Optional[float] = metadata.get('object_height')
|
||||
if height is not None:
|
||||
response['height'] = round(height, 2)
|
||||
layer_height: Optional[float] = metadata.get('layer_height')
|
||||
if layer_height is not None:
|
||||
response['layerHeight'] = round(layer_height, 2)
|
||||
filament: Optional[float] = metadata.get('filament_total')
|
||||
if filament is not None:
|
||||
response['filament'] = [round(filament, 1)]
|
||||
est_time: Optional[float] = metadata.get('estimated_time')
|
||||
if est_time is not None:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
self.write_response(response)
|
||||
|
||||
def close(self) -> None:
|
||||
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_component(config: ConfigHelper) -> PanelDue:
|
||||
return PanelDue(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,342 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import time
|
||||
import re
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
from collections import deque
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Deque,
|
||||
Any,
|
||||
List,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest, WebsocketManager
|
||||
from . import shell_command
|
||||
STAT_CALLBACK = Callable[[int], Optional[Awaitable]]
|
||||
|
||||
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
|
||||
STATM_FILE_PATH = "/proc/self/smaps_rollup"
|
||||
NET_DEV_PATH = "/proc/net/dev"
|
||||
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
|
||||
CPU_STAT_PATH = "/proc/stat"
|
||||
MEM_AVAIL_PATH = "/proc/meminfo"
|
||||
STAT_UPDATE_TIME = 1.
|
||||
REPORT_QUEUE_SIZE = 30
|
||||
THROTTLE_CHECK_INTERVAL = 10
|
||||
WATCHDOG_REFRESH_TIME = 2.
|
||||
REPORT_BLOCKED_TIME = 4.
|
||||
|
||||
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: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.event_loop = self.server.get_event_loop()
|
||||
self.watchdog = Watchdog(self)
|
||||
self.stat_update_timer = self.event_loop.register_timer(
|
||||
self._handle_stat_update)
|
||||
self.vcgencmd: Optional[shell_command.ShellCommand] = None
|
||||
if os.path.exists(VC_GEN_CMD_FILE):
|
||||
logging.info("Detected 'vcgencmd', throttle checking enabled")
|
||||
shell_cmd: shell_command.ShellCommandFactory
|
||||
shell_cmd = self.server.load_component(config, "shell_command")
|
||||
self.vcgencmd = shell_cmd.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.temp_file = pathlib.Path(TEMPERATURE_PATH)
|
||||
self.smaps = pathlib.Path(STATM_FILE_PATH)
|
||||
self.netdev_file = pathlib.Path(NET_DEV_PATH)
|
||||
self.cpu_stats_file = pathlib.Path(CPU_STAT_PATH)
|
||||
self.meminfo_file = pathlib.Path(MEM_AVAIL_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.server.register_notification("proc_stats:proc_stat_update")
|
||||
self.proc_stat_queue: Deque[Dict[str, Any]] = deque(maxlen=30)
|
||||
self.last_update_time = time.time()
|
||||
self.last_proc_time = time.process_time()
|
||||
self.throttle_check_lock = asyncio.Lock()
|
||||
self.total_throttled: int = 0
|
||||
self.last_throttled: int = 0
|
||||
self.update_sequence: int = 0
|
||||
self.last_net_stats: Dict[str, Dict[str, Any]] = {}
|
||||
self.last_cpu_stats: Dict[str, Tuple[int, int]] = {}
|
||||
self.cpu_usage: Dict[str, float] = {}
|
||||
self.memory_usage: Dict[str, int] = {}
|
||||
self.stat_callbacks: List[STAT_CALLBACK] = []
|
||||
|
||||
async def component_init(self) -> None:
|
||||
self.stat_update_timer.start()
|
||||
self.watchdog.start()
|
||||
|
||||
def register_stat_callback(self, callback: STAT_CALLBACK) -> None:
|
||||
self.stat_callbacks.append(callback)
|
||||
|
||||
async def _handle_stat_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
ts: Optional[Dict[str, Any]] = None
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
cpu_temp = await self.event_loop.run_in_thread(
|
||||
self._get_cpu_temperature)
|
||||
wsm: WebsocketManager = self.server.lookup_component("websockets")
|
||||
websocket_count = wsm.get_count()
|
||||
return {
|
||||
'moonraker_stats': list(self.proc_stat_queue),
|
||||
'throttled_state': ts,
|
||||
'cpu_temp': cpu_temp,
|
||||
'network': self.last_net_stats,
|
||||
'system_cpu_usage': self.cpu_usage,
|
||||
'system_uptime': time.clock_gettime(time.CLOCK_BOOTTIME),
|
||||
'system_memory': self.memory_usage,
|
||||
'websocket_connections': websocket_count
|
||||
}
|
||||
|
||||
async def _handle_shutdown(self) -> None:
|
||||
msg = "\nMoonraker System Usage Statistics:"
|
||||
for stats in self.proc_stat_queue:
|
||||
msg += f"\n{self._format_stats(stats)}"
|
||||
cpu_temp = await self.event_loop.run_in_thread(
|
||||
self._get_cpu_temperature)
|
||||
msg += f"\nCPU Temperature: {cpu_temp}"
|
||||
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, eventtime: float) -> float:
|
||||
update_time = eventtime
|
||||
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)
|
||||
cpu_temp, mem, mem_units, net = (
|
||||
await self.event_loop.run_in_thread(self._read_system_files)
|
||||
)
|
||||
for dev in net:
|
||||
bytes_sec = 0.
|
||||
if dev in self.last_net_stats:
|
||||
last_dev_stats = self.last_net_stats[dev]
|
||||
cur_total: int = net[dev]['rx_bytes'] + net[dev]['tx_bytes']
|
||||
last_total: int = last_dev_stats['rx_bytes'] + \
|
||||
last_dev_stats['tx_bytes']
|
||||
bytes_sec = round((cur_total - last_total) / time_diff, 2)
|
||||
net[dev]['bandwidth'] = bytes_sec
|
||||
self.last_net_stats = net
|
||||
result = {
|
||||
'time': time.time(),
|
||||
'cpu_usage': usage,
|
||||
'memory': mem,
|
||||
'mem_units': mem_units
|
||||
}
|
||||
self.proc_stat_queue.append(result)
|
||||
wsm: WebsocketManager = self.server.lookup_component("websockets")
|
||||
websocket_count = wsm.get_count()
|
||||
self.server.send_event("proc_stats:proc_stat_update", {
|
||||
'moonraker_stats': result,
|
||||
'cpu_temp': cpu_temp,
|
||||
'network': net,
|
||||
'system_cpu_usage': self.cpu_usage,
|
||||
'system_memory': self.memory_usage,
|
||||
'websocket_connections': websocket_count
|
||||
})
|
||||
if not self.update_sequence % THROTTLE_CHECK_INTERVAL:
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
cur_throttled = ts['bits']
|
||||
if cur_throttled & ~self.total_throttled:
|
||||
self.server.add_log_rollover_item(
|
||||
'throttled', f"CPU Throttled Flags: {ts['flags']}")
|
||||
if cur_throttled != self.last_throttled:
|
||||
self.server.send_event("proc_stats:cpu_throttled", ts)
|
||||
self.last_throttled = cur_throttled
|
||||
self.total_throttled |= cur_throttled
|
||||
for cb in self.stat_callbacks:
|
||||
ret = cb(self.update_sequence)
|
||||
if ret is not None:
|
||||
await ret
|
||||
self.last_update_time = update_time
|
||||
self.last_proc_time = proc_time
|
||||
self.update_sequence += 1
|
||||
return eventtime + STAT_UPDATE_TIME
|
||||
|
||||
async def _check_throttled_state(self) -> Dict[str, Any]:
|
||||
async with self.throttle_check_lock:
|
||||
assert self.vcgencmd is not None
|
||||
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 _read_system_files(self) -> Tuple:
|
||||
mem, units = self._get_memory_usage()
|
||||
temp = self._get_cpu_temperature()
|
||||
net_stats = self._get_net_stats()
|
||||
self._update_cpu_stats()
|
||||
self._update_system_memory()
|
||||
return temp, mem, units, net_stats
|
||||
|
||||
def _get_memory_usage(self) -> Tuple[Optional[int], Optional[str]]:
|
||||
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 _get_cpu_temperature(self) -> Optional[float]:
|
||||
try:
|
||||
res = int(self.temp_file.read_text().strip())
|
||||
temp = res / 1000.
|
||||
except Exception:
|
||||
return None
|
||||
return temp
|
||||
|
||||
def _get_net_stats(self) -> Dict[str, Any]:
|
||||
net_stats: Dict[str, Any] = {}
|
||||
try:
|
||||
ret = self.netdev_file.read_text()
|
||||
dev_info = re.findall(r"([\w]+):(.+)", ret)
|
||||
for (dev_name, stats) in dev_info:
|
||||
parsed_stats = stats.strip().split()
|
||||
net_stats[dev_name] = {
|
||||
'rx_bytes': int(parsed_stats[0]),
|
||||
'tx_bytes': int(parsed_stats[8]),
|
||||
'rx_packets': int(parsed_stats[1]),
|
||||
'tx_packets': int(parsed_stats[9]),
|
||||
'rx_errs': int(parsed_stats[2]),
|
||||
'tx_errs': int(parsed_stats[10]),
|
||||
'rx_drop': int(parsed_stats[3]),
|
||||
'tx_drop': int(parsed_stats[11])
|
||||
}
|
||||
return net_stats
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def _update_system_memory(self) -> None:
|
||||
mem_stats: Dict[str, Any] = {}
|
||||
try:
|
||||
ret = self.meminfo_file.read_text()
|
||||
total_match = re.search(r"MemTotal:\s+(\d+)", ret)
|
||||
avail_match = re.search(r"MemAvailable:\s+(\d+)", ret)
|
||||
if total_match is not None and avail_match is not None:
|
||||
mem_stats["total"] = int(total_match.group(1))
|
||||
mem_stats["available"] = int(avail_match.group(1))
|
||||
mem_stats["used"] = mem_stats["total"] - mem_stats["available"]
|
||||
self.memory_usage.update(mem_stats)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _update_cpu_stats(self) -> None:
|
||||
try:
|
||||
cpu_usage: Dict[str, Any] = {}
|
||||
ret = self.cpu_stats_file.read_text()
|
||||
usage_info: List[str] = re.findall(r"cpu[^\n]+", ret)
|
||||
for cpu in usage_info:
|
||||
parts = cpu.split()
|
||||
name = parts[0]
|
||||
cpu_sum = sum([int(t) for t in parts[1:]])
|
||||
cpu_idle = int(parts[4])
|
||||
if name in self.last_cpu_stats:
|
||||
last_sum, last_idle = self.last_cpu_stats[name]
|
||||
cpu_delta = cpu_sum - last_sum
|
||||
idle_delta = cpu_idle - last_idle
|
||||
cpu_used = cpu_delta - idle_delta
|
||||
cpu_usage[name] = round(
|
||||
100 * (cpu_used / cpu_delta), 2)
|
||||
self.cpu_usage = cpu_usage
|
||||
self.last_cpu_stats[name] = (cpu_sum, cpu_idle)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _format_stats(self, stats: Dict[str, Any]) -> str:
|
||||
return f"System Time: {stats['time']:2f}, " \
|
||||
f"Usage: {stats['cpu_usage']}%, " \
|
||||
f"Memory: {stats['memory']} {stats['mem_units']}"
|
||||
|
||||
def log_last_stats(self, count: int = 1):
|
||||
count = min(len(self.proc_stat_queue), count)
|
||||
msg = ""
|
||||
for stats in list(self.proc_stat_queue)[-count:]:
|
||||
msg += f"\n{self._format_stats(stats)}"
|
||||
logging.info(msg)
|
||||
|
||||
def close(self) -> None:
|
||||
self.stat_update_timer.stop()
|
||||
self.watchdog.stop()
|
||||
|
||||
class Watchdog:
|
||||
def __init__(self, proc_stats: ProcStats) -> None:
|
||||
self.proc_stats = proc_stats
|
||||
self.event_loop = proc_stats.event_loop
|
||||
self.blocked_count: int = 0
|
||||
self.last_watch_time: float = 0.
|
||||
self.watchdog_timer = self.event_loop.register_timer(
|
||||
self._watchdog_callback
|
||||
)
|
||||
|
||||
def _watchdog_callback(self, eventtime: float) -> float:
|
||||
time_diff = eventtime - self.last_watch_time
|
||||
if time_diff > REPORT_BLOCKED_TIME:
|
||||
self.blocked_count += 1
|
||||
logging.info(
|
||||
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds"
|
||||
f", total blocked count: {self.blocked_count}")
|
||||
# delay the stat logging so we capture the CPU percentage after
|
||||
# the next cycle
|
||||
self.event_loop.delay_callback(
|
||||
.2, self.proc_stats.log_last_stats, 5)
|
||||
self.last_watch_time = eventtime
|
||||
return eventtime + WATCHDOG_REFRESH_TIME
|
||||
|
||||
def start(self):
|
||||
if not self.watchdog_timer.is_running():
|
||||
self.last_watch_time = self.event_loop.get_loop_time()
|
||||
self.watchdog_timer.start()
|
||||
|
||||
def stop(self):
|
||||
self.watchdog_timer.stop()
|
||||
|
||||
def load_component(config: ConfigHelper) -> ProcStats:
|
||||
return ProcStats(config)
|
||||
@@ -0,0 +1,91 @@
|
||||
# Support for password/token secrets
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import pathlib
|
||||
import logging
|
||||
import configparser
|
||||
import json
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict,
|
||||
Optional,
|
||||
Any
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .file_manager.file_manager import FileManager
|
||||
|
||||
class Secrets:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
server = config.get_server()
|
||||
self.secrets_file: Optional[pathlib.Path] = None
|
||||
path: Optional[str] = config.get("secrets_path", None, deprecate=True)
|
||||
app_args = server.get_app_args()
|
||||
data_path = app_args["data_path"]
|
||||
fpath = pathlib.Path(data_path).joinpath("moonraker.secrets")
|
||||
if not fpath.is_file() and path is not None:
|
||||
fpath = pathlib.Path(path).expanduser().resolve()
|
||||
self.type = "invalid"
|
||||
self.values: Dict[str, Any] = {}
|
||||
fm: FileManager = server.lookup_component("file_manager")
|
||||
fm.add_reserved_path("secrets", fpath, False)
|
||||
if fpath.is_file():
|
||||
self.secrets_file = fpath
|
||||
data = self.secrets_file.read_text()
|
||||
vals = self._parse_json(data)
|
||||
if vals is not None:
|
||||
if not isinstance(vals, dict):
|
||||
server.add_warning(
|
||||
f"[secrets]: option 'secrets_path', top level item in"
|
||||
f" json file '{self.secrets_file}' must be an Object.")
|
||||
return
|
||||
self.values = vals
|
||||
self.type = "json"
|
||||
else:
|
||||
vals = self._parse_ini(data)
|
||||
if vals is None:
|
||||
server.add_warning(
|
||||
"[secrets]: option 'secrets_path', invalid file "
|
||||
f"format, must be json or ini: '{self.secrets_file}'")
|
||||
return
|
||||
self.values = vals
|
||||
self.type = "ini"
|
||||
logging.debug(f"[secrets]: Loaded {self.type} file: "
|
||||
f"{self.secrets_file}")
|
||||
elif path is not None:
|
||||
server.add_warning(
|
||||
"[secrets]: option 'secrets_path', file does not exist: "
|
||||
f"'{self.secrets_file}'")
|
||||
else:
|
||||
logging.debug(
|
||||
"[secrets]: Option `secrets_path` not supplied")
|
||||
|
||||
def _parse_ini(self, data: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
cfg = configparser.ConfigParser(interpolation=None)
|
||||
cfg.read_string(data)
|
||||
return {sec: dict(cfg.items(sec)) for sec in cfg.sections()}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _parse_json(self, data: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
return json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
def get_type(self) -> str:
|
||||
return self.type
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
return self.values[key]
|
||||
|
||||
def get(self, key: str, default: Any = None) -> Any:
|
||||
return self.values.get(key, default)
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Secrets:
|
||||
return Secrets(config)
|
||||
@@ -0,0 +1,304 @@
|
||||
# Generic sensor support
|
||||
#
|
||||
# Copyright (C) 2022 Morton Jonuschat <mjonuschat+moonraker@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
# Component to read additional generic sensor data and make it
|
||||
# available to clients
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass, replace
|
||||
from functools import partial
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
Any,
|
||||
DefaultDict,
|
||||
Deque,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Type,
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .mqtt import MQTTClient
|
||||
|
||||
SENSOR_UPDATE_TIME = 1.0
|
||||
SENSOR_EVENT_NAME = "sensors:sensor_update"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SensorConfiguration:
|
||||
id: str
|
||||
name: str
|
||||
type: str
|
||||
source: str = ""
|
||||
|
||||
|
||||
def _set_result(
|
||||
name: str, value: Union[int, float], store: Dict[str, Union[int, float]]
|
||||
) -> None:
|
||||
if not isinstance(value, (int, float)):
|
||||
store[name] = float(value)
|
||||
else:
|
||||
store[name] = value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Sensor:
|
||||
config: SensorConfiguration
|
||||
values: Dict[str, Deque[Union[int, float]]]
|
||||
|
||||
|
||||
class BaseSensor:
|
||||
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200) -> None:
|
||||
self.server = cfg.get_server()
|
||||
self.error_state: Optional[str] = None
|
||||
|
||||
self.config = SensorConfiguration(
|
||||
id=name,
|
||||
type=cfg.get("type"),
|
||||
name=cfg.get("name", name),
|
||||
)
|
||||
self.last_measurements: Dict[str, Union[int, float]] = {}
|
||||
self.last_value: Dict[str, Union[int, float]] = {}
|
||||
self.values: DefaultDict[str, Deque[Union[int, float]]] = defaultdict(
|
||||
lambda: deque(maxlen=store_size)
|
||||
)
|
||||
|
||||
def _update_sensor_value(self, eventtime: float) -> None:
|
||||
"""
|
||||
Append the last updated value to the store.
|
||||
"""
|
||||
for key, value in self.last_measurements.items():
|
||||
self.values[key].append(value)
|
||||
|
||||
# Copy the last measurements data
|
||||
self.last_value = {**self.last_measurements}
|
||||
|
||||
async def initialize(self) -> bool:
|
||||
"""
|
||||
Sensor initialization executed on Moonraker startup.
|
||||
"""
|
||||
logging.info("Registered sensor '%s'", self.config.name)
|
||||
return True
|
||||
|
||||
def get_sensor_info(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": self.config.id,
|
||||
"friendly_name": self.config.name,
|
||||
"type": self.config.type,
|
||||
"values": self.last_measurements,
|
||||
}
|
||||
|
||||
def get_sensor_measurements(self) -> Dict[str, List[Union[int, float]]]:
|
||||
return {key: list(values) for key, values in self.values.items()}
|
||||
|
||||
def get_name(self) -> str:
|
||||
return self.config.name
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class MQTTSensor(BaseSensor):
|
||||
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200):
|
||||
super().__init__(name=name, cfg=cfg)
|
||||
self.mqtt: MQTTClient = self.server.load_component(cfg, "mqtt")
|
||||
|
||||
self.state_topic: str = cfg.get("state_topic")
|
||||
self.state_response = cfg.load_template("state_response_template", "{payload}")
|
||||
self.config = replace(self.config, source=self.state_topic)
|
||||
self.qos: Optional[int] = cfg.getint("qos", None, minval=0, maxval=2)
|
||||
|
||||
self.server.register_event_handler(
|
||||
"mqtt:disconnected", self._on_mqtt_disconnected
|
||||
)
|
||||
|
||||
def _on_state_update(self, payload: bytes) -> None:
|
||||
measurements: Dict[str, Union[int, float]] = {}
|
||||
context = {
|
||||
"payload": payload.decode(),
|
||||
"set_result": partial(_set_result, store=measurements),
|
||||
}
|
||||
|
||||
try:
|
||||
self.state_response.render(context)
|
||||
except Exception as e:
|
||||
logging.error("Error updating sensor results: %s", e)
|
||||
self.error_state = str(e)
|
||||
else:
|
||||
self.error_state = None
|
||||
self.last_measurements = measurements
|
||||
logging.debug(
|
||||
"Received updated sensor value for %s: %s",
|
||||
self.config.name,
|
||||
self.last_measurements,
|
||||
)
|
||||
|
||||
async def _on_mqtt_disconnected(self):
|
||||
self.error_state = "MQTT Disconnected"
|
||||
self.last_measurements = {}
|
||||
|
||||
async def initialize(self) -> bool:
|
||||
await super().initialize()
|
||||
try:
|
||||
self.mqtt.subscribe_topic(
|
||||
self.state_topic,
|
||||
self._on_state_update,
|
||||
self.qos,
|
||||
)
|
||||
self.error_state = None
|
||||
return True
|
||||
except Exception as e:
|
||||
self.error_state = str(e)
|
||||
return False
|
||||
|
||||
|
||||
class Sensors:
|
||||
__sensor_types: Dict[str, Type[BaseSensor]] = {"MQTT": MQTTSensor}
|
||||
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.store_size = config.getint("sensor_store_size", 1200)
|
||||
prefix_sections = config.get_prefix_sections("sensor")
|
||||
self.sensors: Dict[str, BaseSensor] = {}
|
||||
|
||||
# Register timer to update sensor values in store
|
||||
self.sensors_update_timer = self.server.get_event_loop().register_timer(
|
||||
self._update_sensor_values
|
||||
)
|
||||
|
||||
# Register endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/sensors/list",
|
||||
["GET"],
|
||||
self._handle_sensor_list_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/sensors/info",
|
||||
["GET"],
|
||||
self._handle_sensor_info_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/sensors/measurements",
|
||||
["GET"],
|
||||
self._handle_sensor_measurements_request,
|
||||
)
|
||||
|
||||
# Register notifications
|
||||
self.server.register_notification(SENSOR_EVENT_NAME)
|
||||
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
|
||||
try:
|
||||
try:
|
||||
_, name = cfg.get_name().split(maxsplit=1)
|
||||
except ValueError:
|
||||
raise cfg.error(f"Invalid section name: {cfg.get_name()}")
|
||||
|
||||
logging.info(f"Configuring sensor: {name}")
|
||||
|
||||
sensor_type: str = cfg.get("type")
|
||||
sensor_class: Optional[Type[BaseSensor]] = self.__sensor_types.get(
|
||||
sensor_type.upper(), None
|
||||
)
|
||||
if sensor_class is None:
|
||||
raise config.error(f"Unsupported sensor type: {sensor_type}")
|
||||
|
||||
self.sensors[name] = sensor_class(
|
||||
name=name,
|
||||
cfg=cfg,
|
||||
store_size=self.store_size,
|
||||
)
|
||||
except Exception as e:
|
||||
# Ensures that configuration errors are shown to the user
|
||||
self.server.add_warning(
|
||||
f"Failed to configure sensor [{cfg.get_name()}]\n{e}"
|
||||
)
|
||||
continue
|
||||
|
||||
def _update_sensor_values(self, eventtime: float) -> float:
|
||||
"""
|
||||
Iterate through the sensors and store the last updated value.
|
||||
"""
|
||||
changed_data: Dict[str, Dict[str, Union[int, float]]] = {}
|
||||
for sensor_name, sensor in self.sensors.items():
|
||||
base_value = sensor.last_value
|
||||
sensor._update_sensor_value(eventtime=eventtime)
|
||||
|
||||
# Notify if a change in sensor values was detected
|
||||
if base_value != sensor.last_value:
|
||||
changed_data[sensor_name] = sensor.last_value
|
||||
if changed_data:
|
||||
self.server.send_event(SENSOR_EVENT_NAME, changed_data)
|
||||
|
||||
return eventtime + SENSOR_UPDATE_TIME
|
||||
|
||||
async def component_init(self) -> None:
|
||||
try:
|
||||
logging.debug("Initializing sensor component")
|
||||
for sensor in self.sensors.values():
|
||||
if not await sensor.initialize():
|
||||
self.server.add_warning(
|
||||
f"Sensor '{sensor.get_name()}' failed to initialize"
|
||||
)
|
||||
|
||||
self.sensors_update_timer.start()
|
||||
|
||||
except Exception as e:
|
||||
logging.exception(e)
|
||||
|
||||
async def _handle_sensor_list_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
output = {
|
||||
"sensors": {
|
||||
key: sensor.get_sensor_info() for key, sensor in self.sensors.items()
|
||||
}
|
||||
}
|
||||
return output
|
||||
|
||||
async def _handle_sensor_info_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
sensor_name: str = web_request.get_str("sensor")
|
||||
if sensor_name not in self.sensors:
|
||||
raise self.server.error(f"No valid sensor named {sensor_name}")
|
||||
|
||||
sensor = self.sensors[sensor_name]
|
||||
|
||||
return sensor.get_sensor_info()
|
||||
|
||||
async def _handle_sensor_measurements_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
sensor_name: str = web_request.get_str("sensor", "")
|
||||
if sensor_name and sensor_name not in self.sensors:
|
||||
raise self.server.error(f"No valid sensor named {sensor_name}")
|
||||
|
||||
output = {
|
||||
key: sensor.get_sensor_measurements()
|
||||
for key, sensor in self.sensors.items()
|
||||
if sensor_name is "" or key == sensor_name
|
||||
}
|
||||
|
||||
return output
|
||||
|
||||
def close(self) -> None:
|
||||
self.sensors_update_timer.stop()
|
||||
for sensor in self.sensors.values():
|
||||
sensor.close()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Sensors:
|
||||
return Sensors(config)
|
||||
@@ -0,0 +1,397 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import shlex
|
||||
import logging
|
||||
import signal
|
||||
import asyncio
|
||||
from ..utils import ServerError
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
List,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Set,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
OutputCallback = Optional[Callable[[bytes], None]]
|
||||
|
||||
class ShellCommandError(ServerError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
return_code: Optional[int],
|
||||
stdout: Optional[bytes] = b"",
|
||||
stderr: Optional[bytes] = b"",
|
||||
status_code: int = 500
|
||||
) -> None:
|
||||
super().__init__(message, status_code=status_code)
|
||||
self.stdout = stdout or b""
|
||||
self.stderr = stderr or b""
|
||||
self.return_code = return_code
|
||||
|
||||
class ShellCommandProtocol(asyncio.subprocess.SubprocessStreamProtocol):
|
||||
def __init__(
|
||||
self,
|
||||
limit: int,
|
||||
loop: asyncio.events.AbstractEventLoop,
|
||||
program_name: str = "",
|
||||
std_out_cb: OutputCallback = None,
|
||||
std_err_cb: OutputCallback = None,
|
||||
log_stderr: bool = False
|
||||
) -> None:
|
||||
self._loop = loop
|
||||
self._pipe_fds: List[int] = []
|
||||
super().__init__(limit, loop)
|
||||
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.pending_data: List[bytes] = [b"", b""]
|
||||
|
||||
def connection_made(
|
||||
self, transport: asyncio.transports.BaseTransport
|
||||
) -> None:
|
||||
self._transport = transport
|
||||
assert isinstance(transport, asyncio.SubprocessTransport)
|
||||
stdout_transport = transport.get_pipe_transport(1)
|
||||
if stdout_transport is not None:
|
||||
self._pipe_fds.append(1)
|
||||
|
||||
stderr_transport = transport.get_pipe_transport(2)
|
||||
if stderr_transport is not None:
|
||||
self._pipe_fds.append(2)
|
||||
|
||||
stdin_transport = transport.get_pipe_transport(0)
|
||||
if stdin_transport is not None:
|
||||
self.stdin = asyncio.streams.StreamWriter(
|
||||
stdin_transport, # type: ignore
|
||||
protocol=self,
|
||||
reader=None,
|
||||
loop=self._loop
|
||||
)
|
||||
|
||||
def pipe_data_received(self, fd: int, data: bytes | str) -> None:
|
||||
cb = None
|
||||
data_idx = fd - 1
|
||||
if fd == 1:
|
||||
cb = self.std_out_cb
|
||||
elif fd == 2:
|
||||
cb = self.std_err_cb
|
||||
if self.log_stderr:
|
||||
if isinstance(data, bytes):
|
||||
msg = data.decode(errors='ignore')
|
||||
else:
|
||||
msg = data
|
||||
logging.info(f"{self.program_name}: {msg}")
|
||||
if cb is not None:
|
||||
if isinstance(data, str):
|
||||
data = data.encode()
|
||||
lines = data.split(b'\n')
|
||||
lines[0] = self.pending_data[data_idx] + lines[0]
|
||||
self.pending_data[data_idx] = lines.pop()
|
||||
for line in lines:
|
||||
if not line:
|
||||
continue
|
||||
cb(line)
|
||||
|
||||
def pipe_connection_lost(
|
||||
self, fd: int, exc: Exception | None
|
||||
) -> None:
|
||||
cb = None
|
||||
pending = b""
|
||||
if fd == 1:
|
||||
cb = self.std_out_cb
|
||||
pending = self.pending_data[0]
|
||||
elif fd == 2:
|
||||
cb = self.std_err_cb
|
||||
pending = self.pending_data[1]
|
||||
if pending and cb is not None:
|
||||
cb(pending)
|
||||
super().pipe_connection_lost(fd, exc)
|
||||
|
||||
|
||||
class ShellCommand:
|
||||
IDX_SIGINT = 0
|
||||
IDX_SIGTERM = 1
|
||||
IDX_SIGKILL = 2
|
||||
def __init__(
|
||||
self,
|
||||
factory: ShellCommandFactory,
|
||||
cmd: str,
|
||||
std_out_callback: OutputCallback,
|
||||
std_err_callback: OutputCallback,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
log_stderr: bool = False,
|
||||
cwd: Optional[str] = None
|
||||
) -> None:
|
||||
self.factory = factory
|
||||
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: Optional[asyncio.subprocess.Process] = None
|
||||
self.cancelled = False
|
||||
self.return_code: Optional[int] = None
|
||||
self.run_lock = asyncio.Lock()
|
||||
|
||||
async def cancel(self, sig_idx: int = 1) -> None:
|
||||
if self.cancelled:
|
||||
return
|
||||
self.cancelled = True
|
||||
if self.proc is not None:
|
||||
exit_success = False
|
||||
sig_idx = min(2, max(0, sig_idx))
|
||||
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
|
||||
for sig in sigs:
|
||||
try:
|
||||
self.proc.send_signal(sig)
|
||||
ret = self.proc.wait()
|
||||
await asyncio.wait_for(ret, timeout=2.)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
logging.debug(f"Command '{self.name}' exited with "
|
||||
f"signal: {sig.name}")
|
||||
exit_success = True
|
||||
break
|
||||
if not exit_success:
|
||||
logging.info(f"WARNING: {self.name} did not cleanly exit")
|
||||
|
||||
def get_return_code(self) -> Optional[int]:
|
||||
return self.return_code
|
||||
|
||||
def _reset_command_data(self) -> None:
|
||||
self.return_code = self.proc = None
|
||||
self.cancelled = False
|
||||
|
||||
async def run(
|
||||
self,
|
||||
timeout: float = 2.,
|
||||
verbose: bool = True,
|
||||
log_complete: bool = True,
|
||||
sig_idx: int = 1,
|
||||
proc_input: Optional[str] = None,
|
||||
success_codes: Optional[List[int]] = None
|
||||
) -> bool:
|
||||
async with self.run_lock:
|
||||
self.factory.add_running_command(self)
|
||||
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
|
||||
created = await self._create_subprocess(
|
||||
verbose, proc_input is not None)
|
||||
if not created:
|
||||
self.factory.remove_running_command(self)
|
||||
return False
|
||||
assert self.proc is not None
|
||||
try:
|
||||
if proc_input is not None:
|
||||
ret: Coroutine = self.proc.communicate(
|
||||
input=proc_input.encode())
|
||||
else:
|
||||
ret = self.proc.wait()
|
||||
await asyncio.wait_for(ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
await self.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
self.factory.remove_running_command(self)
|
||||
return self._check_proc_success(
|
||||
complete, log_complete, success_codes
|
||||
)
|
||||
|
||||
async def run_with_response(
|
||||
self,
|
||||
timeout: float = 2.,
|
||||
retries: int = 1,
|
||||
log_complete: bool = True,
|
||||
sig_idx: int = 1,
|
||||
proc_input: Optional[str] = None,
|
||||
success_codes: Optional[List[int]] = None
|
||||
) -> str:
|
||||
async with self.run_lock:
|
||||
self.factory.add_running_command(self)
|
||||
retries = max(1, retries)
|
||||
stdin: Optional[bytes] = None
|
||||
if proc_input is not None:
|
||||
stdin = proc_input.encode()
|
||||
while retries > 0:
|
||||
self._reset_command_data()
|
||||
timed_out = False
|
||||
stdout = stderr = b""
|
||||
if await self._create_subprocess(has_input=stdin is not None):
|
||||
assert self.proc is not None
|
||||
try:
|
||||
ret = self.proc.communicate(input=stdin)
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
timed_out = True
|
||||
await self.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
if self.log_stderr and stderr:
|
||||
logging.info(
|
||||
f"{self.command[0]}: "
|
||||
f"{stderr.decode(errors='ignore')}")
|
||||
if self._check_proc_success(
|
||||
complete, log_complete, success_codes
|
||||
):
|
||||
self.factory.remove_running_command(self)
|
||||
return stdout.decode(errors='ignore').rstrip("\n")
|
||||
if stdout:
|
||||
logging.debug(
|
||||
f"Shell command '{self.name}' output:"
|
||||
f"\n{stdout.decode(errors='ignore')}")
|
||||
if self.cancelled and not timed_out:
|
||||
break
|
||||
retries -= 1
|
||||
await asyncio.sleep(.5)
|
||||
self.factory.remove_running_command(self)
|
||||
raise ShellCommandError(
|
||||
f"Error running shell command: '{self.name}'",
|
||||
self.return_code, stdout, stderr)
|
||||
|
||||
async def _create_subprocess(
|
||||
self,
|
||||
use_callbacks: bool = False,
|
||||
has_input: bool = False
|
||||
) -> bool:
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
def protocol_factory():
|
||||
return ShellCommandProtocol(
|
||||
limit=2**20, loop=loop, program_name=self.command[0],
|
||||
std_out_cb=self.std_out_cb, std_err_cb=self.std_err_cb,
|
||||
log_stderr=self.log_stderr)
|
||||
try:
|
||||
stdpipe: Optional[int] = None
|
||||
if has_input:
|
||||
stdpipe = asyncio.subprocess.PIPE
|
||||
if self.std_err_cb is not None or self.log_stderr:
|
||||
errpipe = asyncio.subprocess.PIPE
|
||||
else:
|
||||
errpipe = asyncio.subprocess.STDOUT
|
||||
if use_callbacks:
|
||||
transport, protocol = await loop.subprocess_exec(
|
||||
protocol_factory, *self.command, stdin=stdpipe,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=errpipe, env=self.env, cwd=self.cwd)
|
||||
self.proc = asyncio.subprocess.Process(
|
||||
transport, protocol, loop)
|
||||
else:
|
||||
self.proc = await asyncio.create_subprocess_exec(
|
||||
*self.command, stdin=stdpipe,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=errpipe, env=self.env, cwd=self.cwd)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _check_proc_success(
|
||||
self,
|
||||
complete: bool,
|
||||
log_complete: bool,
|
||||
success_codes: Optional[List[int]] = None
|
||||
) -> bool:
|
||||
assert self.proc is not None
|
||||
if success_codes is None:
|
||||
success_codes = [0]
|
||||
self.return_code = self.proc.returncode
|
||||
success = self.return_code in success_codes 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 __init__(self, config: ConfigHelper) -> None:
|
||||
self.running_commands: Set[ShellCommand] = set()
|
||||
|
||||
def add_running_command(self, cmd: ShellCommand) -> None:
|
||||
self.running_commands.add(cmd)
|
||||
|
||||
def remove_running_command(self, cmd: ShellCommand) -> None:
|
||||
try:
|
||||
self.running_commands.remove(cmd)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def build_shell_command(
|
||||
self,
|
||||
cmd: str,
|
||||
callback: OutputCallback = None,
|
||||
std_err_callback: OutputCallback = None,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
log_stderr: bool = False,
|
||||
cwd: Optional[str] = None
|
||||
) -> ShellCommand:
|
||||
return ShellCommand(
|
||||
self, cmd, callback, std_err_callback, env, log_stderr, cwd
|
||||
)
|
||||
|
||||
def exec_cmd(
|
||||
self,
|
||||
cmd: str,
|
||||
timeout: float = 2.,
|
||||
retries: int = 1,
|
||||
sig_idx: int = 1,
|
||||
proc_input: Optional[str] = None,
|
||||
log_complete: bool = True,
|
||||
log_stderr: bool = False,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
cwd: Optional[str] = None,
|
||||
success_codes: Optional[List[int]] = None
|
||||
) -> Awaitable:
|
||||
scmd = ShellCommand(self, cmd, None, None, env,
|
||||
log_stderr, cwd)
|
||||
coro = scmd.run_with_response(
|
||||
timeout, retries, log_complete, sig_idx,
|
||||
proc_input, success_codes
|
||||
)
|
||||
return asyncio.create_task(coro)
|
||||
|
||||
async def close(self) -> None:
|
||||
for cmd in self.running_commands:
|
||||
await cmd.cancel()
|
||||
|
||||
def load_component(config: ConfigHelper) -> ShellCommandFactory:
|
||||
return ShellCommandFactory(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,111 @@
|
||||
# Template Factory helper
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import asyncio
|
||||
import jinja2
|
||||
import json
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..server import Server
|
||||
from ..confighelper import ConfigHelper
|
||||
from .secrets import Secrets
|
||||
|
||||
class TemplateFactory:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
secrets: Secrets = self.server.load_component(config, 'secrets')
|
||||
self.jenv = jinja2.Environment('{%', '%}', '{', '}')
|
||||
self.async_env = jinja2.Environment(
|
||||
'{%', '%}', '{', '}', enable_async=True
|
||||
)
|
||||
self.ui_env = jinja2.Environment(enable_async=True)
|
||||
self.jenv.add_extension("jinja2.ext.do")
|
||||
self.jenv.filters['fromjson'] = json.loads
|
||||
self.async_env.add_extension("jinja2.ext.do")
|
||||
self.async_env.filters['fromjson'] = json.loads
|
||||
self.ui_env.add_extension("jinja2.ext.do")
|
||||
self.ui_env.filters['fromjson'] = json.loads
|
||||
self.add_environment_global('raise_error', self._raise_error)
|
||||
self.add_environment_global('secrets', secrets)
|
||||
|
||||
def add_environment_global(self, name: str, value: Any):
|
||||
if name in self.jenv.globals:
|
||||
raise self.server.error(
|
||||
f"Jinja 2 environment already contains global {name}")
|
||||
self.jenv.globals[name] = value
|
||||
self.async_env.globals[name] = value
|
||||
|
||||
def _raise_error(self, err_msg: str, err_code: int = 400) -> None:
|
||||
raise self.server.error(err_msg, err_code)
|
||||
|
||||
def create_template(self,
|
||||
source: str,
|
||||
is_async: bool = False
|
||||
) -> JinjaTemplate:
|
||||
env = self.async_env if is_async else self.jenv
|
||||
try:
|
||||
template = env.from_string(source)
|
||||
except Exception:
|
||||
logging.exception(f"Error creating template from source:\n{source}")
|
||||
raise
|
||||
return JinjaTemplate(source, self.server, template, is_async)
|
||||
|
||||
def create_ui_template(self, source: str) -> JinjaTemplate:
|
||||
try:
|
||||
template = self.ui_env.from_string(source)
|
||||
except Exception:
|
||||
logging.exception(f"Error creating template from source:\n{source}")
|
||||
raise
|
||||
return JinjaTemplate(source, self.server, template, True)
|
||||
|
||||
|
||||
class JinjaTemplate:
|
||||
def __init__(self,
|
||||
source: str,
|
||||
server: Server,
|
||||
template: jinja2.Template,
|
||||
is_async: bool
|
||||
) -> None:
|
||||
self.server = server
|
||||
self.orig_source = source
|
||||
self.template = template
|
||||
self.is_async = is_async
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.orig_source
|
||||
|
||||
def render(self, context: Dict[str, Any] = {}) -> str:
|
||||
if self.is_async:
|
||||
raise self.server.error(
|
||||
"Cannot render async templates with the render() method"
|
||||
", use render_async()")
|
||||
try:
|
||||
return self.template.render(context).strip()
|
||||
except Exception as e:
|
||||
msg = "Error rending Jinja2 Template"
|
||||
if self.server.is_configured():
|
||||
raise self.server.error(msg, 500) from e
|
||||
raise self.server.config_error(msg) from e
|
||||
|
||||
async def render_async(self, context: Dict[str, Any] = {}) -> str:
|
||||
try:
|
||||
ret = await self.template.render_async(context)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise self.server.error("Error rending Jinja2 Template", 500) from e
|
||||
return ret.strip()
|
||||
|
||||
def load_component(config: ConfigHelper) -> TemplateFactory:
|
||||
return TemplateFactory(config)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Package definition for the update_manager
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
from . import update_manager as um
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
|
||||
def load_component(config: ConfigHelper) -> um.UpdateManager:
|
||||
return um.load_component(config)
|
||||
@@ -0,0 +1,391 @@
|
||||
# Deploy updates for applications managed by Moonraker
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from .base_deploy import BaseDeploy
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
Tuple
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from .update_manager import CommandHelper
|
||||
from ..machine import Machine
|
||||
from ..file_manager.file_manager import FileManager
|
||||
|
||||
MIN_PIP_VERSION = (23, 0)
|
||||
|
||||
SUPPORTED_CHANNELS = {
|
||||
"zip": ["stable", "beta"],
|
||||
"git_repo": ["dev", "beta"]
|
||||
}
|
||||
TYPE_TO_CHANNEL = {
|
||||
"zip": "stable",
|
||||
"zip_beta": "beta",
|
||||
"git_repo": "dev"
|
||||
}
|
||||
|
||||
class AppDeploy(BaseDeploy):
|
||||
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
|
||||
super().__init__(config, cmd_helper, prefix="Application")
|
||||
self.config = config
|
||||
type_choices = list(TYPE_TO_CHANNEL.keys())
|
||||
self.type = config.get('type').lower()
|
||||
if self.type not in type_choices:
|
||||
raise config.error(
|
||||
f"Config Error: Section [{config.get_name()}], Option "
|
||||
f"'type: {self.type}': value must be one "
|
||||
f"of the following choices: {type_choices}"
|
||||
)
|
||||
self.channel = config.get(
|
||||
"channel", TYPE_TO_CHANNEL[self.type]
|
||||
)
|
||||
if self.type == "zip_beta":
|
||||
self.server.add_warning(
|
||||
f"Config Section [{config.get_name()}], Option 'type: "
|
||||
"zip_beta', value 'zip_beta' is deprecated. Set 'type' "
|
||||
"to zip and 'channel' to 'beta'")
|
||||
self.type = "zip"
|
||||
self.path = pathlib.Path(
|
||||
config.get('path')).expanduser().resolve()
|
||||
if (
|
||||
self.name not in ["moonraker", "klipper"]
|
||||
and not self.path.joinpath(".writeable").is_file()
|
||||
):
|
||||
fm: FileManager = self.server.lookup_component("file_manager")
|
||||
fm.add_reserved_path(f"update_manager {self.name}", self.path)
|
||||
executable = config.get('env', None)
|
||||
if self.channel not in SUPPORTED_CHANNELS[self.type]:
|
||||
raise config.error(
|
||||
f"Invalid Channel '{self.channel}' for config "
|
||||
f"section [{config.get_name()}], type: {self.type}")
|
||||
self._verify_path(config, 'path', self.path, check_file=False)
|
||||
self.executable: Optional[pathlib.Path] = None
|
||||
self.pip_cmd: Optional[str] = None
|
||||
self.pip_version: Tuple[int, ...] = tuple()
|
||||
self.venv_args: Optional[str] = None
|
||||
if executable is not None:
|
||||
self.executable = pathlib.Path(executable).expanduser()
|
||||
self._verify_path(config, 'env', self.executable, check_exe=True)
|
||||
# Detect if executable is actually located in a virtualenv
|
||||
# by checking the parent for the activation script
|
||||
act_path = self.executable.parent.joinpath("activate")
|
||||
while not act_path.is_file():
|
||||
if self.executable.is_symlink():
|
||||
self.executable = pathlib.Path(os.readlink(self.executable))
|
||||
act_path = self.executable.parent.joinpath("activate")
|
||||
else:
|
||||
break
|
||||
if act_path.is_file():
|
||||
venv_dir = self.executable.parent.parent
|
||||
self.log_info(f"Detected virtualenv: {venv_dir}")
|
||||
pip_exe = self.executable.parent.joinpath("pip")
|
||||
if pip_exe.is_file():
|
||||
self.pip_cmd = f"{self.executable} -m pip"
|
||||
else:
|
||||
self.log_info("Unable to locate pip executable")
|
||||
else:
|
||||
self.log_info(
|
||||
f"Unable to detect virtualenv at: {executable}"
|
||||
)
|
||||
self.executable = pathlib.Path(executable).expanduser()
|
||||
self.venv_args = config.get('venv_args', None)
|
||||
self.info_tags: List[str] = config.getlist("info_tags", [])
|
||||
self.managed_services: List[str] = []
|
||||
svc_default = []
|
||||
if config.getboolean("is_system_service", True):
|
||||
svc_default.append(self.name)
|
||||
svc_choices = [self.name, "klipper", "moonraker"]
|
||||
services: List[str] = config.getlist(
|
||||
"managed_services", svc_default, separator=None
|
||||
)
|
||||
for svc in services:
|
||||
if svc not in svc_choices:
|
||||
raw = " ".join(services)
|
||||
self.server.add_warning(
|
||||
f"[{config.get_name()}]: Option 'managed_services: {raw}' "
|
||||
f"contains an invalid value '{svc}'. All values must be "
|
||||
f"one of the following choices: {svc_choices}"
|
||||
)
|
||||
break
|
||||
for svc in svc_choices:
|
||||
if svc in services and svc not in self.managed_services:
|
||||
self.managed_services.append(svc)
|
||||
logging.debug(
|
||||
f"Extension {self.name} managed services: {self.managed_services}"
|
||||
)
|
||||
# We need to fetch all potential options for an Application. Not
|
||||
# all options apply to each subtype, however we can't limit the
|
||||
# options in children if we want to switch between channels and
|
||||
# satisfy the confighelper's requirements.
|
||||
self.moved_origin: Optional[str] = config.get('moved_origin', None)
|
||||
self.origin: str = config.get('origin')
|
||||
self.primary_branch = config.get("primary_branch", "master")
|
||||
self.npm_pkg_json: Optional[pathlib.Path] = None
|
||||
if config.getboolean("enable_node_updates", False):
|
||||
self.npm_pkg_json = self.path.joinpath("package-lock.json")
|
||||
self._verify_path(config, 'enable_node_updates', self.npm_pkg_json)
|
||||
self.python_reqs: Optional[pathlib.Path] = None
|
||||
if self.executable is not None:
|
||||
self.python_reqs = self.path.joinpath(config.get("requirements"))
|
||||
self._verify_path(config, 'requirements', self.python_reqs)
|
||||
self.install_script: Optional[pathlib.Path] = None
|
||||
install_script = config.get('install_script', None)
|
||||
if install_script is not None:
|
||||
self.install_script = self.path.joinpath(install_script).resolve()
|
||||
self._verify_path(config, 'install_script', self.install_script)
|
||||
|
||||
@staticmethod
|
||||
def _is_git_repo(app_path: Union[str, pathlib.Path]) -> bool:
|
||||
if isinstance(app_path, str):
|
||||
app_path = pathlib.Path(app_path).expanduser()
|
||||
return app_path.joinpath('.git').exists()
|
||||
|
||||
async def initialize(self) -> Dict[str, Any]:
|
||||
storage = await super().initialize()
|
||||
self.need_channel_update = storage.get("need_channel_update", False)
|
||||
self._is_valid = storage.get("is_valid", False)
|
||||
self.pip_version = tuple(storage.get("pip_version", []))
|
||||
if self.pip_version:
|
||||
ver_str = ".".join([str(part) for part in self.pip_version])
|
||||
self.log_info(f"Stored pip version: {ver_str}")
|
||||
return storage
|
||||
|
||||
def _verify_path(
|
||||
self,
|
||||
config: ConfigHelper,
|
||||
option: str,
|
||||
path: pathlib.Path,
|
||||
check_file: bool = True,
|
||||
check_exe: bool = False
|
||||
) -> None:
|
||||
base_msg = (
|
||||
f"Invalid path for option `{option}` in section "
|
||||
f"[{config.get_name()}]: Path `{path}`"
|
||||
)
|
||||
if not path.exists():
|
||||
raise config.error(f"{base_msg} does not exist")
|
||||
if check_file and not path.is_file():
|
||||
raise config.error(f"{base_msg} is not a file")
|
||||
if check_exe and not os.access(path, os.X_OK):
|
||||
raise config.error(f"{base_msg} is not executable")
|
||||
|
||||
def check_need_channel_swap(self) -> bool:
|
||||
return self.need_channel_update
|
||||
|
||||
def get_configured_type(self) -> str:
|
||||
return self.type
|
||||
|
||||
def check_same_paths(self,
|
||||
app_path: Union[str, pathlib.Path],
|
||||
executable: Union[str, pathlib.Path]
|
||||
) -> bool:
|
||||
if isinstance(app_path, str):
|
||||
app_path = pathlib.Path(app_path)
|
||||
if isinstance(executable, str):
|
||||
executable = pathlib.Path(executable)
|
||||
app_path = app_path.expanduser()
|
||||
executable = executable.expanduser()
|
||||
if self.executable is None:
|
||||
return False
|
||||
try:
|
||||
return self.path.samefile(app_path) and \
|
||||
self.executable.samefile(executable)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def reinstall(self):
|
||||
raise NotImplementedError
|
||||
|
||||
async def restart_service(self):
|
||||
if not self.managed_services:
|
||||
return
|
||||
is_full = self.cmd_helper.is_full_update()
|
||||
for svc in self.managed_services:
|
||||
if is_full and svc != self.name:
|
||||
self.notify_status(f"Service {svc} restart postponed...")
|
||||
self.cmd_helper.add_pending_restart(svc)
|
||||
continue
|
||||
self.cmd_helper.remove_pending_restart(svc)
|
||||
self.notify_status(f"Restarting service {svc}...")
|
||||
if svc == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
event_loop = self.server.get_event_loop()
|
||||
event_loop.delay_callback(.1, self._do_restart, svc)
|
||||
else:
|
||||
await self._do_restart(svc)
|
||||
|
||||
async def _do_restart(self, svc_name: str) -> None:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
try:
|
||||
await machine.do_service_action("restart", svc_name)
|
||||
except Exception:
|
||||
if svc_name == "moonraker":
|
||||
# We will always get an error when restarting moonraker
|
||||
# from within the child process, so ignore it
|
||||
return
|
||||
raise self.log_exc("Error restarting service")
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'channel': self.channel,
|
||||
'debug_enabled': self.server.is_debug_enabled(),
|
||||
'need_channel_update': self.need_channel_update,
|
||||
'is_valid': self._is_valid,
|
||||
'configured_type': self.type,
|
||||
'info_tags': self.info_tags
|
||||
}
|
||||
|
||||
def get_persistent_data(self) -> Dict[str, Any]:
|
||||
storage = super().get_persistent_data()
|
||||
storage['is_valid'] = self._is_valid
|
||||
storage['need_channel_update'] = self.need_channel_update
|
||||
storage['pip_version'] = list(self.pip_version)
|
||||
return storage
|
||||
|
||||
async def _get_file_hash(self,
|
||||
filename: Optional[pathlib.Path]
|
||||
) -> Optional[str]:
|
||||
if filename is None or not filename.is_file():
|
||||
return None
|
||||
|
||||
def hash_func(f: pathlib.Path) -> str:
|
||||
return hashlib.sha256(f.read_bytes()).hexdigest()
|
||||
try:
|
||||
event_loop = self.server.get_event_loop()
|
||||
return await event_loop.run_in_thread(hash_func, filename)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
async def _check_need_update(self,
|
||||
prev_hash: Optional[str],
|
||||
filename: Optional[pathlib.Path]
|
||||
) -> bool:
|
||||
cur_hash = await self._get_file_hash(filename)
|
||||
if prev_hash is None or cur_hash is None:
|
||||
return False
|
||||
return prev_hash != cur_hash
|
||||
|
||||
async def _install_packages(self, package_list: List[str]) -> None:
|
||||
self.notify_status("Installing system dependencies...")
|
||||
# Install packages with apt-get
|
||||
try:
|
||||
await self.cmd_helper.install_packages(
|
||||
package_list, timeout=3600., notify=True)
|
||||
except Exception:
|
||||
self.log_exc("Error updating packages")
|
||||
return
|
||||
|
||||
async def _update_python_requirements(
|
||||
self, requirements: Union[pathlib.Path, List[str]]
|
||||
) -> None:
|
||||
if self.pip_cmd is None:
|
||||
return
|
||||
await self._update_pip()
|
||||
# Update python dependencies
|
||||
if isinstance(requirements, pathlib.Path):
|
||||
if not requirements.is_file():
|
||||
self.log_info(
|
||||
f"Invalid path to requirements_file '{requirements}'")
|
||||
return
|
||||
args = f"-r {requirements}"
|
||||
else:
|
||||
args = " ".join(requirements)
|
||||
self.notify_status("Updating python packages...")
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"{self.pip_cmd} install {args}", timeout=1200., notify=True,
|
||||
retries=3
|
||||
)
|
||||
except Exception:
|
||||
self.log_exc("Error updating python requirements")
|
||||
|
||||
async def _update_pip(self) -> None:
|
||||
if self.pip_cmd is None:
|
||||
return
|
||||
update_ver = await self._check_pip_version()
|
||||
if update_ver is None:
|
||||
return
|
||||
cur_vstr = ".".join([str(part) for part in self.pip_version])
|
||||
self.notify_status(
|
||||
f"Updating pip from version {cur_vstr} to {update_ver}..."
|
||||
)
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"{self.pip_cmd} install pip=={update_ver}",
|
||||
timeout=1200., notify=True, retries=3
|
||||
)
|
||||
except Exception:
|
||||
self.log_exc("Error updating python pip")
|
||||
|
||||
async def _check_pip_version(self) -> Optional[str]:
|
||||
if self.pip_cmd is None:
|
||||
return None
|
||||
self.notify_status("Checking pip version...")
|
||||
try:
|
||||
data: str = await self.cmd_helper.run_cmd_with_response(
|
||||
f"{self.pip_cmd} --version", timeout=30., retries=3
|
||||
)
|
||||
match = re.match(
|
||||
r"^pip ([0-9.]+) from .+? \(python ([0-9.]+)\)$", data.strip()
|
||||
)
|
||||
if match is None:
|
||||
return None
|
||||
pipver_str: str = match.group(1)
|
||||
pyver_str: str = match.group(2)
|
||||
pipver = tuple([int(part) for part in pipver_str.split(".")])
|
||||
pyver = tuple([int(part) for part in pyver_str.split(".")])
|
||||
except Exception:
|
||||
self.log_exc("Error Getting Pip Version")
|
||||
return None
|
||||
self.pip_version = pipver
|
||||
if not self.pip_version:
|
||||
return None
|
||||
self.log_info(
|
||||
f"Dectected pip version: {pipver_str}, Python {pyver_str}"
|
||||
)
|
||||
if pyver < (3, 7):
|
||||
return None
|
||||
if self.pip_version < MIN_PIP_VERSION:
|
||||
return ".".join([str(ver) for ver in MIN_PIP_VERSION])
|
||||
return None
|
||||
|
||||
async def _build_virtualenv(self) -> None:
|
||||
if self.executable is None or self.venv_args is None:
|
||||
return
|
||||
bin_dir = self.executable.parent
|
||||
env_path = bin_dir.parent.resolve()
|
||||
self.notify_status(f"Creating virtualenv at: {env_path}...")
|
||||
if env_path.exists():
|
||||
shutil.rmtree(env_path)
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
|
||||
except Exception:
|
||||
self.log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
if not self.executable.exists():
|
||||
raise self.log_exc("Failed to create new virtualenv", False)
|
||||
@@ -0,0 +1,61 @@
|
||||
# Moonraker/Klipper update configuration
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
import copy
|
||||
from ...utils import source_info
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from ..database import MoonrakerDatabase
|
||||
|
||||
KLIPPER_DEFAULT_PATH = os.path.expanduser("~/klipper")
|
||||
KLIPPER_DEFAULT_EXEC = os.path.expanduser("~/klippy-env/bin/python")
|
||||
|
||||
BASE_CONFIG: Dict[str, Dict[str, str]] = {
|
||||
"moonraker": {
|
||||
"origin": "https://github.com/arksine/moonraker.git",
|
||||
"requirements": "scripts/moonraker-requirements.txt",
|
||||
"venv_args": "-p python3",
|
||||
"install_script": "scripts/install-moonraker.sh",
|
||||
"host_repo": "arksine/moonraker",
|
||||
"env": sys.executable,
|
||||
"path": str(source_info.source_path()),
|
||||
"managed_services": "moonraker"
|
||||
},
|
||||
"klipper": {
|
||||
"moved_origin": "https://github.com/kevinoconnor/klipper.git",
|
||||
"origin": "https://github.com/Klipper3d/klipper.git",
|
||||
"requirements": "scripts/klippy-requirements.txt",
|
||||
"venv_args": "-p python2",
|
||||
"install_script": "scripts/install-octopi.sh",
|
||||
"host_repo": "arksine/moonraker",
|
||||
"managed_services": "klipper"
|
||||
}
|
||||
}
|
||||
|
||||
def get_base_configuration(config: ConfigHelper, channel: str) -> ConfigHelper:
|
||||
server = config.get_server()
|
||||
base_cfg = copy.deepcopy(BASE_CONFIG)
|
||||
app_type = "zip" if channel == "stable" else "git_repo"
|
||||
base_cfg["moonraker"]["channel"] = channel
|
||||
base_cfg["moonraker"]["type"] = app_type
|
||||
base_cfg["klipper"]["channel"] = channel
|
||||
base_cfg["klipper"]["type"] = app_type
|
||||
db: MoonrakerDatabase = server.lookup_component('database')
|
||||
base_cfg["klipper"]["path"] = db.get_item(
|
||||
"moonraker", "update_manager.klipper_path", KLIPPER_DEFAULT_PATH
|
||||
).result()
|
||||
base_cfg["klipper"]["env"] = db.get_item(
|
||||
"moonraker", "update_manager.klipper_exec", KLIPPER_DEFAULT_EXEC
|
||||
).result()
|
||||
return config.read_supplemental_dict(base_cfg)
|
||||
@@ -0,0 +1,97 @@
|
||||
# Base Deployment Interface
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import time
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any, Optional
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from ...utils import ServerError
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
class BaseDeploy:
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
cmd_helper: CommandHelper,
|
||||
name: Optional[str] = None,
|
||||
prefix: str = "",
|
||||
cfg_hash: Optional[str] = None
|
||||
) -> None:
|
||||
if name is None:
|
||||
name = config.get_name().split(maxsplit=1)[-1]
|
||||
if name.startswith("client "):
|
||||
# allow deprecated [update_manager client app] style names
|
||||
name = name[7:]
|
||||
self.name = name
|
||||
if prefix:
|
||||
prefix = f"{prefix} {self.name}: "
|
||||
self.prefix = prefix
|
||||
self.server = config.get_server()
|
||||
self.cmd_helper = cmd_helper
|
||||
self.refresh_interval = cmd_helper.get_refresh_interval()
|
||||
refresh_interval = config.getint('refresh_interval', None)
|
||||
if refresh_interval is not None:
|
||||
self.refresh_interval = refresh_interval * 60 * 60
|
||||
if cfg_hash is None:
|
||||
cfg_hash = config.get_hash().hexdigest()
|
||||
self.cfg_hash = cfg_hash
|
||||
|
||||
async def initialize(self) -> Dict[str, Any]:
|
||||
umdb = self.cmd_helper.get_umdb()
|
||||
storage: Dict[str, Any] = await umdb.get(self.name, {})
|
||||
self.last_refresh_time: float = storage.get('last_refresh_time', 0.0)
|
||||
self.last_cfg_hash: str = storage.get('last_config_hash', "")
|
||||
return storage
|
||||
|
||||
def needs_refresh(self) -> bool:
|
||||
next_refresh_time = self.last_refresh_time + self.refresh_interval
|
||||
return (
|
||||
self.cfg_hash != self.last_cfg_hash or
|
||||
time.time() > next_refresh_time
|
||||
)
|
||||
|
||||
def get_last_refresh_time(self) -> float:
|
||||
return self.last_refresh_time
|
||||
|
||||
async def refresh(self) -> None:
|
||||
pass
|
||||
|
||||
async def update(self) -> bool:
|
||||
return False
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
return {}
|
||||
|
||||
def get_persistent_data(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'last_config_hash': self.cfg_hash,
|
||||
'last_refresh_time': self.last_refresh_time
|
||||
}
|
||||
|
||||
def _save_state(self) -> None:
|
||||
umdb = self.cmd_helper.get_umdb()
|
||||
self.last_refresh_time = time.time()
|
||||
self.last_cfg_hash = self.cfg_hash
|
||||
umdb[self.name] = self.get_persistent_data()
|
||||
|
||||
def log_exc(self, msg: str, traceback: bool = True) -> ServerError:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
if traceback:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return self.server.error(msg)
|
||||
|
||||
def log_info(self, msg: str) -> None:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
logging.info(log_msg)
|
||||
|
||||
def notify_status(self, msg: str, is_complete: bool = False) -> None:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
logging.debug(log_msg)
|
||||
self.cmd_helper.notify_update_response(log_msg, is_complete)
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,431 @@
|
||||
# Zip Application Deployment implementation
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import pathlib
|
||||
import json
|
||||
import shutil
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from .app_deploy import AppDeploy
|
||||
from ...utils import verify_source
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
RINFO_KEYS = [
|
||||
"git_version", "long_version", "commit_hash", "source_checksum",
|
||||
"ignored_exts", "ignored_dirs", "build_date", "channel",
|
||||
"owner_repo", "host_repo", "release_tag"
|
||||
]
|
||||
|
||||
class ZipDeploy(AppDeploy):
|
||||
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
|
||||
super().__init__(config, cmd_helper)
|
||||
self.need_channel_update = self.type != "zip"
|
||||
self.official_repo: str = "?"
|
||||
self.owner: str = "?"
|
||||
# Extract repo from origin for validation
|
||||
match = re.match(r"https?://(?:www\.)?github.com/([^/]+/[^.]+)",
|
||||
self.origin)
|
||||
if match is not None:
|
||||
self.official_repo = match.group(1)
|
||||
self.owner = self.official_repo.split('/')[0]
|
||||
else:
|
||||
raise config.error(
|
||||
"Invalid url set for 'origin' option in section "
|
||||
f"[{config.get_name()}]. Unable to extract owner/repo.")
|
||||
self.host_repo: str = config.get('host_repo', self.official_repo)
|
||||
self.package_list: List[str] = []
|
||||
self.python_pkg_list: List[str] = []
|
||||
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
|
||||
|
||||
@staticmethod
|
||||
async def from_application(app: AppDeploy) -> ZipDeploy:
|
||||
new_app = ZipDeploy(app.config, app.cmd_helper)
|
||||
await new_app.reinstall()
|
||||
return new_app
|
||||
|
||||
async def initialize(self) -> Dict[str, Any]:
|
||||
storage = await super().initialize()
|
||||
self.source_checksum: str = storage.get("source_checksum", "?")
|
||||
self.pristine = storage.get('pristine', False)
|
||||
self.verified = storage.get('verified', False)
|
||||
self.build_date: int = storage.get('build_date', 0)
|
||||
self.full_version: str = storage.get('full_version', "?")
|
||||
self.short_version: str = storage.get('short_version', "?")
|
||||
self.commit_hash: str = storage.get('commit_hash', "?")
|
||||
self.lastest_hash: str = storage.get('latest_hash', "?")
|
||||
self.latest_version: str = storage.get('latest_version', "?")
|
||||
self.latest_checksum: str = storage.get('latest_checksum', "?")
|
||||
self.latest_build_date: int = storage.get('latest_build_date', 0)
|
||||
self.errors: List[str] = storage.get('errors', [])
|
||||
self.commit_log: List[Dict[str, Any]] = storage.get('commit_log', [])
|
||||
return storage
|
||||
|
||||
def get_persistent_data(self) -> Dict[str, Any]:
|
||||
storage = super().get_persistent_data()
|
||||
storage.update({
|
||||
'source_checksum': self.source_checksum,
|
||||
'pristine': self.pristine,
|
||||
'verified': self.verified,
|
||||
'build_date': self.build_date,
|
||||
'full_version': self.full_version,
|
||||
'short_version': self.short_version,
|
||||
'commit_hash': self.commit_hash,
|
||||
'latest_hash': self.lastest_hash,
|
||||
'latest_version': self.latest_version,
|
||||
'latest_checksum': self.latest_checksum,
|
||||
'latest_build_date': self.latest_build_date,
|
||||
'commit_log': self.commit_log,
|
||||
'errors': self.errors
|
||||
})
|
||||
return storage
|
||||
|
||||
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
|
||||
info_file = self.path.joinpath(file_name)
|
||||
if not info_file.exists():
|
||||
self.log_info(f"Unable to locate file '{info_file}'")
|
||||
return {}
|
||||
try:
|
||||
event_loop = self.server.get_event_loop()
|
||||
info_bytes = await event_loop.run_in_thread(info_file.read_text)
|
||||
info: Dict[str, Any] = json.loads(info_bytes)
|
||||
except Exception:
|
||||
self.log_exc(f"Unable to parse info file {file_name}")
|
||||
info = {}
|
||||
return info
|
||||
|
||||
def _get_tag_version(self, version_string: str) -> str:
|
||||
tag_version: str = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", version_string)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
return tag_version
|
||||
|
||||
async def refresh(self) -> None:
|
||||
try:
|
||||
await self._update_repo_state()
|
||||
except Exception:
|
||||
self.verified = False
|
||||
self.log_exc("Error refreshing application state")
|
||||
|
||||
async def _update_repo_state(self) -> None:
|
||||
self.errors = []
|
||||
self._is_valid = False
|
||||
self.verified = False
|
||||
release_info = await self._parse_info_file(".release_info")
|
||||
dep_info = await self._parse_info_file(".dependencies")
|
||||
for key in RINFO_KEYS:
|
||||
if key not in release_info:
|
||||
self._add_error(f"Missing release info item: {key}")
|
||||
if 'channel' in release_info:
|
||||
local_channel = release_info['channel']
|
||||
if self.channel == "stable" and local_channel == "beta":
|
||||
self.need_channel_update = True
|
||||
self.full_version = release_info.get('long_version', "?")
|
||||
self.short_version = self._get_tag_version(
|
||||
release_info.get('git_version', ""))
|
||||
self.commit_hash = release_info.get('commit_hash', "?")
|
||||
self.build_date = release_info.get('build_date', 0)
|
||||
owner_repo = release_info.get('owner_repo', "?")
|
||||
if self.official_repo != owner_repo:
|
||||
self._add_error(
|
||||
f"Owner repo mismatch. Received {owner_repo}, "
|
||||
f"official: {self.official_repo}")
|
||||
# validate the local source code
|
||||
event_loop = self.server.get_event_loop()
|
||||
res = await event_loop.run_in_thread(verify_source, self.path)
|
||||
if res is not None:
|
||||
self.source_checksum, self.pristine = res
|
||||
if self.name in ["moonraker", "klipper"]:
|
||||
self.server.add_log_rollover_item(
|
||||
f"{self.name}_validation",
|
||||
f"{self.name} checksum: {self.source_checksum}, "
|
||||
f"pristine: {self.pristine}")
|
||||
else:
|
||||
self._add_error("Unable to validate source checksum")
|
||||
self.source_checksum = ""
|
||||
self.pristine = False
|
||||
self.package_list = sorted(dep_info.get(
|
||||
'debian', {}).get('packages', []))
|
||||
self.python_pkg_list = sorted(dep_info.get('python', []))
|
||||
# Retrieve version info from github to check for updates and
|
||||
# validate local release info
|
||||
host_repo = release_info.get('host_repo', "?")
|
||||
release_tag = release_info.get('release_tag', "?")
|
||||
if host_repo != self.host_repo:
|
||||
self._add_error(
|
||||
f"Host repo mismatch, received: {host_repo}, "
|
||||
f"expected: {self.host_repo}. This could result in "
|
||||
" a failed update.")
|
||||
resource = f"repos/{self.host_repo}/releases"
|
||||
current_release, latest_release = await self._fetch_github_releases(
|
||||
resource, release_tag)
|
||||
await self._validate_current_release(release_info, current_release)
|
||||
if not self.errors:
|
||||
self.verified = True
|
||||
await self._process_latest_release(latest_release)
|
||||
self._save_state()
|
||||
self._log_zipapp_info()
|
||||
|
||||
async def _fetch_github_releases(self,
|
||||
resource: str,
|
||||
current_tag: Optional[str] = None
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
try:
|
||||
client = self.cmd_helper.get_http_client()
|
||||
resp = await client.github_api_request(resource, attempts=3)
|
||||
resp.raise_for_status()
|
||||
releases = resp.json()
|
||||
assert isinstance(releases, list)
|
||||
except Exception:
|
||||
self.log_exc("Error fetching releases from GitHub")
|
||||
return {}, {}
|
||||
release: Dict[str, Any]
|
||||
latest_release: Dict[str, Any] = {}
|
||||
current_release: Dict[str, Any] = {}
|
||||
for release in releases:
|
||||
if not latest_release:
|
||||
if self.channel != "stable":
|
||||
# Allow the beta channel to update regardless
|
||||
latest_release = release
|
||||
elif not release['prerelease']:
|
||||
# This is a stable release on the stable channle
|
||||
latest_release = release
|
||||
if current_tag is not None:
|
||||
if not current_release and release['tag_name'] == current_tag:
|
||||
current_release = release
|
||||
if latest_release and current_release:
|
||||
break
|
||||
elif latest_release:
|
||||
break
|
||||
return current_release, latest_release
|
||||
|
||||
async def _validate_current_release(self,
|
||||
release_info: Dict[str, Any],
|
||||
release: Dict[str, Any]
|
||||
) -> None:
|
||||
if not release:
|
||||
self._add_error("Unable to find current release on GitHub")
|
||||
return
|
||||
asset_info = self._get_asset_urls(release, ["RELEASE_INFO"])
|
||||
if "RELEASE_INFO" not in asset_info:
|
||||
self._add_error(
|
||||
"RELEASE_INFO not found in current release assets")
|
||||
info_url, content_type, size = asset_info['RELEASE_INFO']
|
||||
client = self.cmd_helper.get_http_client()
|
||||
rinfo_bytes = await client.get_file(info_url, content_type)
|
||||
github_rinfo: Dict[str, Any] = json.loads(rinfo_bytes)
|
||||
if github_rinfo.get(self.name, {}) != release_info:
|
||||
self._add_error(
|
||||
"Local release info does not match the remote")
|
||||
else:
|
||||
self.log_info("Current Release Info Validated")
|
||||
|
||||
async def _process_latest_release(self, release: Dict[str, Any]):
|
||||
if not release:
|
||||
self._add_error("Unable to find latest release on GitHub")
|
||||
return
|
||||
zip_file_name = f"{self.name}.zip"
|
||||
asset_names = ["RELEASE_INFO", "COMMIT_LOG", zip_file_name]
|
||||
asset_info = self._get_asset_urls(release, asset_names)
|
||||
if "RELEASE_INFO" in asset_info:
|
||||
asset_url, content_type, size = asset_info['RELEASE_INFO']
|
||||
client = self.cmd_helper.get_http_client()
|
||||
rinfo_bytes = await client.get_file(asset_url, content_type)
|
||||
update_release_info: Dict[str, Any] = json.loads(rinfo_bytes)
|
||||
update_info = update_release_info.get(self.name, {})
|
||||
self.lastest_hash = update_info.get('commit_hash', "?")
|
||||
self.latest_checksum = update_info.get('source_checksum', "?")
|
||||
self.latest_version = self._get_tag_version(
|
||||
update_info.get('git_version', "?"))
|
||||
self.latest_build_date = update_info.get('build_date', 0)
|
||||
else:
|
||||
self._add_error(
|
||||
"RELEASE_INFO not found in latest release assets")
|
||||
self.commit_log = []
|
||||
if self.short_version != self.latest_version:
|
||||
# Only report commit log if versions change
|
||||
if "COMMIT_LOG" in asset_info:
|
||||
asset_url, content_type, size = asset_info['COMMIT_LOG']
|
||||
client = self.cmd_helper.get_http_client()
|
||||
commit_bytes = await client.get_file(asset_url, content_type)
|
||||
commit_info: Dict[str, Any] = json.loads(commit_bytes)
|
||||
self.commit_log = commit_info.get(self.name, [])
|
||||
if zip_file_name in asset_info:
|
||||
self.release_download_info = asset_info[zip_file_name]
|
||||
self._is_valid = True
|
||||
else:
|
||||
self.release_download_info = ("?", "?", 0)
|
||||
self._add_error(f"Release asset {zip_file_name} not found")
|
||||
|
||||
def _get_asset_urls(self,
|
||||
release: Dict[str, Any],
|
||||
filenames: List[str]
|
||||
) -> Dict[str, Tuple[str, str, int]]:
|
||||
asset_info: Dict[str, Tuple[str, str, int]] = {}
|
||||
asset: Dict[str, Any]
|
||||
for asset in release.get('assets', []):
|
||||
name = asset['name']
|
||||
if name in filenames:
|
||||
rinfo_url = asset['browser_download_url']
|
||||
content_type = asset['content_type']
|
||||
size = asset['size']
|
||||
asset_info[name] = (rinfo_url, content_type, size)
|
||||
filenames.remove(name)
|
||||
if not filenames:
|
||||
break
|
||||
return asset_info
|
||||
|
||||
def _add_error(self, warning: str):
|
||||
self.log_info(warning)
|
||||
self.errors.append(warning)
|
||||
|
||||
def _log_zipapp_info(self):
|
||||
self.log_info(
|
||||
"\nZip Application Distribution Detected\n"
|
||||
f" Valid: {self._is_valid}\n"
|
||||
f" Verified: {self.verified}\n"
|
||||
f" Channel: {self.channel}\n"
|
||||
f" Repo: {self.official_repo}\n"
|
||||
f" Path: {self.path}\n"
|
||||
f" Pristine: {self.pristine}\n"
|
||||
f" Need Channel Update: {self.need_channel_update}\n"
|
||||
f" Commits Behind: {len(self.commit_log)}\n"
|
||||
f"Current Release Info:\n"
|
||||
f" Source Checksum: {self.source_checksum}\n"
|
||||
f" Commit SHA: {self.commit_hash}\n"
|
||||
f" Long Version: {self.full_version}\n"
|
||||
f" Short Version: {self.short_version}\n"
|
||||
f" Build Date: {time.ctime(self.build_date)}\n"
|
||||
f"Latest Available Release Info:\n"
|
||||
f" Source Checksum: {self.latest_checksum}\n"
|
||||
f" Commit SHA: {self.lastest_hash}\n"
|
||||
f" Version: {self.latest_version}\n"
|
||||
f" Build Date: {time.ctime(self.latest_build_date)}\n"
|
||||
f" Download URL: {self.release_download_info[0]}\n"
|
||||
f" Content Type: {self.release_download_info[1]}\n"
|
||||
f" Download Size: {self.release_download_info[2]}"
|
||||
)
|
||||
|
||||
async def _update_dependencies(self,
|
||||
npm_hash,
|
||||
force: bool = False
|
||||
) -> None:
|
||||
new_deps = await self._parse_info_file('.dependencies')
|
||||
system_pkgs = sorted(
|
||||
new_deps.get('debian', {}).get('packages', []))
|
||||
python_pkgs = sorted(new_deps.get('python', []))
|
||||
if system_pkgs:
|
||||
if force or system_pkgs != self.package_list:
|
||||
await self._install_packages(system_pkgs)
|
||||
if python_pkgs:
|
||||
if force or python_pkgs != self.python_pkg_list:
|
||||
await self._update_python_requirements(python_pkgs)
|
||||
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
|
||||
if force or ret:
|
||||
if self.npm_pkg_json is not None:
|
||||
self.notify_status("Updating Node Packages...")
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
"npm ci --only=prod", notify=True, timeout=600.,
|
||||
cwd=str(self.path))
|
||||
except Exception:
|
||||
self.notify_status("Node Package Update failed")
|
||||
|
||||
def _extract_release(self, release_zip: pathlib.Path) -> None:
|
||||
if self.path.is_dir():
|
||||
shutil.rmtree(self.path)
|
||||
os.mkdir(self.path)
|
||||
with zipfile.ZipFile(release_zip) as zf:
|
||||
zf.extractall(self.path)
|
||||
|
||||
async def update(self, force_dep_update: bool = False) -> bool:
|
||||
if not self._is_valid:
|
||||
raise self.log_exc("Update aborted, repo not valid", False)
|
||||
if self.short_version == self.latest_version:
|
||||
# already up to date
|
||||
return False
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Updating Application {self.name}...")
|
||||
npm_hash = await self._get_file_hash(self.npm_pkg_json)
|
||||
dl_url, content_type, size = self.release_download_info
|
||||
self.notify_status("Starting Download...")
|
||||
td = await self.cmd_helper.create_tempdir(self.name, "app")
|
||||
try:
|
||||
tempdir = pathlib.Path(td.name)
|
||||
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
|
||||
client = self.cmd_helper.get_http_client()
|
||||
await client.download_file(
|
||||
dl_url, content_type, temp_download_file, size,
|
||||
self.cmd_helper.on_download_progress)
|
||||
self.notify_status(
|
||||
f"Download Complete, extracting release to '{self.path}'")
|
||||
event_loop = self.server.get_event_loop()
|
||||
await event_loop.run_in_thread(
|
||||
self._extract_release, temp_download_file)
|
||||
finally:
|
||||
await event_loop.run_in_thread(td.cleanup)
|
||||
await self._update_dependencies(npm_hash, force=force_dep_update)
|
||||
await self._update_repo_state()
|
||||
await self.restart_service()
|
||||
self.notify_status("Update Finished...", is_complete=True)
|
||||
return True
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
res = f"repos/{self.host_repo}/releases"
|
||||
releases = await self._fetch_github_releases(res)
|
||||
await self._process_latest_release(releases[1])
|
||||
await self.update(force_dep_update=force_dep_update)
|
||||
|
||||
async def reinstall(self) -> None:
|
||||
# Clear the persistent storage prior to a channel swap.
|
||||
# After the next update is complete new data will be
|
||||
# restored.
|
||||
umdb = self.cmd_helper.get_umdb()
|
||||
await umdb.pop(self.name, None)
|
||||
await self.initialize()
|
||||
await self.recover(force_dep_update=True)
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
status = super().get_update_status()
|
||||
# XXX - Currently this reports status matching
|
||||
# that of the git repo so as to not break existing
|
||||
# client functionality. In the future it would be
|
||||
# good to report values that are specifc
|
||||
status.update({
|
||||
'detected_type': "zip",
|
||||
'remote_alias': "origin",
|
||||
'branch': "master",
|
||||
'owner': self.owner,
|
||||
'version': self.short_version,
|
||||
'remote_version': self.latest_version,
|
||||
'current_hash': self.commit_hash,
|
||||
'remote_hash': self.lastest_hash,
|
||||
'is_dirty': False,
|
||||
'detached': not self.verified,
|
||||
'commits_behind': self.commit_log,
|
||||
'git_messages': self.errors,
|
||||
'full_version_string': self.full_version,
|
||||
'pristine': self.pristine,
|
||||
})
|
||||
return status
|
||||
@@ -0,0 +1,373 @@
|
||||
# Centralized webcam configuration
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import re
|
||||
import ipaddress
|
||||
import socket
|
||||
import uuid
|
||||
import logging
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Any,
|
||||
Tuple
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..server import Server
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
from .database import MoonrakerDatabase
|
||||
from .machine import Machine
|
||||
from .shell_command import ShellCommandFactory
|
||||
from .http_client import HttpClient
|
||||
|
||||
# This provides a mapping of fields defined by Moonraker to fields
|
||||
# defined by the database.
|
||||
CAM_FIELDS = {
|
||||
"name": "name", "service": "service", "target_fps": "targetFps",
|
||||
"stream_url": "urlStream", "snapshot_url": "urlSnapshot",
|
||||
"flip_horizontal": "flipX", "flip_vertical": "flipY"
|
||||
}
|
||||
|
||||
class WebcamManager:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.webcams: Dict[str, WebCam] = {}
|
||||
# parse user configured webcams
|
||||
prefix_sections = config.get_prefix_sections("webcam ")
|
||||
for section in prefix_sections:
|
||||
cam_cfg = config[section]
|
||||
webcam = WebCam.from_config(cam_cfg)
|
||||
self.webcams[webcam.name] = webcam
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/webcams/list", ["GET"], self._handle_webcam_list
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/webcams/item", ["GET", "POST", "DELETE"],
|
||||
self._handle_webcam_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/webcams/test", ["POST"], self._handle_webcam_test
|
||||
)
|
||||
self.server.register_notification("webcam:webcams_changed")
|
||||
self.server.register_event_handler(
|
||||
"machine:public_ip_changed", self._set_default_host_ip
|
||||
)
|
||||
|
||||
async def component_init(self) -> None:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
if machine.public_ip:
|
||||
self._set_default_host_ip(machine.public_ip)
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
saved_cams: Dict[str, Any] = await db.get_item("webcams", default={})
|
||||
for cam_data in saved_cams.values():
|
||||
try:
|
||||
webcam = WebCam.from_database(self.server, cam_data)
|
||||
if webcam.name in self.webcams:
|
||||
continue
|
||||
self.webcams[webcam.name] = webcam
|
||||
except Exception:
|
||||
logging.exception("Failed to process webcam from db")
|
||||
continue
|
||||
|
||||
def _set_default_host_ip(self, ip: str) -> None:
|
||||
default_host = "http://127.0.0.1"
|
||||
if ip:
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
except Exception:
|
||||
logging.debug(f"Invalid IP Recd: {ip}")
|
||||
else:
|
||||
if addr.version == 6:
|
||||
default_host = f"http://[{addr}]"
|
||||
else:
|
||||
default_host = f"http://{addr}"
|
||||
WebCam.set_default_host(default_host)
|
||||
logging.info(f"Default public webcam address set: {default_host}")
|
||||
|
||||
def get_webcams(self) -> Dict[str, WebCam]:
|
||||
return self.webcams
|
||||
|
||||
def _list_webcams(self) -> List[Dict[str, Any]]:
|
||||
return [wc.as_dict() for wc in self.webcams.values()]
|
||||
|
||||
async def _find_dbcam_by_uuid(
|
||||
self, name: str
|
||||
) -> Tuple[str, Dict[str, Any]]:
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
saved_cams: Dict[str, Dict[str, Any]]
|
||||
saved_cams = await db.get_item("webcams", default={})
|
||||
for uid, cam_data in saved_cams.items():
|
||||
if name == cam_data["name"]:
|
||||
return uid, cam_data
|
||||
return "", {}
|
||||
|
||||
async def _save_cam(self, webcam: WebCam) -> None:
|
||||
uid, cam_data = await self._find_dbcam_by_uuid(webcam.name)
|
||||
if not uid:
|
||||
uid = str(uuid.uuid4())
|
||||
for mfield, dbfield in CAM_FIELDS.items():
|
||||
cam_data[dbfield] = getattr(webcam, mfield)
|
||||
cam_data["location"] = webcam.location
|
||||
cam_data["rotation"] = webcam.rotation
|
||||
if "icon" not in cam_data:
|
||||
cam_data["icon"] = "mdi-webcam"
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
db.insert_item("webcams", uid, cam_data)
|
||||
|
||||
async def _delete_cam(self, webcam: WebCam) -> None:
|
||||
uid, cam = await self._find_dbcam_by_uuid(webcam.name)
|
||||
if not uid:
|
||||
return
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
db.delete_item("webcams", uid)
|
||||
|
||||
async def _handle_webcam_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
name = web_request.get_str("name")
|
||||
webcam_data: Dict[str, Any] = {}
|
||||
if action == "GET":
|
||||
if name not in self.webcams:
|
||||
raise self.server.error(f"Webcam {name} not found", 404)
|
||||
webcam_data = self.webcams[name].as_dict()
|
||||
elif action == "POST":
|
||||
if (
|
||||
name in self.webcams and
|
||||
self.webcams[name].source == "config"
|
||||
):
|
||||
raise self.server.error(
|
||||
f"Cannot overwrite webcam '{name}' sourced from "
|
||||
"Moonraker configuration"
|
||||
)
|
||||
webcam = WebCam.from_web_request(self.server, web_request)
|
||||
self.webcams[name] = webcam
|
||||
webcam_data = webcam.as_dict()
|
||||
await self._save_cam(webcam)
|
||||
elif action == "DELETE":
|
||||
if name not in self.webcams:
|
||||
raise self.server.error(f"Webcam {name} not found", 404)
|
||||
elif self.webcams[name].source == "config":
|
||||
raise self.server.error(
|
||||
f"Cannot delete webcam '{name}' sourced from "
|
||||
"Moonraker configuration"
|
||||
)
|
||||
webcam = self.webcams.pop(name)
|
||||
webcam_data = webcam.as_dict()
|
||||
await self._delete_cam(webcam)
|
||||
if action != "GET":
|
||||
self.server.send_event(
|
||||
"webcam:webcams_changed", {"webcams": self._list_webcams()}
|
||||
)
|
||||
return {"webcam": webcam_data}
|
||||
|
||||
async def _handle_webcam_list(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {"webcams": self._list_webcams()}
|
||||
|
||||
async def _handle_webcam_test(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
name = web_request.get_str("name")
|
||||
if name not in self.webcams:
|
||||
raise self.server.error(f"Webcam '{name}' not found", 404)
|
||||
client: HttpClient = self.server.lookup_component("http_client")
|
||||
cam = self.webcams[name]
|
||||
result: Dict[str, Any] = {
|
||||
"name": name,
|
||||
"snapshot_reachable": False
|
||||
}
|
||||
for img_type in ["snapshot", "stream"]:
|
||||
try:
|
||||
func = getattr(cam, f"get_{img_type}_url")
|
||||
result[f"{img_type}_url"] = await func(True)
|
||||
except Exception:
|
||||
logging.exception(f"Error Processing {img_type} url")
|
||||
result[f"{img_type}_url"] = ""
|
||||
url: str = result["snapshot_url"]
|
||||
if result.get("snapshot_url", "").startswith("http"):
|
||||
ret = await client.get(url, connect_timeout=1., request_timeout=1.)
|
||||
result["snapshot_reachable"] = not ret.has_error()
|
||||
return result
|
||||
|
||||
|
||||
class WebCam:
|
||||
_default_host: str = "http://127.0.0.1"
|
||||
def __init__(self, server: Server, **kwargs) -> None:
|
||||
self._server = server
|
||||
self.name: str = kwargs["name"]
|
||||
self.location: str = kwargs["location"]
|
||||
self.service: str = kwargs["service"]
|
||||
self.target_fps: int = kwargs["target_fps"]
|
||||
self.stream_url: str = kwargs["stream_url"]
|
||||
self.snapshot_url: str = kwargs["snapshot_url"]
|
||||
self.flip_horizontal: bool = kwargs["flip_horizontal"]
|
||||
self.flip_vertical: bool = kwargs["flip_vertical"]
|
||||
self.rotation: int = kwargs["rotation"]
|
||||
self.source: str = kwargs["source"]
|
||||
|
||||
def as_dict(self):
|
||||
return {k: v for k, v in self.__dict__.items() if k[0] != "_"}
|
||||
|
||||
async def get_stream_url(self, convert_local: bool = False) -> str:
|
||||
return await self._get_url(self.stream_url, convert_local)
|
||||
|
||||
async def get_snapshot_url(self, convert_local: bool = False) -> str:
|
||||
return await self._get_url(self.snapshot_url, convert_local)
|
||||
|
||||
async def _get_url(self, url: str, convert_local: bool) -> str:
|
||||
if not url:
|
||||
raise self._server.error("Empty URL Provided")
|
||||
match = re.match(r"\w+://[^/]+", url)
|
||||
if match is None:
|
||||
# assume a partial URL on the default host
|
||||
url = f"{self._default_host}/{url.lstrip('/')}"
|
||||
if not convert_local:
|
||||
return url
|
||||
return await self.convert_local(url)
|
||||
|
||||
def _get_local_ips(self) -> List[str]:
|
||||
all_ips: List[str] = []
|
||||
machine: Machine = self._server.lookup_component("machine")
|
||||
sys_info = machine.get_system_info()
|
||||
network = sys_info.get("network", {})
|
||||
iface: Dict[str, Any]
|
||||
for iface in network.values():
|
||||
addresses: List[Dict[str, Any]] = iface["ip_addresses"]
|
||||
for addr_info in addresses:
|
||||
all_ips.append(addr_info["address"])
|
||||
return all_ips
|
||||
|
||||
async def convert_local(self, url: str) -> str:
|
||||
match = re.match(r"(\w+)://([^/]+)(/.*)?", url)
|
||||
if match is None:
|
||||
return url
|
||||
scheme = match.group(1)
|
||||
addr = match.group(2)
|
||||
fragment = match.group(3)
|
||||
if fragment is None:
|
||||
fragment = ""
|
||||
if addr[0] == "[":
|
||||
# ipv6 address
|
||||
addr_match = re.match(r"\[(.+)\](:\d+)?", addr)
|
||||
else:
|
||||
# ipv4 address or hostname
|
||||
addr_match = re.match(r"([^:]+)(:\d+)?", addr)
|
||||
if addr_match is None:
|
||||
return url
|
||||
addr = addr_match.group(1)
|
||||
port: Optional[str] = addr_match.group(2)
|
||||
default_ports = {"http": "80", "https": "443", "rtsp": "554"}
|
||||
if port is None:
|
||||
if scheme not in default_ports:
|
||||
return url
|
||||
port = default_ports[scheme]
|
||||
else:
|
||||
port = port.lstrip(":")
|
||||
# attempt to convert hostname to IP
|
||||
try:
|
||||
eventloop = self._server.get_event_loop()
|
||||
addr_info = await eventloop.run_in_thread(
|
||||
socket.getaddrinfo, addr, int(port)
|
||||
)
|
||||
if addr_info:
|
||||
addr = addr_info[0][4][0]
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except Exception:
|
||||
# Invalid IP, can't convert.
|
||||
return url
|
||||
else:
|
||||
if ip.is_loopback:
|
||||
return url
|
||||
# Check to see if this ip address is on the local machine
|
||||
if addr not in self._get_local_ips():
|
||||
return url
|
||||
scmd: ShellCommandFactory
|
||||
scmd = self._server.lookup_component("shell_command")
|
||||
try:
|
||||
# Use the ss command to list all tcp ports
|
||||
resp: str = await scmd.exec_cmd("ss -ltn")
|
||||
lines = resp.split("\n")[1:]
|
||||
for line in lines:
|
||||
parts = line.strip().split()
|
||||
if len(parts) < 5:
|
||||
continue
|
||||
laddr, lport = parts[3].split(":")
|
||||
if lport == port:
|
||||
if laddr == "[::]":
|
||||
return f"{scheme}://[::1]:{port}{fragment}"
|
||||
elif laddr == "0.0.0.0":
|
||||
return f"{scheme}://127.0.0.1:{port}{fragment}"
|
||||
except scmd.error:
|
||||
pass
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def set_default_host(host: str) -> None:
|
||||
WebCam._default_host = host
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config: ConfigHelper) -> WebCam:
|
||||
webcam: Dict[str, Any] = {}
|
||||
webcam["name"] = config.get_name().split(maxsplit=1)[-1]
|
||||
webcam["location"] = config.get("location", "printer")
|
||||
webcam["service"] = config.get("service", "mjpegstreamer")
|
||||
webcam["target_fps"] = config.getint("target_fps", 15)
|
||||
webcam["stream_url"] = config.get("stream_url")
|
||||
webcam["snapshot_url"] = config.get("snapshot_url")
|
||||
webcam["flip_horizontal"] = config.getboolean("flip_horizontal", False)
|
||||
webcam["flip_vertical"] = config.getboolean("flip_vertical", False)
|
||||
webcam["rotation"] = config.getint("rotation", 0)
|
||||
if webcam["rotation"] not in [0, 90, 180, 270]:
|
||||
raise config.error("Invalid value for option 'rotation'")
|
||||
webcam["source"] = "config"
|
||||
return cls(config.get_server(), **webcam)
|
||||
|
||||
@classmethod
|
||||
def from_web_request(
|
||||
cls, server: Server, web_request: WebRequest
|
||||
) -> WebCam:
|
||||
webcam: Dict[str, Any] = {}
|
||||
webcam["name"] = web_request.get_str("name")
|
||||
webcam["location"] = web_request.get_str("location", "printer")
|
||||
webcam["service"] = web_request.get_str("service", "mjpegstreamer")
|
||||
webcam["target_fps"] = web_request.get_int("target_fps", 15)
|
||||
webcam["stream_url"] = web_request.get_str("stream_url")
|
||||
webcam["snapshot_url"] = web_request.get_str("snapshot_url")
|
||||
webcam["flip_horizontal"] = web_request.get_boolean(
|
||||
"flip_horizontal", False
|
||||
)
|
||||
webcam["flip_vertical"] = web_request.get_boolean(
|
||||
"flip_vertical", False
|
||||
)
|
||||
webcam["rotation"] = web_request.get_int("rotation", 0)
|
||||
if webcam["rotation"] not in [0, 90, 180, 270]:
|
||||
raise server.error("Invalid value for parameter 'rotation'")
|
||||
webcam["source"] = "database"
|
||||
return cls(server, **webcam)
|
||||
|
||||
@classmethod
|
||||
def from_database(cls, server: Server, cam_data: Dict[str, Any]) -> WebCam:
|
||||
webcam: Dict[str, Any] = {}
|
||||
for mfield, dbfield in CAM_FIELDS.items():
|
||||
webcam[mfield] = cam_data[dbfield]
|
||||
webcam["location"] = webcam.get("location", "printer")
|
||||
webcam["rotation"] = webcam.get("rotation", 0)
|
||||
webcam["source"] = "database"
|
||||
return cls(server, **webcam)
|
||||
|
||||
def load_component(config: ConfigHelper) -> WebcamManager:
|
||||
return WebcamManager(config)
|
||||
@@ -0,0 +1,594 @@
|
||||
# WLED neopixel support
|
||||
#
|
||||
# Copyright (C) 2021-2022 Richard Mitchell <richardjm+moonraker@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
# Component to control the wled neopixel home system from AirCookie
|
||||
# Github at https://github.com/Aircoookie/WLED
|
||||
# Wiki at https://kno.wled.ge/
|
||||
|
||||
from __future__ import annotations
|
||||
from enum import Enum
|
||||
import logging
|
||||
import json
|
||||
import asyncio
|
||||
import serial_asyncio
|
||||
from tornado.httpclient import AsyncHTTPClient
|
||||
from tornado.httpclient import HTTPRequest
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Type,
|
||||
List,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..websockets import WebRequest
|
||||
|
||||
class OnOff(str, Enum):
|
||||
on: str = "on"
|
||||
off: str = "off"
|
||||
|
||||
class Strip():
|
||||
_COLORSIZE: int = 4
|
||||
|
||||
def __init__(self: Strip,
|
||||
name: str,
|
||||
cfg: ConfigHelper):
|
||||
self.server = cfg.get_server()
|
||||
self.request_mutex = asyncio.Lock()
|
||||
|
||||
self.name = name
|
||||
|
||||
self.initial_preset: int = cfg.getint("initial_preset", -1)
|
||||
self.initial_red: float = cfg.getfloat("initial_red", 0.5)
|
||||
self.initial_green: float = cfg.getfloat("initial_green", 0.5)
|
||||
self.initial_blue: float = cfg.getfloat("initial_blue", 0.5)
|
||||
self.initial_white: float = cfg.getfloat("initial_white", 0.5)
|
||||
self.chain_count: int = cfg.getint("chain_count", 1)
|
||||
|
||||
# Supports rgbw always
|
||||
self._chain_data = bytearray(
|
||||
self.chain_count * self._COLORSIZE)
|
||||
|
||||
self.onoff = OnOff.off
|
||||
self.preset = self.initial_preset
|
||||
|
||||
def get_strip_info(self: Strip) -> Dict[str, Any]:
|
||||
return {
|
||||
"strip": self.name,
|
||||
"status": self.onoff.value,
|
||||
"chain_count": self.chain_count,
|
||||
"preset": self.preset,
|
||||
"brightness": self.brightness,
|
||||
"intensity": self.intensity,
|
||||
"speed": self.speed,
|
||||
"error": self.error_state
|
||||
}
|
||||
|
||||
async def initialize(self: Strip) -> None:
|
||||
self.send_full_chain_data = True
|
||||
self.onoff = OnOff.on
|
||||
self.preset = self.initial_preset
|
||||
self.brightness = 255
|
||||
self.intensity = -1
|
||||
self.speed = -1
|
||||
if self.initial_preset >= 0:
|
||||
self._update_color_data(self.initial_red,
|
||||
self.initial_green,
|
||||
self.initial_blue,
|
||||
self.initial_white,
|
||||
None)
|
||||
await self.wled_on(self.initial_preset)
|
||||
else:
|
||||
await self.set_wled(self.initial_red,
|
||||
self.initial_green,
|
||||
self.initial_blue,
|
||||
self.initial_white,
|
||||
None,
|
||||
True)
|
||||
|
||||
def _update_color_data(self: Strip,
|
||||
red: float, green: float, blue: float, white: float,
|
||||
index: Optional[int]) -> None:
|
||||
red = int(red * 255. + .5)
|
||||
blue = int(blue * 255. + .5)
|
||||
green = int(green * 255. + .5)
|
||||
white = int(white * 255. + .5)
|
||||
led_data = [red, green, blue, white]
|
||||
|
||||
if index is None:
|
||||
self._chain_data[:] = led_data * self.chain_count
|
||||
else:
|
||||
elem_size = len(led_data)
|
||||
self._chain_data[(index-1)*elem_size:index*elem_size] = led_data
|
||||
|
||||
async def send_wled_command_impl(self: Strip,
|
||||
state: Dict[str, Any]) -> None:
|
||||
pass
|
||||
|
||||
def close(self: Strip):
|
||||
pass
|
||||
|
||||
async def _send_wled_command(self: Strip,
|
||||
state: Dict[str, Any]) -> None:
|
||||
try:
|
||||
await self.send_wled_command_impl(state)
|
||||
|
||||
self.error_state = None
|
||||
except Exception as e:
|
||||
msg = f"WLED: Error {e}"
|
||||
self.error_state = msg
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
|
||||
async def wled_on(self: Strip, preset: int) -> None:
|
||||
self.onoff = OnOff.on
|
||||
logging.debug(f"WLED: {self.name} on PRESET={preset}")
|
||||
if preset < 0:
|
||||
# WLED_ON STRIP=strip (no args) - reset to default
|
||||
await self.initialize()
|
||||
else:
|
||||
self.send_full_chain_data = True
|
||||
self.preset = preset
|
||||
# Without reading the data back from wled we don't know the values
|
||||
self.brightness = -1
|
||||
self.intensity = -1
|
||||
self.speed = -1
|
||||
await self._send_wled_command({"on": True, "ps": preset})
|
||||
|
||||
async def wled_off(self: Strip) -> None:
|
||||
logging.debug(f"WLED: {self.name} off")
|
||||
self.onoff = OnOff.off
|
||||
# Without this calling SET_WLED for a single pixel after WLED_OFF
|
||||
# would send just that pixel
|
||||
self.send_full_chain_data = True
|
||||
await self._send_wled_command({"on": False})
|
||||
|
||||
async def wled_control(self: Strip, brightness: int, intensity: int,
|
||||
speed: int) -> None:
|
||||
logging.debug(
|
||||
f"WLED: {self.name} control {self.onoff} BRIGHTNESS={brightness} "
|
||||
f"INTENSITY={intensity} SPEED={speed} CURRENTPRESET={self.preset}")
|
||||
|
||||
if self.onoff == OnOff.off:
|
||||
logging.info("wled control only permitted when strip is on")
|
||||
return
|
||||
|
||||
# Even if a preset is not activated sending seg {} information will
|
||||
# turn it back on
|
||||
control: Dict[str, Any]
|
||||
if self.preset != -1:
|
||||
control = {"tt": 0, "seg": {}}
|
||||
else:
|
||||
control = {"tt": 0}
|
||||
|
||||
shouldSend: bool = False
|
||||
# Using 0 is not recommended in wled docs
|
||||
if brightness > 0:
|
||||
if brightness > 255:
|
||||
logging.info("BRIGHTNESS should be between 1 and 255")
|
||||
else:
|
||||
shouldSend = True
|
||||
self.brightness = brightness
|
||||
control["bri"] = self.brightness
|
||||
# Brightness in seg {} - only if a preset is on
|
||||
if self.preset != -1:
|
||||
control["seg"]["bri"] = self.brightness
|
||||
|
||||
# Intensity - only if a preset is on
|
||||
if intensity > -1 and self.preset != -1:
|
||||
if intensity > 255:
|
||||
logging.info("INTENSITY should be between 0 and 255")
|
||||
else:
|
||||
shouldSend = True
|
||||
self.intensity = intensity
|
||||
control["seg"]["ix"] = self.intensity
|
||||
|
||||
# Speed - only if a preset is on
|
||||
if speed > -1 and self.preset != -1:
|
||||
if speed > 255:
|
||||
logging.info("SPEED should be between 0 and 255")
|
||||
else:
|
||||
shouldSend = True
|
||||
self.speed = speed
|
||||
control["seg"]["sx"] = self.speed
|
||||
|
||||
# Control brightness, intensity, and speed for segment
|
||||
# This will allow full control for effects such as "Percent"
|
||||
if shouldSend:
|
||||
await self._send_wled_command(control)
|
||||
|
||||
def _wled_pixel(self: Strip, index: int) -> List[int]:
|
||||
led_color_data: List[int] = []
|
||||
for p in self._chain_data[(index-1)*self._COLORSIZE:
|
||||
(index)*self._COLORSIZE]:
|
||||
led_color_data.append(p)
|
||||
return led_color_data
|
||||
|
||||
async def set_wled(self: Strip,
|
||||
red: float, green: float, blue: float, white: float,
|
||||
index: Optional[int], transmit: bool) -> None:
|
||||
logging.debug(
|
||||
f"WLED: {self.name} R={red} G={green} B={blue} W={white} "
|
||||
f"INDEX={index} TRANSMIT={transmit}")
|
||||
self._update_color_data(red, green, blue, white, index)
|
||||
if transmit:
|
||||
# Clear preset (issues with sending seg{} will revert to preset)
|
||||
self.preset = -1
|
||||
|
||||
# If we are coming from a preset without a wled_control
|
||||
# we don't know a brightness, this will also ensure
|
||||
# behaviour is consistent prior to introduction of wled_control
|
||||
if self.brightness == -1:
|
||||
self.brightness = 255
|
||||
|
||||
# Base command for setting an led (for all active segments)
|
||||
# See https://kno.wled.ge/interfaces/json-api/
|
||||
state: Dict[str, Any] = {"on": True,
|
||||
"tt": 0,
|
||||
"bri": self.brightness,
|
||||
"seg": {"bri": self.brightness, "i": []}}
|
||||
if index is None:
|
||||
# All pixels same color only send range command of first color
|
||||
self.send_full_chain_data = False
|
||||
state["seg"]["i"] = [0, self.chain_count, self._wled_pixel(1)]
|
||||
elif self.send_full_chain_data:
|
||||
# Send a full set of color data (e.g. previous preset)
|
||||
self.send_full_chain_data = False
|
||||
cdata = []
|
||||
for i in range(self.chain_count):
|
||||
cdata.append(self._wled_pixel(i+1))
|
||||
state["seg"]["i"] = cdata
|
||||
else:
|
||||
# Only one pixel has changed since last full data sent
|
||||
# so send just that one
|
||||
state["seg"]["i"] = [index-1, self._wled_pixel(index)]
|
||||
|
||||
# Send wled control command
|
||||
await self._send_wled_command(state)
|
||||
|
||||
if self.onoff == OnOff.off:
|
||||
# Without a repeated call individual led control doesn't
|
||||
# turn the led strip back on or doesn't set brightness
|
||||
# correctly from off
|
||||
# Confirmed as a bug:
|
||||
# https://discord.com/channels/473448917040758787/757254961640898622/934135556370202645
|
||||
self.onoff = OnOff.on
|
||||
await self._send_wled_command(state)
|
||||
else:
|
||||
# If not transmitting this time easiest just to send all data when
|
||||
# next transmitting
|
||||
self.send_full_chain_data = True
|
||||
|
||||
class StripHttp(Strip):
|
||||
def __init__(self: StripHttp,
|
||||
name: str,
|
||||
cfg: ConfigHelper):
|
||||
super().__init__(name, cfg)
|
||||
|
||||
# Read the uri information
|
||||
addr: str = cfg.get("address")
|
||||
port: int = cfg.getint("port", 80)
|
||||
protocol: str = cfg.get("protocol", "http")
|
||||
self.url = f"{protocol}://{addr}:{port}/json"
|
||||
|
||||
self.timeout: float = cfg.getfloat("timeout", 2.)
|
||||
self.client = AsyncHTTPClient()
|
||||
|
||||
async def send_wled_command_impl(self: StripHttp,
|
||||
state: Dict[str, Any],
|
||||
retries: int = 3
|
||||
) -> None:
|
||||
async with self.request_mutex:
|
||||
logging.debug(f"WLED: url:{self.url} json:{state}")
|
||||
|
||||
headers = {"Content-Type": "application/json"}
|
||||
request = HTTPRequest(url=self.url,
|
||||
method="POST",
|
||||
headers=headers,
|
||||
body=json.dumps(state),
|
||||
connect_timeout=self.timeout,
|
||||
request_timeout=self.timeout)
|
||||
for i in range(retries):
|
||||
try:
|
||||
response = await self.client.fetch(request)
|
||||
except Exception:
|
||||
if i == retries - 1:
|
||||
raise
|
||||
await asyncio.sleep(1.0)
|
||||
else:
|
||||
break
|
||||
|
||||
logging.debug(
|
||||
f"WLED: url:{self.url} status:{response.code} "
|
||||
f"response:{response.body.decode()}")
|
||||
|
||||
class StripSerial(Strip):
|
||||
def __init__(self: StripSerial,
|
||||
name: str,
|
||||
cfg: ConfigHelper):
|
||||
super().__init__(name, cfg)
|
||||
|
||||
# Read the serial information (requires wled 0.13 2108250 or greater)
|
||||
self.serialport: str = cfg.get("serial")
|
||||
self.baud: int = cfg.getint("baud", 115200, above=49)
|
||||
|
||||
async def send_wled_command_impl(self: StripSerial,
|
||||
state: Dict[str, Any]) -> None:
|
||||
async with self.request_mutex:
|
||||
if not hasattr(self, 'ser'):
|
||||
_, self.ser = await serial_asyncio.open_serial_connection(
|
||||
url=self.serialport, baudrate=self.baud)
|
||||
|
||||
logging.debug(f"WLED: serial:{self.serialport} json:{state}")
|
||||
|
||||
self.ser.write(json.dumps(state).encode())
|
||||
|
||||
def close(self: StripSerial):
|
||||
if hasattr(self, 'ser'):
|
||||
self.ser.close()
|
||||
logging.info(f"WLED: Closing serial {self.serialport}")
|
||||
|
||||
class WLED:
|
||||
def __init__(self: WLED, config: ConfigHelper) -> None:
|
||||
# root_logger = logging.getLogger()
|
||||
# root_logger.setLevel(logging.DEBUG)
|
||||
|
||||
self.server = config.get_server()
|
||||
prefix_sections = config.get_prefix_sections("wled")
|
||||
logging.info(f"WLED component loading strips: {prefix_sections}")
|
||||
|
||||
strip_types = {
|
||||
"HTTP": StripHttp,
|
||||
"SERIAL": StripSerial
|
||||
}
|
||||
self.strips = {}
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
|
||||
try:
|
||||
name_parts = cfg.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise cfg.error(
|
||||
f"Invalid Section Name: {cfg.get_name()}")
|
||||
name: str = name_parts[1]
|
||||
|
||||
logging.info(f"WLED strip: {name}")
|
||||
|
||||
# Discard old color_order setting, always support 4 color strips
|
||||
_ = cfg.get("color_order", "", deprecate=True)
|
||||
|
||||
strip_type: str = cfg.get("type", "http")
|
||||
strip_class: Optional[Type[Strip]]
|
||||
strip_class = strip_types.get(strip_type.upper())
|
||||
if strip_class is None:
|
||||
raise config.error(f"Unsupported Strip Type: {strip_type}")
|
||||
|
||||
self.strips[name] = strip_class(name, cfg)
|
||||
|
||||
except Exception as e:
|
||||
# Ensures errors such as "Color not supported" are visible
|
||||
msg = f"Failed to initialise strip [{cfg.get_name()}]\n{e}"
|
||||
self.server.add_warning(msg)
|
||||
continue
|
||||
|
||||
# Register two remote methods for GCODE
|
||||
self.server.register_remote_method(
|
||||
"set_wled_state", self.set_wled_state)
|
||||
self.server.register_remote_method(
|
||||
"set_wled", self.set_wled)
|
||||
|
||||
# As moonraker is about making things a web api, let's try it
|
||||
# Yes, this is largely a cut-n-paste from power.py
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/strips", ["GET"],
|
||||
self._handle_list_strips)
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/status", ["GET"],
|
||||
self._handle_batch_wled_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/on", ["POST"],
|
||||
self._handle_batch_wled_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/off", ["POST"],
|
||||
self._handle_batch_wled_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/toggle", ["POST"],
|
||||
self._handle_batch_wled_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/wled/strip", ["GET", "POST"],
|
||||
self._handle_single_wled_request)
|
||||
|
||||
async def component_init(self) -> None:
|
||||
try:
|
||||
logging.debug("Initializing wled")
|
||||
event_loop = self.server.get_event_loop()
|
||||
cur_time = event_loop.get_loop_time()
|
||||
endtime = cur_time + 120.
|
||||
query_strips = list(self.strips.values())
|
||||
failed_strips: List[Strip] = []
|
||||
while cur_time < endtime:
|
||||
for strip in query_strips:
|
||||
ret = strip.initialize()
|
||||
if ret is not None:
|
||||
await ret
|
||||
if strip.error_state is not None:
|
||||
failed_strips.append(strip)
|
||||
if not failed_strips:
|
||||
logging.debug("All wled strips initialized")
|
||||
return
|
||||
query_strips = failed_strips
|
||||
failed_strips = []
|
||||
await asyncio.sleep(2.)
|
||||
cur_time = event_loop.get_loop_time()
|
||||
if failed_strips:
|
||||
failed_names = [s.name for s in failed_strips]
|
||||
self.server.add_warning(
|
||||
"The following wled strips failed init:"
|
||||
f" {failed_names}")
|
||||
except Exception as e:
|
||||
logging.exception(e)
|
||||
|
||||
async def wled_on(self: WLED, strip: str, preset: int) -> None:
|
||||
if strip not in self.strips:
|
||||
logging.info(f"Unknown WLED strip: {strip}")
|
||||
return
|
||||
await self.strips[strip].wled_on(preset)
|
||||
|
||||
# Full control of wled
|
||||
# state: True, False, "on", "off"
|
||||
# preset: wled preset (int) to use (ignored if state False or "Off")
|
||||
async def set_wled_state(
|
||||
self: WLED,
|
||||
strip: str,
|
||||
state: Optional[str] = None,
|
||||
preset: int = -1,
|
||||
brightness: int = -1,
|
||||
intensity: int = -1,
|
||||
speed: int = -1
|
||||
) -> None:
|
||||
status = None
|
||||
|
||||
if isinstance(state, bool):
|
||||
status = OnOff.on if state else OnOff.off
|
||||
elif isinstance(state, str):
|
||||
status = state.lower()
|
||||
if status in ["true", "false"]:
|
||||
status = OnOff.on if status == "true" else OnOff.off
|
||||
|
||||
if status is None and preset == -1 and brightness == -1 and \
|
||||
intensity == -1 and speed == -1:
|
||||
logging.info(
|
||||
f"Invalid state received but no control or preset data passed")
|
||||
return
|
||||
|
||||
if strip not in self.strips:
|
||||
logging.info(f"Unknown WLED strip: {strip}")
|
||||
return
|
||||
|
||||
# All other arguments are ignored
|
||||
if status == OnOff.off:
|
||||
await self.strips[strip].wled_off()
|
||||
|
||||
# Turn on if on or a preset is specified
|
||||
if status == OnOff.on or preset != -1:
|
||||
await self.strips[strip].wled_on(preset)
|
||||
|
||||
# Control
|
||||
if brightness != -1 or intensity != -1 or speed != -1:
|
||||
await self.strips[strip].wled_control(brightness, intensity, speed)
|
||||
|
||||
# Individual pixel control, for compatibility with SET_LED
|
||||
async def set_wled(self: WLED,
|
||||
strip: str,
|
||||
red: float = 0.,
|
||||
green: float = 0.,
|
||||
blue: float = 0.,
|
||||
white: float = 0.,
|
||||
index: Optional[int] = None,
|
||||
transmit: int = 1) -> None:
|
||||
if strip not in self.strips:
|
||||
logging.info(f"Unknown WLED strip: {strip}")
|
||||
return
|
||||
if isinstance(index, int) and index < 0:
|
||||
index = None
|
||||
await self.strips[strip].set_wled(red, green, blue, white,
|
||||
index,
|
||||
True if transmit == 1 else False)
|
||||
|
||||
async def _handle_list_strips(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
strips = {name: strip.get_strip_info()
|
||||
for name, strip in self.strips.items()}
|
||||
output = {"strips": strips}
|
||||
return output
|
||||
|
||||
async def _handle_single_wled_request(self: WLED,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
strip_name: str = web_request.get_str('strip')
|
||||
preset: int = web_request.get_int('preset', -1)
|
||||
brightness: int = web_request.get_int('brightness', -1)
|
||||
intensity: int = web_request.get_int('intensity', -1)
|
||||
speed: int = web_request.get_int('speed', -1)
|
||||
|
||||
req_action = web_request.get_action()
|
||||
if strip_name not in self.strips:
|
||||
raise self.server.error(f"No valid strip named {strip_name}")
|
||||
strip = self.strips[strip_name]
|
||||
if req_action == 'GET':
|
||||
return {strip_name: strip.get_strip_info()}
|
||||
elif req_action == "POST":
|
||||
action = web_request.get_str('action').lower()
|
||||
if action not in ["on", "off", "toggle", "control"]:
|
||||
raise self.server.error(
|
||||
f"Invalid requested action '{action}'")
|
||||
result = await self._process_request(strip, action, preset,
|
||||
brightness, intensity, speed)
|
||||
return {strip_name: result}
|
||||
|
||||
async def _handle_batch_wled_request(self: WLED,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
args = web_request.get_args()
|
||||
ep = web_request.get_endpoint()
|
||||
if not args:
|
||||
raise self.server.error("No arguments provided")
|
||||
requested_strips = {k: self.strips.get(k, None) for k in args}
|
||||
result = {}
|
||||
req = ep.split("/")[-1]
|
||||
for name, strip in requested_strips.items():
|
||||
if strip is not None:
|
||||
result[name] = await self._process_request(strip, req, -1,
|
||||
-1, -1, -1)
|
||||
else:
|
||||
result[name] = {"error": "strip_not_found"}
|
||||
return result
|
||||
|
||||
async def _process_request(self: WLED,
|
||||
strip: Strip,
|
||||
req: str,
|
||||
preset: int,
|
||||
brightness: int,
|
||||
intensity: int,
|
||||
speed: int
|
||||
) -> Dict[str, Any]:
|
||||
strip_onoff = strip.onoff
|
||||
|
||||
if req == "status":
|
||||
return strip.get_strip_info()
|
||||
if req == "toggle":
|
||||
req = "on" if strip_onoff == OnOff.off else "off"
|
||||
|
||||
if req in ["on", "off", "control"]:
|
||||
# Always do something, could be turning off colors, or changing
|
||||
# preset, easier not to have to worry
|
||||
if req == "on" or req == "control":
|
||||
if req == "on":
|
||||
strip_onoff = OnOff.on
|
||||
await strip.wled_on(preset)
|
||||
|
||||
if brightness != -1 or intensity != -1 or speed != -1:
|
||||
await strip.wled_control(brightness, intensity, speed)
|
||||
else:
|
||||
strip_onoff = OnOff.off
|
||||
await strip.wled_off()
|
||||
|
||||
return strip.get_strip_info()
|
||||
|
||||
raise self.server.error(f"Unsupported wled request: {req}")
|
||||
|
||||
def close(self) -> None:
|
||||
for strip in self.strips.values():
|
||||
strip.close()
|
||||
|
||||
def load_component(config: ConfigHelper) -> WLED:
|
||||
return WLED(config)
|
||||
@@ -0,0 +1,108 @@
|
||||
# Zeroconf registration implementation for Moonraker
|
||||
#
|
||||
# Copyright (C) 2021 Clifford Roche <clifford.roche@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
from __future__ import annotations
|
||||
import socket
|
||||
import asyncio
|
||||
import logging
|
||||
import ipaddress
|
||||
from zeroconf import IPVersion
|
||||
from zeroconf.asyncio import AsyncServiceInfo, AsyncZeroconf
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .machine import Machine
|
||||
|
||||
|
||||
class AsyncRunner:
|
||||
def __init__(self, ip_version: IPVersion) -> None:
|
||||
self.ip_version = ip_version
|
||||
self.aiozc: Optional[AsyncZeroconf] = None
|
||||
|
||||
async def register_services(self, infos: List[AsyncServiceInfo]) -> None:
|
||||
self.aiozc = AsyncZeroconf(ip_version=self.ip_version)
|
||||
tasks = [
|
||||
self.aiozc.async_register_service(info, allow_name_change=True)
|
||||
for info in infos
|
||||
]
|
||||
background_tasks = await asyncio.gather(*tasks)
|
||||
await asyncio.gather(*background_tasks)
|
||||
|
||||
async def unregister_services(self, infos: List[AsyncServiceInfo]) -> None:
|
||||
assert self.aiozc is not None
|
||||
tasks = [self.aiozc.async_unregister_service(info) for info in infos]
|
||||
background_tasks = await asyncio.gather(*tasks)
|
||||
await asyncio.gather(*background_tasks)
|
||||
await self.aiozc.async_close()
|
||||
|
||||
async def update_services(self, infos: List[AsyncServiceInfo]) -> None:
|
||||
assert self.aiozc is not None
|
||||
tasks = [self.aiozc.async_update_service(info) for info in infos]
|
||||
background_tasks = await asyncio.gather(*tasks)
|
||||
await asyncio.gather(*background_tasks)
|
||||
|
||||
|
||||
class ZeroconfRegistrar:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.runner = AsyncRunner(IPVersion.All)
|
||||
hi = self.server.get_host_info()
|
||||
addr: str = hi["address"]
|
||||
if addr.lower() == "all":
|
||||
addr = "::"
|
||||
host_ip = ipaddress.ip_address(addr)
|
||||
fam = socket.AF_INET6 if host_ip.version == 6 else socket.AF_INET
|
||||
addresses: List[bytes] = [(socket.inet_pton(fam, addr))]
|
||||
self.bound_all = addr in ["0.0.0.0", "::"]
|
||||
self.service_info = self._build_service_info(addresses)
|
||||
if self.bound_all:
|
||||
self.server.register_event_handler(
|
||||
"machine:net_state_changed", self._update_service)
|
||||
|
||||
async def component_init(self) -> None:
|
||||
logging.info("Starting Zeroconf services")
|
||||
if self.bound_all:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
network = machine.get_system_info()["network"]
|
||||
addresses = [x for x in self._extract_ip_addresses(network)]
|
||||
self.service_info = self._build_service_info(addresses)
|
||||
await self.runner.register_services([self.service_info])
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.runner.unregister_services([self.service_info])
|
||||
|
||||
async def _update_service(self, network: Dict[str, Any]) -> None:
|
||||
if self.bound_all:
|
||||
addresses = [x for x in self._extract_ip_addresses(network)]
|
||||
self.service_info = self._build_service_info(addresses)
|
||||
await self.runner.update_services([self.service_info])
|
||||
|
||||
def _build_service_info(self,
|
||||
addresses: Optional[List[bytes]] = None
|
||||
) -> AsyncServiceInfo:
|
||||
hi = self.server.get_host_info()
|
||||
return AsyncServiceInfo(
|
||||
"_moonraker._tcp.local.",
|
||||
f"Moonraker Instance on {hi['hostname']}._moonraker._tcp.local.",
|
||||
addresses=addresses,
|
||||
port=hi["port"],
|
||||
properties={"path": "/"},
|
||||
server=f"{hi['hostname']}.local.",
|
||||
)
|
||||
|
||||
def _extract_ip_addresses(self, network: Dict[str, Any]) -> Iterator[bytes]:
|
||||
for ifname, ifinfo in network.items():
|
||||
for addr_info in ifinfo["ip_addresses"]:
|
||||
if addr_info["is_link_local"]:
|
||||
continue
|
||||
is_ipv6 = addr_info['family'] == "ipv6"
|
||||
family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
|
||||
yield socket.inet_pton(family, addr_info["address"])
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> ZeroconfRegistrar:
|
||||
return ZeroconfRegistrar(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,188 @@
|
||||
# Wrapper around the asyncio eventloop
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import inspect
|
||||
import functools
|
||||
import socket
|
||||
import time
|
||||
import logging
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Optional,
|
||||
Tuple,
|
||||
TypeVar,
|
||||
Union
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
_T = TypeVar("_T")
|
||||
FlexCallback = Callable[..., Optional[Awaitable]]
|
||||
TimerCallback = Callable[[float], Union[float, Awaitable[float]]]
|
||||
|
||||
class EventLoop:
|
||||
TimeoutError = asyncio.TimeoutError
|
||||
def __init__(self) -> None:
|
||||
self.reset()
|
||||
|
||||
def reset(self) -> None:
|
||||
self.aioloop = self._create_new_loop()
|
||||
self.add_signal_handler = self.aioloop.add_signal_handler
|
||||
self.remove_signal_handler = self.aioloop.remove_signal_handler
|
||||
self.add_reader = self.aioloop.add_reader
|
||||
self.add_writer = self.aioloop.add_writer
|
||||
self.remove_reader = self.aioloop.remove_reader
|
||||
self.remove_writer = self.aioloop.remove_writer
|
||||
self.get_loop_time = self.aioloop.time
|
||||
self.create_future = self.aioloop.create_future
|
||||
self.create_task = self.aioloop.create_task
|
||||
self.call_at = self.aioloop.call_at
|
||||
self.set_debug = self.aioloop.set_debug
|
||||
self.is_running = self.aioloop.is_running
|
||||
|
||||
def _create_new_loop(self) -> asyncio.AbstractEventLoop:
|
||||
for _ in range(5):
|
||||
# Sometimes the new loop does not properly instantiate.
|
||||
# Give 5 attempts before raising an exception
|
||||
new_loop = asyncio.new_event_loop()
|
||||
if not new_loop.is_closed():
|
||||
break
|
||||
logging.info("Failed to create open eventloop, "
|
||||
"retyring in .5 seconds...")
|
||||
time.sleep(.5)
|
||||
else:
|
||||
raise RuntimeError("Unable to create new open eventloop")
|
||||
asyncio.set_event_loop(new_loop)
|
||||
return new_loop
|
||||
|
||||
def register_callback(self,
|
||||
callback: FlexCallback,
|
||||
*args,
|
||||
**kwargs
|
||||
) -> None:
|
||||
async def _wrapper():
|
||||
try:
|
||||
ret = callback(*args, **kwargs)
|
||||
if inspect.isawaitable(ret):
|
||||
await ret
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception("Error Running Callback")
|
||||
self.aioloop.create_task(_wrapper())
|
||||
|
||||
def delay_callback(self,
|
||||
delay: float,
|
||||
callback: FlexCallback,
|
||||
*args,
|
||||
**kwargs
|
||||
) -> asyncio.TimerHandle:
|
||||
return self.aioloop.call_later(
|
||||
delay, self.register_callback,
|
||||
functools.partial(callback, *args, **kwargs)
|
||||
)
|
||||
|
||||
def register_timer(self, callback: TimerCallback):
|
||||
return FlexTimer(self, callback)
|
||||
|
||||
def run_in_thread(self,
|
||||
callback: Callable[..., _T],
|
||||
*args
|
||||
) -> Awaitable[_T]:
|
||||
return self.aioloop.run_in_executor(None, callback, *args)
|
||||
|
||||
async def create_socket_connection(
|
||||
self, address: Tuple[str, int], timeout: Optional[float] = None
|
||||
) -> socket.socket:
|
||||
host, port = address
|
||||
"""
|
||||
async port of socket.create_connection()
|
||||
"""
|
||||
loop = self.aioloop
|
||||
err = None
|
||||
ainfo = await loop.getaddrinfo(
|
||||
host, port, family=0, type=socket.SOCK_STREAM
|
||||
)
|
||||
for res in ainfo:
|
||||
af, socktype, proto, canonname, sa = res
|
||||
sock = None
|
||||
try:
|
||||
sock = socket.socket(af, socktype, proto)
|
||||
sock.settimeout(0)
|
||||
sock.setblocking(False)
|
||||
await asyncio.wait_for(
|
||||
loop.sock_connect(sock, (host, port)), timeout
|
||||
)
|
||||
# Break explicitly a reference cycle
|
||||
err = None
|
||||
return sock
|
||||
except (socket.error, asyncio.TimeoutError) as _:
|
||||
err = _
|
||||
if sock is not None:
|
||||
loop.remove_writer(sock.fileno())
|
||||
sock.close()
|
||||
if err is not None:
|
||||
try:
|
||||
raise err
|
||||
finally:
|
||||
# Break explicitly a reference cycle
|
||||
err = None
|
||||
else:
|
||||
raise socket.error("getaddrinfo returns an empty list")
|
||||
|
||||
def start(self):
|
||||
self.aioloop.run_forever()
|
||||
|
||||
def stop(self):
|
||||
self.aioloop.stop()
|
||||
|
||||
def close(self):
|
||||
self.aioloop.close()
|
||||
|
||||
class FlexTimer:
|
||||
def __init__(self,
|
||||
eventloop: EventLoop,
|
||||
callback: TimerCallback
|
||||
) -> None:
|
||||
self.eventloop = eventloop
|
||||
self.callback = callback
|
||||
self.timer_handle: Optional[asyncio.TimerHandle] = None
|
||||
self.running: bool = False
|
||||
|
||||
def start(self, delay: float = 0.):
|
||||
if self.running:
|
||||
return
|
||||
self.running = True
|
||||
call_time = self.eventloop.get_loop_time() + delay
|
||||
self.timer_handle = self.eventloop.call_at(
|
||||
call_time, self._schedule_task)
|
||||
|
||||
def stop(self):
|
||||
if not self.running:
|
||||
return
|
||||
self.running = False
|
||||
if self.timer_handle is not None:
|
||||
self.timer_handle.cancel()
|
||||
self.timer_handle = None
|
||||
|
||||
def _schedule_task(self):
|
||||
self.timer_handle = None
|
||||
self.eventloop.create_task(self._call_wrapper())
|
||||
|
||||
def is_running(self) -> bool:
|
||||
return self.running
|
||||
|
||||
async def _call_wrapper(self):
|
||||
if not self.running:
|
||||
return
|
||||
ret = self.callback(self.eventloop.get_loop_time())
|
||||
if isinstance(ret, Awaitable):
|
||||
ret = await ret
|
||||
if self.running:
|
||||
self.timer_handle = self.eventloop.call_at(ret, self._schedule_task)
|
||||
@@ -0,0 +1,692 @@
|
||||
|
||||
# KlippyConnection - manage unix socket connection to Klipper
|
||||
#
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import json
|
||||
import getpass
|
||||
import asyncio
|
||||
import pathlib
|
||||
from .utils import ServerError, get_unix_peer_credentials
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Awaitable,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
List,
|
||||
Set,
|
||||
Tuple
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from .server import Server
|
||||
from .app import MoonrakerApp
|
||||
from .websockets import WebRequest, Subscribable
|
||||
from .confighelper import ConfigHelper
|
||||
from .components.klippy_apis import KlippyAPI
|
||||
from .components.file_manager.file_manager import FileManager
|
||||
from .components.machine import Machine
|
||||
from .components.job_state import JobState
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
|
||||
# These endpoints are reserved for klippy/moonraker communication only and are
|
||||
# not exposed via http or the websocket
|
||||
RESERVED_ENDPOINTS = [
|
||||
"list_endpoints",
|
||||
"gcode/subscribe_output",
|
||||
"register_remote_method",
|
||||
]
|
||||
|
||||
INIT_TIME = .25
|
||||
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
|
||||
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, server: Server) -> None:
|
||||
self.server = server
|
||||
self.uds_address = pathlib.Path("/tmp/klippy_uds")
|
||||
self.writer: Optional[asyncio.StreamWriter] = None
|
||||
self.connection_mutex: asyncio.Lock = asyncio.Lock()
|
||||
self.event_loop = self.server.get_event_loop()
|
||||
self.log_no_access = True
|
||||
# Connection State
|
||||
self.connection_task: Optional[asyncio.Task] = None
|
||||
self.closing: bool = False
|
||||
self._klippy_info: Dict[str, Any] = {}
|
||||
self._klippy_identified: bool = False
|
||||
self._klippy_initializing: bool = False
|
||||
self._klippy_started: bool = False
|
||||
self._klipper_version: str = ""
|
||||
self._missing_reqs: Set[str] = set()
|
||||
self._peer_cred: Dict[str, int] = {}
|
||||
self._service_info: Dict[str, Any] = {}
|
||||
self.init_attempts: int = 0
|
||||
self._state: str = "disconnected"
|
||||
self._state_message: str = "Klippy Disconnected"
|
||||
self.subscriptions: Dict[Subscribable, Dict[str, Any]] = {}
|
||||
# Setup remote methods accessable to Klippy. Note that all
|
||||
# registered remote methods should be of the notification type,
|
||||
# they do not return a response to Klippy after execution
|
||||
self.pending_requests: Dict[int, KlippyRequest] = {}
|
||||
self.remote_methods: Dict[str, FlexCallback] = {}
|
||||
self.klippy_reg_methods: List[str] = []
|
||||
self.register_remote_method(
|
||||
'process_gcode_response', self._process_gcode_response,
|
||||
need_klippy_reg=False)
|
||||
self.register_remote_method(
|
||||
'process_status_update', self._process_status_update,
|
||||
need_klippy_reg=False)
|
||||
self.server.register_component("klippy_connection", self)
|
||||
|
||||
def configure(self, config: ConfigHelper):
|
||||
self.uds_address = config.getpath(
|
||||
"klippy_uds_address", self.uds_address
|
||||
)
|
||||
|
||||
@property
|
||||
def klippy_apis(self) -> KlippyAPI:
|
||||
return self.server.lookup_component("klippy_apis")
|
||||
|
||||
@property
|
||||
def state(self) -> str:
|
||||
if self.is_connected() and not self._klippy_started:
|
||||
return "startup"
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def state_message(self) -> str:
|
||||
return self._state_message
|
||||
|
||||
@property
|
||||
def klippy_info(self) -> Dict[str, Any]:
|
||||
return self._klippy_info
|
||||
|
||||
@property
|
||||
def missing_requirements(self) -> List[str]:
|
||||
return list(self._missing_reqs)
|
||||
|
||||
@property
|
||||
def peer_credentials(self) -> Dict[str, int]:
|
||||
return dict(self._peer_cred)
|
||||
|
||||
@property
|
||||
def service_info(self) -> Dict[str, Any]:
|
||||
return self._service_info
|
||||
|
||||
@property
|
||||
def unit_name(self) -> str:
|
||||
svc_info = self._service_info
|
||||
unit_name = svc_info.get("unit_name", "klipper.service")
|
||||
return unit_name.split(".", 1)[0]
|
||||
|
||||
async def wait_connected(self) -> bool:
|
||||
if (
|
||||
self.connection_task is None or
|
||||
self.connection_task.done()
|
||||
):
|
||||
return self.is_connected()
|
||||
try:
|
||||
await self.connection_task
|
||||
except Exception:
|
||||
pass
|
||||
return self.is_connected()
|
||||
|
||||
async def wait_started(self, timeout: float = 20.) -> bool:
|
||||
if self.connection_task is None or not self.is_connected():
|
||||
return False
|
||||
if not self.connection_task.done():
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(self.connection_task), timeout=timeout)
|
||||
return self.is_connected()
|
||||
|
||||
async def _read_stream(self, reader: asyncio.StreamReader) -> None:
|
||||
errors_remaining: int = 10
|
||||
while not reader.at_eof():
|
||||
try:
|
||||
data = await reader.readuntil(b'\x03')
|
||||
except (ConnectionError, asyncio.IncompleteReadError):
|
||||
break
|
||||
except asyncio.CancelledError:
|
||||
logging.exception("Klippy Stream Read Cancelled")
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception("Klippy Stream Read Error")
|
||||
errors_remaining -= 1
|
||||
if not errors_remaining or not self.is_connected():
|
||||
break
|
||||
continue
|
||||
errors_remaining = 10
|
||||
try:
|
||||
decoded_cmd = json.loads(data[:-1])
|
||||
self._process_command(decoded_cmd)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error processing Klippy Host Response: {data.decode()}")
|
||||
if not self.closing:
|
||||
logging.debug("Klippy Disconnection From _read_stream()")
|
||||
await self.close()
|
||||
|
||||
async def _write_request(self, request: KlippyRequest) -> None:
|
||||
if self.writer is None or self.closing:
|
||||
self.pending_requests.pop(request.id, None)
|
||||
request.notify(ServerError("Klippy Host not connected", 503))
|
||||
return
|
||||
data = json.dumps(request.to_dict()).encode() + b"\x03"
|
||||
try:
|
||||
self.writer.write(data)
|
||||
await self.writer.drain()
|
||||
except asyncio.CancelledError:
|
||||
self.pending_requests.pop(request.id, None)
|
||||
request.notify(ServerError("Klippy Write Request Cancelled", 503))
|
||||
raise
|
||||
except Exception:
|
||||
self.pending_requests.pop(request.id, None)
|
||||
request.notify(ServerError("Klippy Write Request Error", 503))
|
||||
if not self.closing:
|
||||
logging.debug("Klippy Disconnection From _write_request()")
|
||||
await self.close()
|
||||
|
||||
def register_remote_method(self,
|
||||
method_name: str,
|
||||
cb: FlexCallback,
|
||||
need_klippy_reg: bool = True
|
||||
) -> None:
|
||||
if method_name in self.remote_methods:
|
||||
raise self.server.error(
|
||||
f"Remote method ({method_name}) already registered")
|
||||
if self.server.is_running():
|
||||
raise self.server.error(
|
||||
f"Failed to register remote method {method_name}, "
|
||||
"methods must be registered during initialization")
|
||||
self.remote_methods[method_name] = cb
|
||||
if need_klippy_reg:
|
||||
# These methods need to be registered with Klippy
|
||||
self.klippy_reg_methods.append(method_name)
|
||||
|
||||
def connect(self) -> Awaitable[bool]:
|
||||
if (
|
||||
self.is_connected() or
|
||||
not self.server.is_running() or
|
||||
(self.connection_task is not None and
|
||||
not self.connection_task.done())
|
||||
):
|
||||
# already connecting
|
||||
fut = self.event_loop.create_future()
|
||||
fut.set_result(self.is_connected())
|
||||
return fut
|
||||
self.connection_task = self.event_loop.create_task(self._do_connect())
|
||||
return self.connection_task
|
||||
|
||||
async def _do_connect(self) -> bool:
|
||||
async with self.connection_mutex:
|
||||
while self.writer is None:
|
||||
await asyncio.sleep(INIT_TIME)
|
||||
if self.closing or not self.server.is_running():
|
||||
return False
|
||||
if not self.uds_address.exists():
|
||||
continue
|
||||
if not os.access(str(self.uds_address), os.R_OK | os.W_OK):
|
||||
if self.log_no_access:
|
||||
user = getpass.getuser()
|
||||
logging.info(
|
||||
f"Cannot connect to Klippy, Linux user '{user}' "
|
||||
"lacks permission to open Unix Domain Socket: "
|
||||
f"{self.uds_address}")
|
||||
self.log_no_access = False
|
||||
continue
|
||||
self.log_no_access = True
|
||||
try:
|
||||
reader, writer = await self.open_klippy_connection(True)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
continue
|
||||
logging.info("Klippy Connection Established")
|
||||
self.writer = writer
|
||||
if self._get_peer_credentials(writer):
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
provider = machine.get_system_provider()
|
||||
svc_info = await provider.extract_service_info(
|
||||
"klipper", self._peer_cred["process_id"]
|
||||
)
|
||||
if svc_info != self._service_info:
|
||||
self._service_info = svc_info
|
||||
machine.log_service_info(svc_info)
|
||||
self.event_loop.create_task(self._read_stream(reader))
|
||||
return await self._init_klippy_connection()
|
||||
|
||||
async def open_klippy_connection(
|
||||
self, primary: bool = False
|
||||
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
|
||||
if not primary and not self.is_connected():
|
||||
raise ServerError("Klippy Unix Connection Not Available", 503)
|
||||
return await asyncio.open_unix_connection(
|
||||
str(self.uds_address), limit=UNIX_BUFFER_LIMIT)
|
||||
|
||||
def _get_peer_credentials(self, writer: asyncio.StreamWriter) -> bool:
|
||||
self._peer_cred = get_unix_peer_credentials(writer, "Klippy")
|
||||
if not self._peer_cred:
|
||||
return False
|
||||
logging.debug(
|
||||
f"Klippy Connection: Received Peer Credentials: {self._peer_cred}"
|
||||
)
|
||||
return True
|
||||
|
||||
async def _init_klippy_connection(self) -> bool:
|
||||
self._klippy_identified = False
|
||||
self._klippy_started = False
|
||||
self._klippy_initializing = True
|
||||
self._missing_reqs.clear()
|
||||
self.init_attempts = 0
|
||||
self._state = "startup"
|
||||
while self.server.is_running():
|
||||
await asyncio.sleep(INIT_TIME)
|
||||
await self._check_ready()
|
||||
if not self._klippy_initializing:
|
||||
logging.debug("Klippy Connection Initialized")
|
||||
return True
|
||||
if not self.is_connected():
|
||||
self._klippy_initializing = False
|
||||
break
|
||||
else:
|
||||
self.init_attempts += 1
|
||||
logging.debug("Klippy Connection Failed to Init")
|
||||
return False
|
||||
|
||||
async def _request_endpoints(self) -> None:
|
||||
result = await self.klippy_apis.list_endpoints(default=None)
|
||||
if result is None:
|
||||
return
|
||||
endpoints = result.get('endpoints', [])
|
||||
app: MoonrakerApp = self.server.lookup_component("application")
|
||||
for ep in endpoints:
|
||||
if ep not in RESERVED_ENDPOINTS:
|
||||
app.register_remote_handler(ep)
|
||||
|
||||
async def _request_initial_subscriptions(self) -> None:
|
||||
try:
|
||||
await self.klippy_apis.subscribe_objects({'webhooks': None})
|
||||
except ServerError as e:
|
||||
logging.exception("Unable to subscribe to webhooks object")
|
||||
else:
|
||||
logging.info("Webhooks Subscribed")
|
||||
try:
|
||||
await self.klippy_apis.subscribe_gcode_output()
|
||||
except ServerError as e:
|
||||
logging.exception(
|
||||
"Unable to register gcode output subscription"
|
||||
)
|
||||
else:
|
||||
logging.info("GCode Output Subscribed")
|
||||
|
||||
async def _check_ready(self) -> None:
|
||||
send_id = not self._klippy_identified
|
||||
result: Dict[str, Any]
|
||||
try:
|
||||
result = await self.klippy_apis.get_klippy_info(send_id)
|
||||
except ServerError as e:
|
||||
if self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
|
||||
self.init_attempts <= MAX_LOG_ATTEMPTS:
|
||||
logging.info(
|
||||
f"{e}\nKlippy info request error. This indicates that\n"
|
||||
f"Klippy may have experienced an error during startup.\n"
|
||||
f"Please check klippy.log for more information")
|
||||
return
|
||||
version = result.get("software_version", "")
|
||||
if version != self._klipper_version:
|
||||
self._klipper_version = version
|
||||
msg = f"Klipper Version: {version}"
|
||||
self.server.add_log_rollover_item("klipper_version", msg)
|
||||
self._klippy_info = dict(result)
|
||||
if "state_message" in self._klippy_info:
|
||||
self._state_message = self._klippy_info["state_message"]
|
||||
if "state" not in result:
|
||||
return
|
||||
if send_id:
|
||||
self._klippy_identified = True
|
||||
await self.server.send_event("server:klippy_identified")
|
||||
# Request initial endpoints to register info, emergency stop APIs
|
||||
await self._request_endpoints()
|
||||
self._state = result["state"]
|
||||
if self._state != "startup":
|
||||
await self._request_initial_subscriptions()
|
||||
# Register remaining endpoints available
|
||||
await self._request_endpoints()
|
||||
startup_state = self._state
|
||||
await self.server.send_event(
|
||||
"server:klippy_started", startup_state
|
||||
)
|
||||
self._klippy_started = True
|
||||
if self._state != "ready":
|
||||
logging.info("\n" + self._state_message)
|
||||
if self._state == "shutdown" and startup_state != "shutdown":
|
||||
# Klippy shutdown during startup event
|
||||
self.server.send_event("server:klippy_shutdown")
|
||||
else:
|
||||
await self._verify_klippy_requirements()
|
||||
# register methods with klippy
|
||||
for method in self.klippy_reg_methods:
|
||||
try:
|
||||
await self.klippy_apis.register_method(method)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
f"Unable to register method '{method}'")
|
||||
if self._state == "ready":
|
||||
logging.info("Klippy ready")
|
||||
await self.server.send_event("server:klippy_ready")
|
||||
if self._state == "shutdown":
|
||||
# Klippy shutdown during ready event
|
||||
self.server.send_event("server:klippy_shutdown")
|
||||
else:
|
||||
logging.info(
|
||||
"Klippy state transition from ready during init, "
|
||||
f"new state: {self._state}"
|
||||
)
|
||||
self._klippy_initializing = False
|
||||
|
||||
async def _verify_klippy_requirements(self) -> None:
|
||||
result = await self.klippy_apis.get_object_list(default=None)
|
||||
if result is None:
|
||||
logging.info(
|
||||
f"Unable to retrieve Klipper Object List")
|
||||
return
|
||||
req_objs = set(["virtual_sdcard", "display_status", "pause_resume"])
|
||||
self._missing_reqs = req_objs - set(result)
|
||||
if self._missing_reqs:
|
||||
err_str = ", ".join([f"[{o}]" for o in self._missing_reqs])
|
||||
logging.info(
|
||||
f"\nWarning, unable to detect the following printer "
|
||||
f"objects:\n{err_str}\nPlease add the the above sections "
|
||||
f"to printer.cfg for full Moonraker functionality.")
|
||||
if "virtual_sdcard" not in self._missing_reqs:
|
||||
# Update the gcode path
|
||||
query_res = await self.klippy_apis.query_objects(
|
||||
{'configfile': None}, default=None)
|
||||
if query_res is None:
|
||||
logging.info(f"Unable to set SD Card path")
|
||||
else:
|
||||
config = query_res.get('configfile', {}).get('config', {})
|
||||
vsd_config = config.get('virtual_sdcard', {})
|
||||
vsd_path = vsd_config.get('path', None)
|
||||
if vsd_path is not None:
|
||||
file_manager: FileManager = self.server.lookup_component(
|
||||
'file_manager')
|
||||
file_manager.validate_gcode_path(vsd_path)
|
||||
else:
|
||||
logging.info(
|
||||
"Configuration for [virtual_sdcard] not found,"
|
||||
" unable to set SD Card path")
|
||||
|
||||
def _process_command(self, cmd: Dict[str, Any]) -> None:
|
||||
method = cmd.get('method', None)
|
||||
if method is not None:
|
||||
# This is a remote method called from klippy
|
||||
if method in self.remote_methods:
|
||||
params = cmd.get('params', {})
|
||||
self.event_loop.register_callback(
|
||||
self._execute_method, method, **params)
|
||||
else:
|
||||
logging.info(f"Unknown method received: {method}")
|
||||
return
|
||||
# This is a response to a request, process
|
||||
req_id = cmd.get('id', None)
|
||||
request: Optional[KlippyRequest]
|
||||
request = self.pending_requests.pop(req_id, None)
|
||||
if request is None:
|
||||
logging.info(
|
||||
f"No request matching request ID: {req_id}, "
|
||||
f"response: {cmd}")
|
||||
return
|
||||
if 'result' in cmd:
|
||||
result = cmd['result']
|
||||
if not result:
|
||||
result = "ok"
|
||||
else:
|
||||
err = cmd.get('error', "Malformed Klippy Response")
|
||||
result = ServerError(err, 400)
|
||||
request.notify(result)
|
||||
|
||||
async def _execute_method(self, method_name: str, **kwargs) -> None:
|
||||
try:
|
||||
ret = self.remote_methods[method_name](**kwargs)
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(f"Error running remote method: {method_name}")
|
||||
|
||||
def _process_gcode_response(self, response: str) -> None:
|
||||
self.server.send_event("server:gcode_response", response)
|
||||
|
||||
def _process_status_update(self,
|
||||
eventtime: float,
|
||||
status: Dict[str, Any]
|
||||
) -> None:
|
||||
if 'webhooks' in status:
|
||||
wh: Dict[str, str] = status['webhooks']
|
||||
if "state_message" in wh:
|
||||
self._state_message = wh["state_message"]
|
||||
# XXX - process other states (startup, ready, error, etc)?
|
||||
if "state" in wh:
|
||||
state = wh["state"]
|
||||
if state == "shutdown" and not self._klippy_initializing:
|
||||
# If the shutdown state is received during initialization
|
||||
# defer the event, the init routine will handle it.
|
||||
logging.info("Klippy has shutdown")
|
||||
self.server.send_event("server:klippy_shutdown")
|
||||
self._state = state
|
||||
for conn, sub in self.subscriptions.items():
|
||||
conn_status: Dict[str, Any] = {}
|
||||
for name, fields in sub.items():
|
||||
if name in status:
|
||||
val: Dict[str, Any] = dict(status[name])
|
||||
if fields is not None:
|
||||
val = {k: v for k, v in val.items() if k in fields}
|
||||
if val:
|
||||
conn_status[name] = val
|
||||
conn.send_status(conn_status, eventtime)
|
||||
|
||||
async def request(self, web_request: WebRequest) -> Any:
|
||||
if not self.is_connected():
|
||||
raise ServerError("Klippy Host not connected", 503)
|
||||
rpc_method = web_request.get_endpoint()
|
||||
if rpc_method == "objects/subscribe":
|
||||
return await self._request_subscripton(web_request)
|
||||
else:
|
||||
if rpc_method == "gcode/script":
|
||||
script = web_request.get_str('script', "")
|
||||
if script:
|
||||
self.server.send_event(
|
||||
"klippy_connection:gcode_received", script)
|
||||
return await self._request_standard(web_request)
|
||||
|
||||
async def _request_subscripton(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
args = web_request.get_args()
|
||||
conn = web_request.get_subscribable()
|
||||
|
||||
# Build the subscription request from a superset of all client
|
||||
# subscriptions
|
||||
sub = args.get('objects', {})
|
||||
if conn is None:
|
||||
raise self.server.error(
|
||||
"No connection associated with subscription request")
|
||||
self.subscriptions[conn] = sub
|
||||
all_subs: Dict[str, Any] = {}
|
||||
# request superset of all client subscriptions
|
||||
for sub in self.subscriptions.values():
|
||||
for obj, items in sub.items():
|
||||
if obj in all_subs:
|
||||
pi = all_subs[obj]
|
||||
if items is None or pi is None:
|
||||
all_subs[obj] = None
|
||||
else:
|
||||
uitems = list(set(pi) | set(items))
|
||||
all_subs[obj] = uitems
|
||||
else:
|
||||
all_subs[obj] = items
|
||||
args['objects'] = all_subs
|
||||
args['response_template'] = {'method': "process_status_update"}
|
||||
|
||||
result = await self._request_standard(web_request)
|
||||
|
||||
# prune the status response
|
||||
pruned_status = {}
|
||||
all_status = result['status']
|
||||
sub = self.subscriptions.get(conn, {})
|
||||
for obj, fields in all_status.items():
|
||||
if obj in sub:
|
||||
valid_fields = sub[obj]
|
||||
if valid_fields is None:
|
||||
pruned_status[obj] = fields
|
||||
else:
|
||||
pruned_status[obj] = {k: v for k, v in fields.items()
|
||||
if k in valid_fields}
|
||||
result['status'] = pruned_status
|
||||
return result
|
||||
|
||||
async def _request_standard(self, web_request: WebRequest) -> Any:
|
||||
rpc_method = web_request.get_endpoint()
|
||||
args = web_request.get_args()
|
||||
# Create a base klippy request
|
||||
base_request = KlippyRequest(rpc_method, args)
|
||||
self.pending_requests[base_request.id] = base_request
|
||||
self.event_loop.register_callback(self._write_request, base_request)
|
||||
return await base_request.wait()
|
||||
|
||||
def remove_subscription(self, conn: Subscribable) -> None:
|
||||
self.subscriptions.pop(conn, None)
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
return self.writer is not None and not self.closing
|
||||
|
||||
def is_ready(self) -> bool:
|
||||
return self._state == "ready"
|
||||
|
||||
def is_printing(self) -> bool:
|
||||
if not self.is_ready():
|
||||
return False
|
||||
job_state: JobState = self.server.lookup_component("job_state")
|
||||
stats = job_state.get_last_stats()
|
||||
return stats.get("state", "") == "printing"
|
||||
|
||||
async def rollover_log(self) -> None:
|
||||
if "unit_name" not in self._service_info:
|
||||
raise self.server.error(
|
||||
"Unable to detect Klipper Service, cannot perform "
|
||||
"manual rollover"
|
||||
)
|
||||
logfile: Optional[str] = self._klippy_info.get("log_file", None)
|
||||
if logfile is None:
|
||||
raise self.server.error(
|
||||
"Unable to detect path to Klipper log file"
|
||||
)
|
||||
if self.is_printing():
|
||||
raise self.server.error("Cannot rollover log while printing")
|
||||
logpath = pathlib.Path(logfile).expanduser().resolve()
|
||||
if not logpath.is_file():
|
||||
raise self.server.error(
|
||||
f"No file at {logpath} exists, cannot perform rollover"
|
||||
)
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
await machine.do_service_action("stop", self.unit_name)
|
||||
suffix = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
new_path = pathlib.Path(f"{logpath}.{suffix}")
|
||||
|
||||
def _do_file_op() -> None:
|
||||
if new_path.exists():
|
||||
new_path.unlink()
|
||||
logpath.rename(new_path)
|
||||
|
||||
await self.event_loop.run_in_thread(_do_file_op)
|
||||
await machine.do_service_action("start", self.unit_name)
|
||||
|
||||
async def _on_connection_closed(self) -> None:
|
||||
self._klippy_identified = False
|
||||
self._klippy_initializing = False
|
||||
self._klippy_started = False
|
||||
self._state = "disconnected"
|
||||
self._state_message = "Klippy Disconnected"
|
||||
for request in self.pending_requests.values():
|
||||
request.notify(ServerError("Klippy Disconnected", 503))
|
||||
self.pending_requests = {}
|
||||
self.subscriptions = {}
|
||||
self._peer_cred = {}
|
||||
self._missing_reqs.clear()
|
||||
logging.info("Klippy Connection Removed")
|
||||
await self.server.send_event("server:klippy_disconnect")
|
||||
if self.server.is_running():
|
||||
# Reconnect if server is running
|
||||
loop = self.event_loop
|
||||
self.connection_task = loop.create_task(self._do_connect())
|
||||
|
||||
async def close(self, wait_closed: bool = False) -> None:
|
||||
if self.closing:
|
||||
if wait_closed:
|
||||
await self.connection_mutex.acquire()
|
||||
self.connection_mutex.release()
|
||||
return
|
||||
self.closing = True
|
||||
if (
|
||||
self.connection_task is not None and
|
||||
not self.connection_task.done()
|
||||
):
|
||||
self.connection_task.cancel()
|
||||
async with self.connection_mutex:
|
||||
if self.writer is not None:
|
||||
try:
|
||||
self.writer.close()
|
||||
await self.writer.wait_closed()
|
||||
except Exception:
|
||||
logging.exception("Error closing Klippy Unix Socket")
|
||||
self.writer = None
|
||||
await self._on_connection_closed()
|
||||
self.closing = False
|
||||
|
||||
# Basic KlippyRequest class, easily converted to dict for json encoding
|
||||
class KlippyRequest:
|
||||
def __init__(self, rpc_method: str, params: Dict[str, Any]) -> None:
|
||||
self.id = id(self)
|
||||
self.rpc_method = rpc_method
|
||||
self.params = params
|
||||
self._event = asyncio.Event()
|
||||
self.response: Any = None
|
||||
|
||||
async def wait(self) -> Any:
|
||||
# Log pending requests every 60 seconds
|
||||
start_time = time.time()
|
||||
while True:
|
||||
try:
|
||||
await asyncio.wait_for(self._event.wait(), 60.)
|
||||
except asyncio.TimeoutError:
|
||||
pending_time = time.time() - start_time
|
||||
logging.info(
|
||||
f"Request '{self.rpc_method}' pending: "
|
||||
f"{pending_time:.2f} seconds")
|
||||
self._event.clear()
|
||||
continue
|
||||
break
|
||||
if isinstance(self.response, ServerError):
|
||||
raise self.response
|
||||
return self.response
|
||||
|
||||
def notify(self, response: Any) -> None:
|
||||
if self._event.is_set():
|
||||
return
|
||||
self.response = response
|
||||
self._event.set()
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {'id': self.id, 'method': self.rpc_method,
|
||||
'params': self.params}
|
||||
@@ -0,0 +1,153 @@
|
||||
# Log Management
|
||||
#
|
||||
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
import asyncio
|
||||
from queue import SimpleQueue as Queue
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Optional,
|
||||
Awaitable,
|
||||
Dict,
|
||||
List,
|
||||
Any,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .server import Server
|
||||
from .websockets import WebRequest
|
||||
from .klippy_connection import KlippyConnection
|
||||
|
||||
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
|
||||
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
|
||||
class LocalQueueHandler(logging.handlers.QueueHandler):
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
# Removed the call to self.prepare(), handle task cancellation
|
||||
try:
|
||||
self.enqueue(record)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
self.handleError(record)
|
||||
|
||||
# Timed Rotating File Handler, based on Klipper's implementation
|
||||
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
def __init__(self, app_args: Dict[str, Any], **kwargs) -> None:
|
||||
super().__init__(app_args['log_file'], **kwargs)
|
||||
self.rollover_info: Dict[str, str] = {
|
||||
'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
|
||||
}
|
||||
self.rollover_info['application_args'] = "\n".join(
|
||||
[f"{k}: {v}" for k, v in app_args.items()])
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
def set_rollover_info(self, name: str, item: str) -> None:
|
||||
self.rollover_info[name] = item
|
||||
|
||||
def doRollover(self) -> None:
|
||||
super().doRollover()
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
class LogManager:
|
||||
def __init__(
|
||||
self, app_args: Dict[str, Any], startup_warnings: List[str]
|
||||
) -> None:
|
||||
root_logger = logging.getLogger()
|
||||
queue: Queue = Queue()
|
||||
queue_handler = LocalQueueHandler(queue)
|
||||
root_logger.addHandler(queue_handler)
|
||||
root_logger.setLevel(logging.INFO)
|
||||
stdout_hdlr = logging.StreamHandler(sys.stdout)
|
||||
stdout_fmt = logging.Formatter(
|
||||
'[%(filename)s:%(funcName)s()] - %(message)s')
|
||||
stdout_hdlr.setFormatter(stdout_fmt)
|
||||
for name, val in app_args.items():
|
||||
logging.info(f"{name}: {val}")
|
||||
self.file_hdlr: Optional[MoonrakerLoggingHandler] = None
|
||||
self.listener: Optional[logging.handlers.QueueListener] = None
|
||||
log_file: str = app_args.get('log_file', "")
|
||||
if log_file:
|
||||
try:
|
||||
self.file_hdlr = MoonrakerLoggingHandler(
|
||||
app_args, when='midnight', backupCount=2)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
self.file_hdlr.setFormatter(formatter)
|
||||
self.listener = logging.handlers.QueueListener(
|
||||
queue, self.file_hdlr, stdout_hdlr)
|
||||
except Exception:
|
||||
log_file = os.path.normpath(log_file)
|
||||
dir_name = os.path.dirname(log_file)
|
||||
startup_warnings.append(
|
||||
f"Unable to create log file at '{log_file}'. "
|
||||
f"Make sure that the folder '{dir_name}' exists "
|
||||
"and Moonraker has Read/Write access to the folder. "
|
||||
)
|
||||
if self.listener is None:
|
||||
self.listener = logging.handlers.QueueListener(
|
||||
queue, stdout_hdlr)
|
||||
self.listener.start()
|
||||
|
||||
def set_server(self, server: Server) -> None:
|
||||
self.server = server
|
||||
self.server.register_endpoint(
|
||||
"/server/logs/rollover", ['POST'], self._handle_log_rollover
|
||||
)
|
||||
|
||||
def set_rollover_info(self, name: str, item: str) -> None:
|
||||
if self.file_hdlr is not None:
|
||||
self.file_hdlr.set_rollover_info(name, item)
|
||||
|
||||
def rollover_log(self) -> Awaitable[None]:
|
||||
if self.file_hdlr is None:
|
||||
raise self.server.error("File Logging Disabled")
|
||||
eventloop = self.server.get_event_loop()
|
||||
return eventloop.run_in_thread(self.file_hdlr.doRollover)
|
||||
|
||||
def stop_logging(self):
|
||||
self.listener.stop()
|
||||
|
||||
async def _handle_log_rollover(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
log_apps = ["moonraker", "klipper"]
|
||||
app = web_request.get_str("application", None)
|
||||
result: Dict[str, Any] = {"rolled_over": [], "failed": {}}
|
||||
if app is not None:
|
||||
if app not in log_apps:
|
||||
raise self.server.error(f"Unknown application {app}")
|
||||
log_apps = [app]
|
||||
if "moonraker" in log_apps:
|
||||
try:
|
||||
ret = self.rollover_log()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
result["failed"]["moonraker"] = str(e)
|
||||
else:
|
||||
result["rolled_over"].append("moonraker")
|
||||
if "klipper" in log_apps:
|
||||
kconn: KlippyConnection
|
||||
kconn = self.server.lookup_component("klippy_connection")
|
||||
try:
|
||||
await kconn.rollover_log()
|
||||
except self.server.error as e:
|
||||
result["failed"]["klipper"] = str(e)
|
||||
else:
|
||||
result["rolled_over"].append("klipper")
|
||||
return result
|
||||
Regular → Executable
+12
-476
@@ -1,481 +1,17 @@
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#!/usr/bin/env python3
|
||||
# Legacy entry point for Moonraker
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import argparse
|
||||
import sys
|
||||
import importlib
|
||||
import os
|
||||
import time
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
import errno
|
||||
import tornado
|
||||
import tornado.netutil
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.util import TimeoutError
|
||||
from tornado.locks import Event
|
||||
from app import MoonrakerApp
|
||||
from utils import ServerError, MoonrakerLoggingHandler
|
||||
|
||||
INIT_MS = 1000
|
||||
|
||||
CORE_PLUGINS = [
|
||||
'file_manager', 'gcode_apis', 'machine',
|
||||
'temperature_store', 'shell_command']
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class Server:
|
||||
error = ServerError
|
||||
def __init__(self, args):
|
||||
self.host = args.address
|
||||
self.port = args.port
|
||||
|
||||
# Options configurable by Klippy
|
||||
self.request_timeout = 5.
|
||||
self.long_running_gcodes = {}
|
||||
self.long_running_requests = {}
|
||||
|
||||
# Event initialization
|
||||
self.events = {}
|
||||
|
||||
# Klippy Connection Handling
|
||||
socketfile = os.path.normpath(os.path.expanduser(args.socketfile))
|
||||
self.klippy_server_sock = tornado.netutil.bind_unix_socket(
|
||||
socketfile, backlog=1)
|
||||
self.remove_server_sock = tornado.netutil.add_accept_handler(
|
||||
self.klippy_server_sock, self._handle_klippy_connection)
|
||||
self.klippy_sock = None
|
||||
self.is_klippy_connected = False
|
||||
self.is_klippy_ready = False
|
||||
self.server_configured = False
|
||||
self.partial_data = b""
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
self.moonraker_app = app = MoonrakerApp(self, args)
|
||||
self.io_loop = IOLoop.current()
|
||||
self.init_cb = PeriodicCallback(self._initialize, INIT_MS)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
self.register_endpoint = app.register_local_handler
|
||||
self.register_static_file_handler = app.register_static_file_handler
|
||||
self.register_upload_handler = app.register_upload_handler
|
||||
|
||||
for plugin in CORE_PLUGINS:
|
||||
self.load_plugin(plugin)
|
||||
|
||||
# Setup remote methods accessable to Klippy. Note that all
|
||||
# registered remote methods should be of the notification type,
|
||||
# they do not return a response to Klippy after execution
|
||||
self.pending_requests = {}
|
||||
self.remote_methods = {}
|
||||
self.register_remote_method(
|
||||
'set_klippy_shutdown', self._set_klippy_shutdown)
|
||||
self.register_remote_method(
|
||||
'response', self._handle_klippy_response)
|
||||
self.register_remote_method(
|
||||
'process_gcode_response', self._process_gcode_response)
|
||||
self.register_remote_method(
|
||||
'process_status_update', self._process_status_update)
|
||||
|
||||
def start(self):
|
||||
logging.info(
|
||||
"Starting Moonraker on (%s, %d)" %
|
||||
(self.host, self.port))
|
||||
self.moonraker_app.listen(self.host, self.port)
|
||||
self.server_running = True
|
||||
|
||||
# ***** Plugin Management *****
|
||||
def load_plugin(self, plugin_name, default=Sentinel):
|
||||
if plugin_name in self.plugins:
|
||||
return self.plugins[plugin_name]
|
||||
# Make sure plugin exists
|
||||
mod_path = os.path.join(
|
||||
os.path.dirname(__file__), 'plugins', plugin_name + '.py')
|
||||
if not os.path.exists(mod_path):
|
||||
msg = "Plugin (%s) does not exist" % (plugin_name)
|
||||
logging.info(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
module = importlib.import_module("plugins." + plugin_name)
|
||||
try:
|
||||
load_func = getattr(module, "load_plugin")
|
||||
plugin = load_func(self)
|
||||
except Exception:
|
||||
msg = "Unable to load plugin (%s)" % (plugin_name)
|
||||
logging.info(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
self.plugins[plugin_name] = plugin
|
||||
logging.info("Plugin (%s) loaded" % (plugin_name))
|
||||
return plugin
|
||||
|
||||
def lookup_plugin(self, plugin_name, default=Sentinel):
|
||||
plugin = self.plugins.get(plugin_name, default)
|
||||
if plugin == Sentinel:
|
||||
raise ServerError("Plugin (%s) not found" % (plugin_name))
|
||||
return plugin
|
||||
|
||||
def register_event_handler(self, event, callback):
|
||||
self.events.setdefault(event, []).append(callback)
|
||||
|
||||
def send_event(self, event, *args):
|
||||
events = self.events.get(event, [])
|
||||
for evt in events:
|
||||
self.io_loop.spawn_callback(evt, *args)
|
||||
|
||||
def register_remote_method(self, method_name, cb):
|
||||
if method_name in self.remote_methods:
|
||||
# XXX - may want to raise an exception here
|
||||
logging.info("Remote method (%s) already registered"
|
||||
% (method_name))
|
||||
return
|
||||
self.remote_methods[method_name] = cb
|
||||
|
||||
# ***** Klippy Connection *****
|
||||
def _handle_klippy_connection(self, conn, addr):
|
||||
if self.is_klippy_connected:
|
||||
logging.info("New Connection received while Klippy Connected")
|
||||
self.close_client_sock()
|
||||
logging.info("Klippy Connection Established")
|
||||
self.is_klippy_connected = True
|
||||
conn.setblocking(0)
|
||||
self.klippy_sock = conn
|
||||
self.io_loop.add_handler(
|
||||
self.klippy_sock.fileno(), self._handle_klippy_data,
|
||||
IOLoop.READ | IOLoop.ERROR)
|
||||
# begin server iniialization
|
||||
self.init_cb.start()
|
||||
|
||||
def _handle_klippy_data(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
self.close_client_sock()
|
||||
return
|
||||
try:
|
||||
data = self.klippy_sock.recv(4096)
|
||||
except socket.error as e:
|
||||
# If bad file descriptor allow connection to be
|
||||
# closed by the data check
|
||||
if e.errno == errno.EBADF:
|
||||
data = b''
|
||||
else:
|
||||
return
|
||||
if data == b'':
|
||||
# Socket Closed
|
||||
self.close_client_sock()
|
||||
return
|
||||
commands = data.split(b'\x03')
|
||||
commands[0] = self.partial_data + commands[0]
|
||||
self.partial_data = commands.pop()
|
||||
for cmd in commands:
|
||||
try:
|
||||
decoded_cmd = json.loads(cmd)
|
||||
method = decoded_cmd.get('method')
|
||||
params = decoded_cmd.get('params', {})
|
||||
cb = self.remote_methods.get(method)
|
||||
if cb is not None:
|
||||
cb(**params)
|
||||
else:
|
||||
logging.info("Unknown command received %s" % cmd.decode())
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Error processing Klippy Host Response: %s"
|
||||
% (cmd.decode()))
|
||||
|
||||
def klippy_send(self, data):
|
||||
# TODO: need a mutex or lock to make sure that multiple co-routines
|
||||
# do not attempt to send
|
||||
if not self.is_klippy_connected:
|
||||
return False
|
||||
retries = 10
|
||||
data = json.dumps(data).encode() + b"\x03"
|
||||
while data:
|
||||
try:
|
||||
sent = self.klippy_sock.send(data)
|
||||
except socket.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE \
|
||||
or not retries:
|
||||
sent = 0
|
||||
else:
|
||||
# XXX - Should pause for 1ms here
|
||||
retries -= 1
|
||||
continue
|
||||
retries = 10
|
||||
if sent > 0:
|
||||
data = data[sent:]
|
||||
else:
|
||||
logging.info("Error sending client data, closing socket")
|
||||
self.close_client_sock()
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _initialize(self):
|
||||
await self._request_endpoints()
|
||||
if not self.server_configured:
|
||||
await self._request_config()
|
||||
if not self.is_klippy_ready:
|
||||
await self._request_ready()
|
||||
if self.is_klippy_ready and self.server_configured:
|
||||
# Make sure we have all registered endpoints
|
||||
await self._request_endpoints()
|
||||
self.init_cb.stop()
|
||||
|
||||
async def _request_endpoints(self):
|
||||
request = self.make_request("list_endpoints", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
endpoints = result.get('hooks', {})
|
||||
static_paths = result.get('static_paths', {})
|
||||
for ep in endpoints:
|
||||
self.moonraker_app.register_remote_handler(ep)
|
||||
for sp in static_paths:
|
||||
self.moonraker_app.register_static_file_handler(
|
||||
sp['resource_id'], sp['file_path'])
|
||||
|
||||
async def _request_config(self):
|
||||
request = self.make_request(
|
||||
"moonraker/get_configuration", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
self._load_config(result)
|
||||
self.server_configured = True
|
||||
else:
|
||||
logging.info(
|
||||
"Error receiving configuration. This indicates a "
|
||||
"potential configuration issue in printer.cfg. Please check "
|
||||
"klippy.log for more information")
|
||||
|
||||
async def _request_ready(self):
|
||||
request = self.make_request("info", "GET", {})
|
||||
result = await request.wait()
|
||||
if not isinstance(result, ServerError):
|
||||
is_ready = result.get("is_ready", False)
|
||||
if is_ready:
|
||||
self._set_klippy_ready()
|
||||
else:
|
||||
msg = result.get("message", "Klippy Not Ready")
|
||||
logging.info(msg)
|
||||
else:
|
||||
logging.info(
|
||||
"Klippy Info request error. This indicates a that Klippy "
|
||||
"may have experienced an error during startup. Please check "
|
||||
"klippy.log for more information")
|
||||
|
||||
def _load_config(self, config):
|
||||
self.request_timeout = config.get(
|
||||
'request_timeout', self.request_timeout)
|
||||
self.long_running_gcodes = config.get(
|
||||
'long_running_gcodes', self.long_running_gcodes)
|
||||
self.long_running_requests = config.get(
|
||||
'long_running_requests', self.long_running_requests)
|
||||
self.moonraker_app.load_config(config)
|
||||
# load config for core plugins
|
||||
for plugin_name in CORE_PLUGINS:
|
||||
plugin = self.plugins[plugin_name]
|
||||
if hasattr(plugin, "load_config"):
|
||||
plugin.load_config(config)
|
||||
# Load and apply optional plugin Configuration
|
||||
plugin_cfgs = {name[7:]: cfg for name, cfg in config.items()
|
||||
if name.startswith("plugin_")}
|
||||
for name, cfg in plugin_cfgs.items():
|
||||
plugin = self.plugins.get(name)
|
||||
if plugin is None:
|
||||
plugin = self.load_plugin(name, None)
|
||||
if hasattr(plugin, "load_config"):
|
||||
plugin.load_config(cfg)
|
||||
# Remove plugins that are loaded but no longer configured
|
||||
valid_plugins = CORE_PLUGINS + list(plugin_cfgs.keys())
|
||||
self.io_loop.spawn_callback(self._prune_plugins, valid_plugins)
|
||||
|
||||
async def _prune_plugins(self, valid_plugins):
|
||||
for name, plugin in self.plugins.items():
|
||||
if name not in valid_plugins:
|
||||
if hasattr(plugin, "close"):
|
||||
await plugin.close()
|
||||
self.plugins.pop(name, None)
|
||||
|
||||
def _handle_klippy_response(self, request_id, response):
|
||||
req = self.pending_requests.pop(request_id, None)
|
||||
if req is not None:
|
||||
if isinstance(response, dict) and 'error' in response:
|
||||
response = ServerError(response['message'], 400)
|
||||
req.notify(response)
|
||||
else:
|
||||
logging.info("No request matching response: " + str(response))
|
||||
|
||||
def _set_klippy_ready(self):
|
||||
logging.info("Klippy ready")
|
||||
self.is_klippy_ready = True
|
||||
self.send_event("server:klippy_state_changed", "ready")
|
||||
|
||||
def _set_klippy_shutdown(self):
|
||||
logging.info("Klippy has shutdown")
|
||||
self.is_klippy_ready = False
|
||||
self.send_event("server:klippy_state_changed", "shutdown")
|
||||
|
||||
def _process_gcode_response(self, response):
|
||||
self.send_event("server:gcode_response", response)
|
||||
|
||||
def _process_status_update(self, status):
|
||||
self.send_event("server:status_update", status)
|
||||
|
||||
def make_request(self, path, method, args):
|
||||
timeout = self.long_running_requests.get(path, self.request_timeout)
|
||||
|
||||
if path == "gcode/script":
|
||||
script = args.get('script', "")
|
||||
base_gc = script.strip().split()[0].upper()
|
||||
timeout = self.long_running_gcodes.get(base_gc, timeout)
|
||||
|
||||
base_request = BaseRequest(path, method, args, timeout)
|
||||
self.pending_requests[base_request.id] = base_request
|
||||
ret = self.klippy_send(base_request.to_dict())
|
||||
if not ret:
|
||||
self.pending_requests.pop(base_request.id, None)
|
||||
base_request.notify(
|
||||
ServerError("Klippy Host not connected", 503))
|
||||
return base_request
|
||||
|
||||
async def _kill_server(self):
|
||||
# XXX - Currently this function is not used.
|
||||
# Should I expose functionality to shutdown
|
||||
# or restart the server, or simply remove this?
|
||||
logging.info(
|
||||
"Shutting Down Webserver")
|
||||
for plugin in self.plugins:
|
||||
if hasattr(plugin, "close"):
|
||||
await plugin.close()
|
||||
self.close_client_sock()
|
||||
self.close_server_sock()
|
||||
if self.server_running:
|
||||
self.server_running = False
|
||||
await self.moonraker_app.close()
|
||||
self.io_loop.stop()
|
||||
|
||||
def close_client_sock(self):
|
||||
self.is_klippy_ready = False
|
||||
self.server_configured = False
|
||||
self.init_cb.stop()
|
||||
if self.is_klippy_connected:
|
||||
self.is_klippy_connected = False
|
||||
logging.info("Klippy Connection Removed")
|
||||
try:
|
||||
self.io_loop.remove_handler(self.klippy_sock.fileno())
|
||||
self.klippy_sock.close()
|
||||
except socket.error:
|
||||
logging.exception("Error Closing Client Socket")
|
||||
self.send_event("server:klippy_state_changed", "disconnect")
|
||||
|
||||
def close_server_sock(self):
|
||||
try:
|
||||
self.remove_server_sock()
|
||||
self.klippy_server_sock.close()
|
||||
# XXX - remove server sock file (or use abstract?)
|
||||
except Exception:
|
||||
logging.exception("Error Closing Server Socket")
|
||||
|
||||
# Basic WebRequest class, easily converted to dict for json encoding
|
||||
class BaseRequest:
|
||||
def __init__(self, path, method, args, timeout=None):
|
||||
self.id = id(self)
|
||||
self.path = path
|
||||
self.method = method
|
||||
self.args = args
|
||||
self._timeout = timeout
|
||||
self._event = Event()
|
||||
self.response = None
|
||||
if timeout is not None:
|
||||
self._timeout = time.time() + timeout
|
||||
|
||||
async def wait(self):
|
||||
# Wait for klippy to process the request or until the timeout
|
||||
# has been reached.
|
||||
try:
|
||||
await self._event.wait(timeout=self._timeout)
|
||||
except TimeoutError:
|
||||
logging.info("Request '%s' Timed Out" %
|
||||
(self.method + " " + self.path))
|
||||
return ServerError("Klippy Request Timed Out", 500)
|
||||
return self.response
|
||||
|
||||
def notify(self, response):
|
||||
self.response = response
|
||||
self._event.set()
|
||||
|
||||
def to_dict(self):
|
||||
return {'id': self.id, 'path': self.path,
|
||||
'method': self.method, 'args': self.args}
|
||||
|
||||
def main():
|
||||
# Parse start arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Moonraker - Klipper API Server")
|
||||
parser.add_argument(
|
||||
"-a", "--address", default='0.0.0.0', metavar='<address>',
|
||||
help="host name or ip to bind to the Web Server")
|
||||
parser.add_argument(
|
||||
"-p", "--port", type=int, default=7125, metavar='<port>',
|
||||
help="port the Web Server will listen on")
|
||||
parser.add_argument(
|
||||
"-s", "--socketfile", default="/tmp/moonraker", metavar='<socketfile>',
|
||||
help="file name and location for the Unix Domain Socket")
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
parser.add_argument(
|
||||
"-k", "--apikey", default="~/.moonraker_api_key",
|
||||
metavar='<apikeyfile>', help="API Key file location")
|
||||
parser.add_argument(
|
||||
"-d", "--debug", action='store_true',
|
||||
help="Enable Debug Logging")
|
||||
cmd_line_args = parser.parse_args()
|
||||
|
||||
# Setup Logging
|
||||
log_file = os.path.normpath(os.path.expanduser(cmd_line_args.logfile))
|
||||
cmd_line_args.logfile = log_file
|
||||
root_logger = logging.getLogger()
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
log_file, when='midnight', backupCount=2)
|
||||
root_logger.addHandler(file_hdlr)
|
||||
if cmd_line_args.debug:
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
root_logger.setLevel(logging.INFO)
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
|
||||
file_hdlr.setFormatter(formatter)
|
||||
|
||||
if sys.version_info < (3, 7):
|
||||
msg = "Moonraker requires Python 3.7 or above. Detected Version: %s" \
|
||||
% (sys.version)
|
||||
logging.info(msg)
|
||||
print(msg)
|
||||
exit(1)
|
||||
|
||||
# Start IOLoop and Server
|
||||
io_loop = IOLoop.current()
|
||||
try:
|
||||
server = Server(cmd_line_args)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
return
|
||||
try:
|
||||
server.start()
|
||||
io_loop.start()
|
||||
except Exception:
|
||||
logging.exception("Server Running Error")
|
||||
io_loop.close(True)
|
||||
logging.info("Server Shutdown")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
import importlib
|
||||
import pathlib
|
||||
pkg_parent = pathlib.Path(__file__).parent.parent
|
||||
sys.path.pop(0)
|
||||
sys.path.insert(0, str(pkg_parent))
|
||||
svr = importlib.import_module(".server", "moonraker")
|
||||
svr.main(False) # type: ignore
|
||||
@@ -1,490 +0,0 @@
|
||||
# Enhanced gcode file management and analysis
|
||||
#
|
||||
# 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 sys
|
||||
import shutil
|
||||
import time
|
||||
import logging
|
||||
import json
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.locks import Lock
|
||||
|
||||
VALID_GCODE_EXTS = ['gcode', 'g', 'gco']
|
||||
FULL_ACCESS_ROOTS = ["gcodes", "config"]
|
||||
METADATA_SCRIPT = os.path.join(
|
||||
os.path.dirname(__file__), "../../scripts/extract_metadata.py")
|
||||
|
||||
class FileManager:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.file_paths = {}
|
||||
self.file_lists = {}
|
||||
self.gcode_metadata = {}
|
||||
self.metadata_lock = Lock()
|
||||
self.server.register_endpoint(
|
||||
"/server/files/list", "file_list", ['GET'],
|
||||
self._handle_filelist_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/metadata", "file_metadata", ['GET'],
|
||||
self._handle_metadata_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/directory", "directory", ['GET', 'POST', 'DELETE'],
|
||||
self._handle_directory_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/move", "file_move", ['POST'],
|
||||
self._handle_file_move_copy)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/copy", "file_copy", ['POST'],
|
||||
self._handle_file_move_copy)
|
||||
# Register APIs to handle file uploads
|
||||
self.server.register_upload_handler("/server/files/upload")
|
||||
self.server.register_upload_handler("/api/files/local")
|
||||
|
||||
def load_config(self, config):
|
||||
# Gcode Files
|
||||
sd = config.get('sd_path', None)
|
||||
if sd is not None:
|
||||
sd = os.path.normpath(os.path.expanduser(sd))
|
||||
if sd != self.file_paths.get('gcodes', ""):
|
||||
self.file_paths['gcodes'] = sd
|
||||
self.server.register_static_file_handler(
|
||||
'/server/files/gcodes/', sd, can_delete=True,
|
||||
op_check_cb=self._handle_operation_check)
|
||||
try:
|
||||
self._update_file_list()
|
||||
except Exception:
|
||||
logging.exception("Unable to initialize gcode file list")
|
||||
# Configuration files in the optional config path
|
||||
cfg_path = config.get('printer_config_path', None)
|
||||
if cfg_path is not None:
|
||||
cfg_path = os.path.normpath(os.path.expanduser(cfg_path))
|
||||
if cfg_path != self.file_paths.get('config', ""):
|
||||
self.file_paths['config'] = cfg_path
|
||||
self.server.register_static_file_handler(
|
||||
"/server/files/config/", cfg_path,
|
||||
can_delete=True)
|
||||
try:
|
||||
self._update_file_list(base='config')
|
||||
except Exception:
|
||||
logging.exception("Unable to initialize config file list")
|
||||
# Register path for example configs
|
||||
klipper_path = config.get('klipper_path', None)
|
||||
if klipper_path is not None:
|
||||
example_cfg_path = os.path.join(klipper_path, "config")
|
||||
if example_cfg_path != self.file_paths.get("config_examples", ""):
|
||||
self.file_paths['config_examples'] = example_cfg_path
|
||||
self.server.register_static_file_handler(
|
||||
"/server/files/config_examples/", example_cfg_path)
|
||||
try:
|
||||
self._update_file_list(base='config_examples')
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Unable to initialize config_examples file list")
|
||||
|
||||
def get_sd_directory(self):
|
||||
return self.file_paths.get('gcodes', "")
|
||||
|
||||
async def _handle_filelist_request(self, path, method, args):
|
||||
root = args.get('root', "gcodes")
|
||||
return self.get_file_list(format_list=True, base=root)
|
||||
|
||||
async def _handle_metadata_request(self, path, method, args):
|
||||
requested_file = args.get('filename')
|
||||
metadata = self.gcode_metadata.get(requested_file)
|
||||
if metadata is None:
|
||||
raise self.server.error(
|
||||
"Metadata not available for <%s>" % (requested_file), 404)
|
||||
metadata['filename'] = requested_file
|
||||
return metadata
|
||||
|
||||
async def _handle_directory_request(self, path, method, args):
|
||||
directory = args.get('path', "gcodes")
|
||||
base, url_path, dir_path = self._convert_path(directory)
|
||||
method = method.upper()
|
||||
if method == 'GET':
|
||||
# Get list of files and subdirectories for this target
|
||||
return self._list_directory(dir_path)
|
||||
elif method == 'POST' and base in FULL_ACCESS_ROOTS:
|
||||
# Create a new directory
|
||||
try:
|
||||
os.mkdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed(url_path, "add_directory", base)
|
||||
elif method == 'DELETE' and base in FULL_ACCESS_ROOTS:
|
||||
# Remove a directory
|
||||
if directory.strip("/") == base:
|
||||
raise self.server.error(
|
||||
"Cannot delete root directory")
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
"Directory does not exist (%s)" % (directory))
|
||||
force = args.get('force', False)
|
||||
if isinstance(force, str):
|
||||
force = force.lower() == "true"
|
||||
if force:
|
||||
# Make sure that the directory does not contain a file
|
||||
# loaded by the virtual_sdcard
|
||||
await self._handle_operation_check(dir_path)
|
||||
shutil.rmtree(dir_path)
|
||||
else:
|
||||
try:
|
||||
os.rmdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed(url_path, "delete_directory", base)
|
||||
else:
|
||||
raise self.server.error("Operation Not Supported", 405)
|
||||
return "ok"
|
||||
|
||||
async def _handle_operation_check(self, requested_path):
|
||||
# Get virtual_sdcard status
|
||||
request = self.server.make_request(
|
||||
"objects/status", 'GET', {'virtual_sdcard': []})
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise result
|
||||
vsd = result.get('virtual_sdcard', {})
|
||||
loaded_file = vsd.get('filename', "")
|
||||
gc_path = self.file_paths.get('gcodes', "")
|
||||
full_path = os.path.join(gc_path, loaded_file)
|
||||
if os.path.isdir(requested_path):
|
||||
# Check to see of the loaded file is in the reques
|
||||
if full_path.startswith(requested_path):
|
||||
raise self.server.error("File currently in use", 403)
|
||||
elif full_path == requested_path:
|
||||
raise self.server.error("File currently in use", 403)
|
||||
ongoing = vsd.get('total_duration', 0.) > 0.
|
||||
return ongoing
|
||||
|
||||
def _convert_path(self, url_path):
|
||||
parts = url_path.strip("/").split("/")
|
||||
if not parts:
|
||||
raise self.server.error("Invalid path: " % (url_path))
|
||||
base = parts[0]
|
||||
if base not in self.file_paths:
|
||||
raise self.server.error("Invalid base path (%s)" % (base))
|
||||
root_path = local_path = self.file_paths[base]
|
||||
url_path = ""
|
||||
if len(parts) > 1:
|
||||
url_path = "/".join(parts[1:])
|
||||
local_path = os.path.join(root_path, url_path)
|
||||
return base, url_path, local_path
|
||||
|
||||
async def _handle_file_move_copy(self, path, method, args):
|
||||
source = args.get("source")
|
||||
destination = args.get("dest")
|
||||
if source is None:
|
||||
raise self.server.error("File move/copy request issing source")
|
||||
if destination is None:
|
||||
raise self.server.error(
|
||||
"File move/copy request missing destination")
|
||||
source_base, src_url_path, source_path = self._convert_path(source)
|
||||
dest_base, dst_url_path, dest_path = self._convert_path(destination)
|
||||
if dest_base not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
"Destination path is read-only: %s" % (dest_base))
|
||||
if not os.path.exists(source_path):
|
||||
raise self.server.error("File %s does not exist" % (source_path))
|
||||
# make sure the destination is not in use
|
||||
if os.path.exists(dest_path):
|
||||
await self._handle_operation_check(dest_path)
|
||||
action = ""
|
||||
if path == "/server/files/move":
|
||||
if source_base not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
"Source path is read-only, cannot move: %s"
|
||||
% (source_base))
|
||||
# if moving the file, make sure the source is not in use
|
||||
await self._handle_operation_check(source_path)
|
||||
try:
|
||||
shutil.move(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
action = "file_move"
|
||||
elif path == "/server/files/copy":
|
||||
try:
|
||||
if os.path.isdir(source_path):
|
||||
shutil.copytree(source_path, dest_path)
|
||||
else:
|
||||
shutil.copy2(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
action = "file_copy"
|
||||
self.notify_filelist_changed(
|
||||
dst_url_path, action, dest_base,
|
||||
{'prev_file': src_url_path, 'prev_root': source_base})
|
||||
return "ok"
|
||||
|
||||
def _list_directory(self, path):
|
||||
if not os.path.isdir(path):
|
||||
raise self.server.error(
|
||||
"Directory does not exist (%s)" % (path))
|
||||
flist = {'dirs': [], 'files': []}
|
||||
for fname in os.listdir(path):
|
||||
full_path = os.path.join(path, fname)
|
||||
modified = time.ctime(os.path.getmtime(full_path))
|
||||
if os.path.isdir(full_path):
|
||||
flist['dirs'].append({
|
||||
'dirname': fname,
|
||||
'modified': modified
|
||||
})
|
||||
elif os.path.isfile(full_path):
|
||||
size = os.path.getsize(full_path)
|
||||
flist['files'].append(
|
||||
{'filename': fname,
|
||||
'modified': modified,
|
||||
'size': size})
|
||||
return flist
|
||||
|
||||
def _shell_proc_callback(self, result):
|
||||
try:
|
||||
proc_resp = json.loads(result.strip())
|
||||
except Exception:
|
||||
logging.exception("file_manager: unable to load metadata")
|
||||
logging.debug(result)
|
||||
return
|
||||
proc_log = proc_resp.get('log', [])
|
||||
for log_msg in proc_log:
|
||||
logging.info(log_msg)
|
||||
file_path = proc_resp.pop('file', None)
|
||||
if file_path is not None:
|
||||
self.gcode_metadata[file_path] = proc_resp.get('metadata')
|
||||
|
||||
async def _update_metadata(self):
|
||||
async with self.metadata_lock:
|
||||
exisiting_data = {}
|
||||
update_list = []
|
||||
gc_files = dict(self.file_lists.get('gcodes', {}))
|
||||
gc_path = self.file_paths.get('gcodes', "")
|
||||
for fname, fdata in gc_files.items():
|
||||
mdata = self.gcode_metadata.get(fname, {})
|
||||
if mdata.get('size', "") == fdata.get('size') \
|
||||
and mdata.get('modified', "") == fdata.get('modified'):
|
||||
# file metadata has already been extracted
|
||||
exisiting_data[fname] = mdata
|
||||
else:
|
||||
update_list.append(fname)
|
||||
self.gcode_metadata = exisiting_data
|
||||
for fname in update_list:
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
gc_path, "-f", "'" + fname + "'"])
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(
|
||||
cmd, self._shell_proc_callback)
|
||||
try:
|
||||
await scmd.run(timeout=4.)
|
||||
except Exception:
|
||||
logging.exception("Error running extract_metadata.py")
|
||||
|
||||
def _update_file_list(self, base='gcodes'):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
path = self.file_paths.get(base, None)
|
||||
if path is None:
|
||||
msg = "No known path for root: %s" % (base)
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
elif not os.path.isdir(path):
|
||||
msg = "Cannot generate file list for root: %s" % (base)
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info("Updating File List <%s>..." % (base))
|
||||
new_list = {}
|
||||
for root, dirs, files in os.walk(path, followlinks=True):
|
||||
for name in files:
|
||||
ext = name[name.rfind('.')+1:]
|
||||
if base == 'gcodes' and ext not in VALID_GCODE_EXTS:
|
||||
continue
|
||||
full_path = os.path.join(root, name)
|
||||
r_path = full_path[len(path) + 1:]
|
||||
size = os.path.getsize(full_path)
|
||||
modified = time.ctime(os.path.getmtime(full_path))
|
||||
new_list[r_path] = {'size': size, 'modified': modified}
|
||||
self.file_lists[base] = new_list
|
||||
if base == 'gcodes':
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(self._update_metadata)
|
||||
return dict(new_list)
|
||||
|
||||
async def process_file_upload(self, request):
|
||||
# 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("Invalid root request: %s" % (root))
|
||||
return result
|
||||
|
||||
async def _do_gcode_upload(self, request):
|
||||
start_print = print_ongoing = False
|
||||
base_path = self.file_paths.get("gcodes", "")
|
||||
if not base_path:
|
||||
raise self.server.error("Gcodes root not available")
|
||||
start_print = self._get_argument(request, 'print', "false") == "true"
|
||||
upload = self._get_upload_info(request, base_path)
|
||||
# Verify that the operation can be done if attempting to upload a gcode
|
||||
try:
|
||||
print_ongoing = await self._handle_operation_check(
|
||||
upload['full_path'])
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise self.server.error(
|
||||
"File is loaded, upload not permitted", 403)
|
||||
else:
|
||||
# Couldn't reach Klippy, so it should be safe
|
||||
# to permit the upload but not start
|
||||
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)
|
||||
if start_print:
|
||||
# Make a Klippy Request to "Start Print"
|
||||
gcode_apis = self.server.lookup_plugin('gcode_apis')
|
||||
try:
|
||||
await gcode_apis.gcode_start_print(
|
||||
request.path, 'POST', {'filename': upload['filename']})
|
||||
except self.server.error:
|
||||
# Attempt to start print failed
|
||||
start_print = False
|
||||
self.notify_filelist_changed(upload['filename'], 'added', "gcodes")
|
||||
return {'result': upload['filename'], 'print_started': start_print}
|
||||
|
||||
def _do_standard_upload(self, request, root):
|
||||
path = self.file_paths.get(root, None)
|
||||
if path is None:
|
||||
raise self.server.error("Unknown root path: %s" % (root))
|
||||
upload = self._get_upload_info(request, path)
|
||||
self._write_file(upload)
|
||||
self.notify_filelist_changed(upload['filename'], 'added', 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, base_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(base_path):
|
||||
filename = os.path.basename(base_path)
|
||||
full_path = base_path
|
||||
dir_path = ""
|
||||
else:
|
||||
filename = "_".join(upload['filename'].strip().split()).lstrip("/")
|
||||
if dir_path:
|
||||
filename = os.path.join(dir_path, filename)
|
||||
full_path = os.path.normpath(os.path.join(base_path, filename))
|
||||
# Validate the path. Don't allow uploads to a parent of the root
|
||||
if not full_path.startswith(base_path):
|
||||
raise self.server.error(
|
||||
"Cannot write to path: %s" % (full_path))
|
||||
return {
|
||||
'filename': filename,
|
||||
'body': upload['body'],
|
||||
'dir_path': dir_path,
|
||||
'full_path': full_path}
|
||||
|
||||
def _write_file(self, upload):
|
||||
try:
|
||||
if upload['dir_path']:
|
||||
os.makedirs(os.path.dirname(upload['full_path']), exist_ok=True)
|
||||
with open(upload['full_path'], 'wb') as fh:
|
||||
fh.write(upload['body'])
|
||||
except Exception:
|
||||
raise self.server.error("Unable to save file", 500)
|
||||
|
||||
def get_file_list(self, format_list=False, base='gcodes'):
|
||||
try:
|
||||
filelist = self._update_file_list(base)
|
||||
except Exception:
|
||||
msg = "Unable to update file list"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
if format_list:
|
||||
flist = []
|
||||
for fname in sorted(filelist, key=str.lower):
|
||||
fdict = {'filename': fname}
|
||||
fdict.update(filelist[fname])
|
||||
flist.append(fdict)
|
||||
return flist
|
||||
return filelist
|
||||
|
||||
def get_file_metadata(self, filename):
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
|
||||
# Remove "gcodes" of its added. It is valid for a request to
|
||||
# include to the root or assume the root is gcodes
|
||||
if filename.startswith('gcodes/'):
|
||||
filename = filename[7:]
|
||||
|
||||
flist = self.get_file_list()
|
||||
return self.gcode_metadata.get(filename, flist.get(filename, {}))
|
||||
|
||||
def list_dir(self, directory, simple_format=False):
|
||||
# List a directory relative to its root. Currently the only
|
||||
# Supported root is "gcodes"
|
||||
if directory[0] == "/":
|
||||
directory = directory[1:]
|
||||
parts = directory.split("/", 1)
|
||||
root = parts[0]
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(
|
||||
"Invalid Directory Request: %s" % (directory))
|
||||
path = self.file_paths[root]
|
||||
if len(parts) == 1:
|
||||
dir_path = path
|
||||
else:
|
||||
dir_path = os.path.join(path, parts[1])
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
"Directory does not exist (%s)" % (dir_path))
|
||||
flist = self._list_directory(dir_path)
|
||||
if simple_format:
|
||||
simple_list = []
|
||||
for dirobj in flist['dirs']:
|
||||
simple_list.append("*" + dirobj['dirname'])
|
||||
for fileobj in flist['files']:
|
||||
fname = fileobj['filename']
|
||||
ext = fname[fname.rfind('.')+1:]
|
||||
if root == "gcodes" and ext in VALID_GCODE_EXTS:
|
||||
simple_list.append(fname)
|
||||
return simple_list
|
||||
return flist
|
||||
|
||||
def delete_file(self, path):
|
||||
parts = path.split("/", 1)
|
||||
root = parts[0]
|
||||
if root not in self.file_paths or len(parts) != 2:
|
||||
raise self.server.error("Invalid file path: %s" % (path))
|
||||
root_path = self.file_paths[root]
|
||||
full_path = os.path.join(root_path, parts[1])
|
||||
if not os.path.isfile(full_path):
|
||||
raise self.server.error("Invalid file path: %s" % (path))
|
||||
os.remove(full_path)
|
||||
|
||||
def notify_filelist_changed(self, fname, action, base, params={}):
|
||||
self._update_file_list(base)
|
||||
result = {'filename': fname, 'action': action, 'root': base}
|
||||
if params:
|
||||
result.update(params)
|
||||
self.server.send_event("file_manager:filelist_changed", result)
|
||||
|
||||
def load_plugin(server):
|
||||
return FileManager(server)
|
||||
@@ -1,67 +0,0 @@
|
||||
# Map HTTP/Websocket APIs for specific gcode tasks
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
GCODE_ENDPOINT = "gcode/script"
|
||||
|
||||
class GCodeAPIs:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
|
||||
# Register GCode Endpoints
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/pause", "printer_print_pause", ['POST'],
|
||||
self.gcode_pause)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", "printer_print_resume", ['POST'],
|
||||
self.gcode_resume)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", "printer_print_cancel", ['POST'],
|
||||
self.gcode_cancel)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", "printer_print_start", ['POST'],
|
||||
self.gcode_start_print)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", "printer_restart", ['POST'],
|
||||
self.gcode_restart)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", "printer_firmware_restart", ['POST'],
|
||||
self.gcode_firmware_restart)
|
||||
|
||||
async def _send_gcode(self, script):
|
||||
args = {'script': script}
|
||||
request = self.server.make_request(
|
||||
GCODE_ENDPOINT, 'POST', args)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise result
|
||||
return result
|
||||
|
||||
async def gcode_pause(self, path, method, args):
|
||||
return await self._send_gcode("PAUSE")
|
||||
|
||||
async def gcode_resume(self, path, method, args):
|
||||
return await self._send_gcode("RESUME")
|
||||
|
||||
async def gcode_cancel(self, path, method, args):
|
||||
return await self._send_gcode("CANCEL_PRINT")
|
||||
|
||||
async def gcode_start_print(self, path, method, args):
|
||||
filename = args.get('filename')
|
||||
# XXX - validate that file is on disk
|
||||
|
||||
if filename[0] != '/':
|
||||
filename = '/' + filename
|
||||
script = "M23 " + filename + "\nM24"
|
||||
return await self._send_gcode(script)
|
||||
|
||||
async def gcode_restart(self, path, method, args):
|
||||
return await self._send_gcode("RESTART")
|
||||
|
||||
async def gcode_firmware_restart(self, path, method, args):
|
||||
return await self._send_gcode("FIRMWARE_RESTART")
|
||||
|
||||
def load_plugin(server):
|
||||
return GCodeAPIs(server)
|
||||
@@ -1,34 +0,0 @@
|
||||
# Machine manipulation request handlers
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
|
||||
class Machine:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.server.register_endpoint(
|
||||
"/machine/reboot", "machine_reboot", ['POST'],
|
||||
self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/shutdown", "machine_shutdown", ['POST'],
|
||||
self._handle_machine_request)
|
||||
|
||||
async def _handle_machine_request(self, path, method, args):
|
||||
if path == "/machine/shutdown":
|
||||
cmd = "sudo shutdown now"
|
||||
elif path == "/machine/reboot":
|
||||
cmd = "sudo reboot now"
|
||||
else:
|
||||
raise self.server.error("Unsupported machine request")
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
try:
|
||||
await scmd.run(timeout=2., verbose=False)
|
||||
except Exception:
|
||||
logging.exception("Error running cmd '%s'" % (cmd))
|
||||
return "ok"
|
||||
|
||||
def load_plugin(server):
|
||||
return Machine(server)
|
||||
@@ -1,685 +0,0 @@
|
||||
# PanelDue LCD display support
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import serial
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import tempfile
|
||||
from utils import ServerError
|
||||
from tornado import gen, netutil
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.locks import Lock
|
||||
|
||||
MIN_EST_TIME = 10.
|
||||
|
||||
class PanelDueError(ServerError):
|
||||
pass
|
||||
|
||||
class SerialConnection:
|
||||
def __init__(self, paneldue):
|
||||
self.ioloop = IOLoop.current()
|
||||
self.paneldue = paneldue
|
||||
self.port = ""
|
||||
self.baud = 57200
|
||||
self.sendlock = Lock()
|
||||
self.partial_input = b""
|
||||
self.ser = self.fd = None
|
||||
self.connected = False
|
||||
|
||||
def load_config(self, config):
|
||||
port = config.get('serial', None)
|
||||
baud = int(config.get('baud', 57200))
|
||||
if port is None:
|
||||
logging.info("No serial port specified, cannot connect")
|
||||
return
|
||||
if port != self.port or baud != self.baud or \
|
||||
not self.connected:
|
||||
self.disconnect()
|
||||
self.port = port
|
||||
self.baud = baud
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
|
||||
def disconnect(self):
|
||||
if self.connected:
|
||||
if self.fd is not None:
|
||||
self.ioloop.remove_handler(self.fd)
|
||||
self.fd = None
|
||||
self.connected = False
|
||||
self.ser.close()
|
||||
self.ser = None
|
||||
logging.info("PanelDue Disconnected")
|
||||
|
||||
async def _connect(self):
|
||||
start_time = connect_time = time.time()
|
||||
while not self.connected:
|
||||
if connect_time > start_time + 30.:
|
||||
logging.info("Unable to connect, aborting")
|
||||
break
|
||||
logging.info("Attempting to connect to: %s" % (self.port))
|
||||
try:
|
||||
# XXX - sometimes the port cannot be exclusively locked, this
|
||||
# would likely be due to a restart where the serial port was
|
||||
# not correctly closed. Maybe don't use exclusive mode?
|
||||
self.ser = serial.Serial(
|
||||
self.port, self.baud, timeout=0, exclusive=True)
|
||||
except (OSError, IOError, serial.SerialException):
|
||||
logging.exception("Unable to open port: %s" % (self.port))
|
||||
await gen.sleep(2.)
|
||||
connect_time += time.time()
|
||||
continue
|
||||
self.fd = self.ser.fileno()
|
||||
os.set_blocking(self.fd, False)
|
||||
self.ioloop.add_handler(
|
||||
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
|
||||
self.connected = True
|
||||
logging.info("PanelDue Connected")
|
||||
|
||||
def _handle_incoming(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
logging.info("PanelDue Connection Error")
|
||||
self.disconnect()
|
||||
return
|
||||
# Process incoming data using same method as gcode.py
|
||||
try:
|
||||
data = os.read(fd, 4096)
|
||||
except os.error:
|
||||
return
|
||||
|
||||
if not data:
|
||||
# possibly an error, disconnect
|
||||
self.disconnect()
|
||||
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)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
"GCode Processing Error: " + line)
|
||||
self.paneldue.handle_gcode_response(
|
||||
"!! 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
|
||||
|
||||
|
||||
class PanelDue:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.ioloop = IOLoop.current()
|
||||
self.ser_conn = SerialConnection(self)
|
||||
self.file_manager = self.server.load_plugin('file_manager')
|
||||
self.kinematics = "none"
|
||||
self.machine_name = "Klipper"
|
||||
self.firmware_name = "Repetier | Klipper"
|
||||
self.last_message = None
|
||||
self.last_gcode_response = None
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state = {
|
||||
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'pause_resume': {}, 'fan': {}, 'display_status': {}}
|
||||
self.available_macros = {}
|
||||
self.non_trivial_keys = []
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
|
||||
# Register server events
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_state_changed", self.handle_klippy_state)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self.handle_status_update)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self.handle_gcode_response)
|
||||
|
||||
self.server.register_remote_method(
|
||||
"paneldue_beep", self.handle_paneldue_beep)
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# make a request to Klippy
|
||||
self.direct_gcodes = {
|
||||
'M20': self._run_paneldue_M20,
|
||||
'M30': self._run_paneldue_M30,
|
||||
'M36': self._run_paneldue_M36,
|
||||
'M408': self._run_paneldue_M408
|
||||
}
|
||||
|
||||
# These gcodes require special parsing or handling prior to being
|
||||
# sent via Klippy's "gcode/script" api command.
|
||||
self.special_gcodes = {
|
||||
'M0': lambda args: "CANCEL_PRINT",
|
||||
'M23': self._prepare_M23,
|
||||
'M24': lambda args: "RESUME",
|
||||
'M25': lambda args: "PAUSE",
|
||||
'M32': self._prepare_M32,
|
||||
'M98': self._prepare_M98,
|
||||
'M120': lambda args: "SAVE_GCODE_STATE STATE=PANELDUE",
|
||||
'M121': lambda args: "RESTORE_GCODE_STATE STATE=PANELDUE",
|
||||
'M290': self._prepare_M290,
|
||||
'M999': lambda args: "FIRMWARE_RESTART"
|
||||
}
|
||||
|
||||
def load_config(self, config):
|
||||
self.ser_conn.load_config(config)
|
||||
self.machine_name = config.get('machine_name', self.machine_name)
|
||||
macros = config.get('macros', None)
|
||||
if macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
macros = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
else:
|
||||
self.available_macros = {}
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
|
||||
self.ioloop.spawn_callback(self.write_response, {'status': 'C'})
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
async def _klippy_request(self, command, method='GET', args={}):
|
||||
request = self.server.make_request(command, method, args)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
raise PanelDueError(str(result))
|
||||
return result
|
||||
|
||||
async def handle_klippy_state(self, state):
|
||||
if state == "ready":
|
||||
await self._process_klippy_ready()
|
||||
elif state == "shutdown":
|
||||
await self._process_klippy_shutdown()
|
||||
elif state == "disconnect":
|
||||
await self._process_klippy_disconnect()
|
||||
|
||||
async def _process_klippy_ready(self):
|
||||
# Request "info" and "configfile" status
|
||||
retries = 10
|
||||
while retries:
|
||||
try:
|
||||
printer_info = await self._klippy_request("info")
|
||||
cfg_status = await self._klippy_request(
|
||||
"objects/status", args={'configfile': []})
|
||||
except PanelDueError:
|
||||
logging.exception("PanelDue initialization request failed")
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise
|
||||
await gen.sleep(1.)
|
||||
continue
|
||||
break
|
||||
|
||||
self.firmware_name = "Repetier | Klipper " + printer_info['version']
|
||||
config = cfg_status.get('configfile', {}).get('config', {})
|
||||
printer_cfg = config.get('printer', {})
|
||||
self.kinematics = printer_cfg.get('kinematics', "none")
|
||||
|
||||
logging.info(
|
||||
"PanelDue Config Received:\n"
|
||||
"Firmware Name: %s\n"
|
||||
"Kinematics: %s\n"
|
||||
"Printer Config: %s\n"
|
||||
% (self.firmware_name, self.kinematics, str(config)))
|
||||
|
||||
# Initalize printer state and make subscription request
|
||||
self.printer_state = {
|
||||
'gcode': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'pause_resume': {}, 'fan': {}, 'display_status': {}}
|
||||
sub_args = {'gcode': [], 'toolhead': []}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
for cfg in config:
|
||||
if cfg.startswith("extruder"):
|
||||
self.extruder_count += 1
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = []
|
||||
elif cfg == "heater_bed":
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = []
|
||||
elif cfg in self.printer_state:
|
||||
sub_args[cfg] = []
|
||||
try:
|
||||
await self._klippy_request(
|
||||
"objects/subscription", method='POST', args=sub_args)
|
||||
except PanelDueError:
|
||||
logging.exception("Unable to complete subscription request")
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
async 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
|
||||
|
||||
async def handle_status_update(self, status):
|
||||
self.printer_state.update(status)
|
||||
|
||||
def handle_paneldue_beep(self, frequency, duration):
|
||||
duration = int(duration * 1000.)
|
||||
self.ioloop.spawn_callback(
|
||||
self.write_response,
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
async def process_line(self, line):
|
||||
# If we find M112 in the line then skip verification
|
||||
if "M112" in line.upper():
|
||||
await self._klippy_request("emergency_stop", method='POST')
|
||||
return
|
||||
|
||||
# Get line number
|
||||
line_index = line.find(' ')
|
||||
try:
|
||||
line_no = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
|
||||
# Verify checksum
|
||||
cs_index = line.rfind('*')
|
||||
try:
|
||||
checksum = int(line[cs_index+1:])
|
||||
except Exception:
|
||||
# Invalid checksum, do not process
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg = " Line Number: %d" % line_no
|
||||
logging.exception("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
# Checksum is calculated by XORing every byte in the line other
|
||||
# than the checksum itself
|
||||
calculated_cs = 0
|
||||
for c in line[:cs_index]:
|
||||
calculated_cs ^= ord(c)
|
||||
if calculated_cs & 0xFF != checksum:
|
||||
msg = "!! Invalid Checksum"
|
||||
if line_no is not None:
|
||||
msg = " Line Number: %d" % line_no
|
||||
logging.info("PanelDue: " + msg)
|
||||
raise PanelDueError(msg)
|
||||
|
||||
await self._run_gcode(line[line_index+1:cs_index])
|
||||
|
||||
async def _run_gcode(self, script):
|
||||
# Execute the gcode. Check for special RRF gcodes that
|
||||
# require special handling
|
||||
parts = script.split()
|
||||
cmd = parts[0].strip()
|
||||
|
||||
# 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"
|
||||
try:
|
||||
val = int(p[1:].strip()) if arg in "sr" else p[1:].strip()
|
||||
except Exception:
|
||||
msg = "paneldue: Error parsing direct gcode %s" % (script)
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
return
|
||||
params["arg_" + arg] = val
|
||||
func = self.direct_gcodes[cmd]
|
||||
await func(**params)
|
||||
return
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
if cmd in self.special_gcodes:
|
||||
func = self.special_gcodes[cmd]
|
||||
script = func(parts[1:])
|
||||
|
||||
try:
|
||||
args = {'script': script}
|
||||
await self._klippy_request(
|
||||
"gcode/script", method='POST', args=args)
|
||||
except PanelDueError:
|
||||
msg = "Error executing script %s" % script
|
||||
self.handle_gcode_response("!! " + msg)
|
||||
logging.exception(msg)
|
||||
|
||||
def _clean_filename(self, filename):
|
||||
# Remove drive number
|
||||
if filename.startswith("0:/"):
|
||||
filename = filename[3:]
|
||||
# Remove initial "gcodes" folder. This is necessary
|
||||
# due to the HACK in the paneldue_M20 gcode.
|
||||
if filename.startswith("gcodes/"):
|
||||
filename = filename[6:]
|
||||
elif filename.startswith("/gcodes/"):
|
||||
filename = filename[7:]
|
||||
# Start with a "/" so the gcode parser can correctly
|
||||
# handle files that begin with digits or special chars
|
||||
if filename[0] != "/":
|
||||
filename = "/" + filename
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "M23 " + filename
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
filename = self._clean_filename(args[0].strip())
|
||||
return "M23 " + filename + "\n" + "M24"
|
||||
|
||||
def _prepare_M98(self, args):
|
||||
macro = args[0][1:].strip()
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
cmd = self.available_macros.get(macro)
|
||||
if cmd is None:
|
||||
raise PanelDueError("Macro %s invalid" % (macro))
|
||||
return cmd
|
||||
|
||||
def _prepare_M290(self, args):
|
||||
# args should in in the format Z0.02
|
||||
offset = args[0][1:].strip()
|
||||
return "SET_GCODE_OFFSET Z_ADJUST=%s MOVE=1" % (offset)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
# moment we'll handle state changes and errors
|
||||
if "Klipper state" in response \
|
||||
or response.startswith('!!'):
|
||||
self.last_gcode_response = response
|
||||
else:
|
||||
for key in self.non_trivial_keys:
|
||||
if key in response:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
async def write_response(self, response):
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
await self.ser_conn.send(byte_resp.encode())
|
||||
|
||||
def _get_printer_status(self):
|
||||
# PanelDue States applicable to Klipper:
|
||||
# I = idle, P = printing from SD, S = stopped (shutdown),
|
||||
# C = starting up (not ready), A = paused, D = pausing,
|
||||
# B = busy
|
||||
if self.is_shutdown:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
is_active = printer_state['virtual_sdcard'].get('is_active', False)
|
||||
paused = printer_state['pause_resume'].get('is_paused', False)
|
||||
if paused:
|
||||
if is_active:
|
||||
return 'D'
|
||||
else:
|
||||
return 'A'
|
||||
|
||||
if is_active:
|
||||
return 'P'
|
||||
|
||||
if printer_state['gcode'].get('busy', False):
|
||||
return 'B'
|
||||
|
||||
return 'I'
|
||||
|
||||
async 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
|
||||
response['status'] = 'S' if self.is_shutdown else 'C'
|
||||
await self.write_response(response)
|
||||
return
|
||||
|
||||
# Send gcode responses
|
||||
if sequence is not None and self.last_gcode_response:
|
||||
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
|
||||
response['firmwareName'] = self.firmware_name
|
||||
response['numTools'] = self.extruder_count
|
||||
response['geometry'] = self.kinematics
|
||||
response['axes'] = 3
|
||||
|
||||
p_state = self.printer_state
|
||||
status = self._get_printer_status()
|
||||
response['status'] = status
|
||||
response['babystep'] = round(p_state['gcode'].get(
|
||||
'homing_zpos', 0.), 3)
|
||||
|
||||
# Current position
|
||||
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
|
||||
response['pos'] = [round(p, 2) for p in pos[:3]]
|
||||
homed_pos = p_state['toolhead'].get('homed_axes', "")
|
||||
response['homed'] = [int(a in homed_pos) for a in "xyz"]
|
||||
sfactor = round(p_state['gcode'].get('speed_factor', 1.) * 100, 2)
|
||||
response['sfactor'] = sfactor
|
||||
|
||||
# Print Progress Tracking
|
||||
sd_status = p_state['virtual_sdcard']
|
||||
fname = sd_status.get('filename', "")
|
||||
if fname:
|
||||
# We know a file has been loaded, initialize metadata
|
||||
if self.current_file != fname:
|
||||
self.current_file = fname
|
||||
self.file_metadata = self.file_manager.get_file_metadata(fname)
|
||||
progress = p_state['virtual_sdcard'].get('progress', 0)
|
||||
# progress and print tracking
|
||||
if progress:
|
||||
response['fraction_printed'] = round(progress, 3)
|
||||
est_time = self.file_metadata.get('estimated_time', 0)
|
||||
if est_time > MIN_EST_TIME:
|
||||
# file read estimate
|
||||
times_left = [int(est_time - est_time * progress)]
|
||||
# filament estimate
|
||||
est_total_fil = self.file_metadata.get('filament_total')
|
||||
if est_total_fil:
|
||||
cur_filament = sd_status.get('filament_used', 0.)
|
||||
fpct = min(1., cur_filament / est_total_fil)
|
||||
times_left.append(int(est_time - est_time * fpct))
|
||||
# object height estimate
|
||||
obj_height = self.file_metadata.get('object_height')
|
||||
if obj_height:
|
||||
cur_height = p_state['gcode'].get('move_zpos', 0.)
|
||||
hpct = min(1., cur_height / obj_height)
|
||||
times_left.append(int(est_time - est_time * hpct))
|
||||
else:
|
||||
# The estimated time is not in the metadata, however we
|
||||
# can still provide an estimate based on file progress
|
||||
duration = sd_status.get('print_duration', 0.)
|
||||
times_left = [int(duration / progress - duration)]
|
||||
response['timesLeft'] = times_left
|
||||
else:
|
||||
# clear filename and metadata
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
|
||||
fan_speed = p_state['fan'].get('speed')
|
||||
if fan_speed is not None:
|
||||
response['fanPercent'] = [round(fan_speed * 100, 1)]
|
||||
|
||||
if self.extruder_count > 0:
|
||||
extruder_name = p_state['toolhead'].get('extruder')
|
||||
if extruder_name is not None:
|
||||
tool = 0
|
||||
if extruder_name != "extruder":
|
||||
tool = int(extruder_name[-1])
|
||||
response['tool'] = tool
|
||||
|
||||
# Report Heater Status
|
||||
efactor = round(p_state['gcode'].get('extrude_factor', 1.) * 100., 2)
|
||||
|
||||
for name in self.heaters:
|
||||
temp = round(p_state[name].get('temperature', 0.0), 1)
|
||||
target = round(p_state[name].get('target', 0.0), 1)
|
||||
response.setdefault('heaters', []).append(temp)
|
||||
response.setdefault('active', []).append(target)
|
||||
response.setdefault('standby', []).append(target)
|
||||
response.setdefault('hstat', []).append(2 if target else 0)
|
||||
if name.startswith('extruder'):
|
||||
response.setdefault('efactor', []).append(efactor)
|
||||
response.setdefault('extr', []).append(round(pos[3], 2))
|
||||
|
||||
# Display message (via M117)
|
||||
msg = p_state['display_status'].get('message')
|
||||
if msg and msg != self.last_message:
|
||||
response['message'] = msg
|
||||
# reset the message so it only shows once. The paneldue
|
||||
# is strange about this, and displays it as a full screen
|
||||
# notification
|
||||
self.last_message = msg
|
||||
await self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
"PanelDue: Cannot process response type %d in M20"
|
||||
% (response_type))
|
||||
return
|
||||
path = arg_p
|
||||
|
||||
# Strip quotes if they exist
|
||||
path = path.strip('\"')
|
||||
|
||||
# Path should come in as "0:/macros, or 0:/<gcode_folder>". With
|
||||
# repetier compatibility enabled, the default folder is root,
|
||||
# ie. "0:/"
|
||||
if path.startswith("0:/"):
|
||||
path = path[2:]
|
||||
response = {'dir': path}
|
||||
response['files'] = []
|
||||
|
||||
if path == "/macros":
|
||||
response['files'] = list(self.available_macros.keys())
|
||||
else:
|
||||
# HACK: The PanelDue has a bug where it does not correctly detect
|
||||
# subdirectories if we return the root as "/". Moonraker can
|
||||
# support a "gcodes" directory, however we must choose between this
|
||||
# support or disabling RRF specific gcodes (this is done by
|
||||
# identifying as Repetier).
|
||||
# The workaround below converts both "/" and "/gcodes" paths to
|
||||
# "gcodes".
|
||||
if path == "/":
|
||||
response['dir'] = "/gcodes"
|
||||
path = "gcodes"
|
||||
elif path.startswith("/gcodes"):
|
||||
path = path[1:]
|
||||
|
||||
flist = self.file_manager.list_dir(path, simple_format=True)
|
||||
if flist:
|
||||
response['files'] = flist
|
||||
await self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p=None):
|
||||
# Delete a file. Clean up the file name and make sure
|
||||
# it is relative to the "gcodes" root.
|
||||
path = arg_p
|
||||
path = path.strip('\"')
|
||||
if path.startswith("0:/"):
|
||||
path = path[3:]
|
||||
elif path[0] == "/":
|
||||
path = path[1:]
|
||||
|
||||
if not path.startswith("gcodes/"):
|
||||
path = "gcodes/" + path
|
||||
self.file_manager.delete_file(path)
|
||||
|
||||
async def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
if filename is None:
|
||||
# PanelDue is requesting file information on a
|
||||
# currently printed file
|
||||
active = False
|
||||
if sd_status:
|
||||
filename = sd_status['filename']
|
||||
active = sd_status['is_active']
|
||||
if not filename or not active:
|
||||
# Either no file printing or no virtual_sdcard
|
||||
response['err'] = 1
|
||||
await 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 not filename.startswith("gcodes/"):
|
||||
filename = "gcodes/" + filename
|
||||
|
||||
metadata = self.file_manager.get_file_metadata(filename)
|
||||
if metadata:
|
||||
response['err'] = 0
|
||||
response['size'] = metadata['size']
|
||||
# workaround for PanelDue replacing the first "T" found
|
||||
response['lastModified'] = "T" + metadata['modified']
|
||||
slicer = metadata.get('slicer')
|
||||
if slicer is not None:
|
||||
response['generatedBy'] = slicer
|
||||
height = metadata.get('object_height')
|
||||
if height is not None:
|
||||
response['height'] = round(height, 2)
|
||||
layer_height = metadata.get('layer_height')
|
||||
if layer_height is not None:
|
||||
response['layerHeight'] = round(layer_height, 2)
|
||||
filament = metadata.get('filament_total')
|
||||
if filament is not None:
|
||||
response['filament'] = [round(filament, 1)]
|
||||
est_time = metadata.get('estimated_time')
|
||||
if est_time is not None:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
await self.write_response(response)
|
||||
|
||||
async def close(self):
|
||||
self.ser_conn.disconnect()
|
||||
|
||||
def load_plugin(server):
|
||||
return PanelDue(server)
|
||||
@@ -1,188 +0,0 @@
|
||||
# Raspberry Pi Power Control
|
||||
#
|
||||
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
import logging
|
||||
import os
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado import gen
|
||||
|
||||
class PrinterPower:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/devices", "power_devices", ['GET'],
|
||||
self._handle_list_devices)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/status", "power_status", ['GET'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/on", "power_on", ['POST'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/printer/power/off", "power_off", ['POST'],
|
||||
self._handle_power_request)
|
||||
|
||||
self.current_dev = None
|
||||
self.devices = {}
|
||||
|
||||
async def _handle_list_devices(self, path, method, args):
|
||||
output = {"devices": []}
|
||||
for dev in self.devices:
|
||||
output['devices'].append({
|
||||
"name": self.devices[dev]["name"],
|
||||
"id": dev
|
||||
})
|
||||
return output
|
||||
|
||||
async def _handle_power_request(self, path, method, args):
|
||||
if len(args) == 0:
|
||||
if path == "/printer/power/status":
|
||||
args = self.devices
|
||||
else:
|
||||
return "no_devices"
|
||||
|
||||
result = {}
|
||||
for dev in args:
|
||||
if dev not in self.devices:
|
||||
result[dev] = "device_not_found"
|
||||
continue
|
||||
|
||||
await GPIO.verify_pin(self.devices[dev]["pin"],
|
||||
self.devices[dev]["active_low"])
|
||||
if path == "/printer/power/on":
|
||||
GPIO.set_pin_value(self.devices[dev]["pin"], 1)
|
||||
elif path == "/printer/power/off":
|
||||
GPIO.set_pin_value(self.devices[dev]["pin"], 0)
|
||||
elif path != "/printer/power/status":
|
||||
raise self.server.error("Unsupported power request")
|
||||
|
||||
self.devices[dev]["status"] = GPIO.is_pin_on(
|
||||
self.devices[dev]["pin"])
|
||||
|
||||
result[dev] = self.devices[dev]["status"]
|
||||
return result
|
||||
|
||||
def load_config(self, config):
|
||||
if "devices" not in config:
|
||||
return
|
||||
|
||||
devices = config["devices"].split(',')
|
||||
logging.info("Power plugin loading devices: " + str(devices))
|
||||
|
||||
parsed_devices = {}
|
||||
for dev in devices:
|
||||
dev = dev.strip()
|
||||
pin = config.get(dev + "_pin", "")
|
||||
if not pin.isdigit():
|
||||
logging.info(
|
||||
"Power plugin: ERR %s does not have a pin defined" % (dev))
|
||||
continue
|
||||
|
||||
name = config.get(dev + "_name", dev)
|
||||
active_low = int(config.get(
|
||||
dev + "_active_low", "false").lower() == "true")
|
||||
parsed_devices[dev] = {
|
||||
"name": name,
|
||||
"pin": int(pin),
|
||||
"active_low": active_low,
|
||||
"status": None
|
||||
}
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(self.initialize_devices, parsed_devices)
|
||||
|
||||
async def initialize_devices(self, devices):
|
||||
for name, device in devices.items():
|
||||
try:
|
||||
logging.debug(
|
||||
"Attempting to configure pin GPIO%d"
|
||||
% (device["pin"]))
|
||||
await GPIO.setup_pin(device["pin"], device["active_low"])
|
||||
device["status"] = GPIO.is_pin_on(device["pin"])
|
||||
except Exception:
|
||||
logging.exception(
|
||||
"Power plugin: ERR Problem configuring the output pin for"
|
||||
" device %s. Removing device" % (name))
|
||||
self.devices.pop(name, None)
|
||||
continue
|
||||
self.devices[name] = device
|
||||
|
||||
class GPIO:
|
||||
gpio_root = "/sys/class/gpio"
|
||||
|
||||
@staticmethod
|
||||
def _set_gpio_option(gpio, option, value):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, "gpio%d" % (gpio), option),
|
||||
value
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_gpio_option(pin, option):
|
||||
return GPIO._read(
|
||||
os.path.join(GPIO.gpio_root, "gpio%d" % (pin), option)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _write(file, data):
|
||||
with open(file, 'w') as f:
|
||||
f.write(str(data))
|
||||
f.flush()
|
||||
|
||||
@staticmethod
|
||||
def _read(file):
|
||||
with open(file, 'r') as f:
|
||||
f.seek(0)
|
||||
return f.read().strip()
|
||||
|
||||
@staticmethod
|
||||
async def verify_pin(pin, active_low=1):
|
||||
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
|
||||
if not os.path.exists(gpiopath):
|
||||
logging.info("Re-intializing GPIO%d" % (pin))
|
||||
await GPIO.setup_pin(pin, active_low)
|
||||
return
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
|
||||
@staticmethod
|
||||
async def setup_pin(pin, active_low=1):
|
||||
pin = int(pin)
|
||||
active_low = 1 if active_low == 1 else 0
|
||||
|
||||
gpiopath = os.path.join(GPIO.gpio_root, "gpio%d" % (pin))
|
||||
if not os.path.exists(gpiopath):
|
||||
GPIO._write(
|
||||
os.path.join(GPIO.gpio_root, "export"),
|
||||
pin)
|
||||
logging.info("Waiting for GPIO%d to initialize" % (pin))
|
||||
while os.stat(os.path.join(
|
||||
GPIO.gpio_root, "gpio%d" % (pin),
|
||||
"active_low")).st_gid == 0:
|
||||
await gen.sleep(.1)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "active_low").strip() != str(active_low):
|
||||
GPIO._set_gpio_option(pin, "active_low", active_low)
|
||||
|
||||
if GPIO._get_gpio_option(pin, "direction").strip() != "out":
|
||||
GPIO._set_gpio_option(pin, "direction", "out")
|
||||
|
||||
|
||||
@staticmethod
|
||||
def is_pin_on(pin):
|
||||
return "on" if int(GPIO._get_gpio_option(pin, "value")) else "off"
|
||||
|
||||
@staticmethod
|
||||
def set_pin_value(pin, active):
|
||||
value = 1 if (active == 1) else 0
|
||||
GPIO._set_gpio_option(pin, "value", value)
|
||||
|
||||
|
||||
def load_plugin(server):
|
||||
return PrinterPower(server)
|
||||
@@ -1,88 +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=None):
|
||||
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""
|
||||
|
||||
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
|
||||
if b'\n' not in data:
|
||||
self.partial_output = data
|
||||
return
|
||||
elif data[-1] != b'\n':
|
||||
split = data.rfind(b'\n') + 1
|
||||
self.partial_output = data[split:]
|
||||
data = data[:split]
|
||||
try:
|
||||
self.output_cb(data)
|
||||
except Exception:
|
||||
logging.exception("Error writing command output")
|
||||
|
||||
async def run(self, timeout=2., verbose=True):
|
||||
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(
|
||||
"shell_command: Command {%s} failed" % (self.name))
|
||||
return
|
||||
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
|
||||
sleeptime = 0
|
||||
complete = False
|
||||
while sleeptime < timeout:
|
||||
await gen.sleep(.05)
|
||||
sleeptime += .05
|
||||
if proc.poll() is not None:
|
||||
complete = True
|
||||
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 = "Command {%s} finished" % (self.name)
|
||||
else:
|
||||
msg = "Command {%s} timed out" % (self.name)
|
||||
logging.info(msg)
|
||||
self.io_loop.remove_handler(fd)
|
||||
|
||||
class ShellCommandFactory:
|
||||
def build_shell_command(self, cmd, callback):
|
||||
return ShellCommand(cmd, callback)
|
||||
|
||||
def load_plugin(server):
|
||||
return ShellCommandFactory()
|
||||
@@ -1,102 +0,0 @@
|
||||
# Heater sensor temperature storage
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
|
||||
TEMPERATURE_UPDATE_MS = 1000
|
||||
TEMPERATURE_STORE_SIZE = 20 * 60
|
||||
|
||||
class TemperatureStore:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps = {}
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_state_changed", self._init_sensors)
|
||||
|
||||
# Register endpoint
|
||||
self.server.register_endpoint(
|
||||
"/server/temperature_store", "server_temperature_store", ['GET'],
|
||||
self._handle_temp_store_request)
|
||||
|
||||
async def _init_sensors(self, state):
|
||||
if state != "ready":
|
||||
return
|
||||
|
||||
# Fetch sensors
|
||||
request = self.server.make_request(
|
||||
"objects/status", 'GET', {'heaters': []})
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
logging.info("Error Configuring Sensors: %s" % (str(result)))
|
||||
return
|
||||
sensors = result.get("heaters", {}).get("available_sensors", [])
|
||||
|
||||
if sensors:
|
||||
# Add Subscription
|
||||
sub = {s: [] for s in sensors}
|
||||
request = self.server.make_request(
|
||||
"objects/subscription", 'POST', sub)
|
||||
result = await request.wait()
|
||||
if isinstance(result, self.server.error):
|
||||
logging.info("Error subscribing to sensors: %s" %(str(result)))
|
||||
return
|
||||
logging.info("Configuring available sensors: %s" % (str(sensors)))
|
||||
new_store = {}
|
||||
for sensor in sensors:
|
||||
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)}
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
if sensor not in self.temperature_store:
|
||||
del self.last_temps[sensor]
|
||||
self.temp_update_cb.start()
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
self.last_temps = {}
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _set_current_temps(self, data):
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
self.last_temps[sensor] = (
|
||||
round(data[sensor].get('temperature', 0.), 2),
|
||||
data[sensor].get('target', 0.))
|
||||
|
||||
|
||||
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)
|
||||
|
||||
async def _handle_temp_store_request(self, path, method, args):
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
store[name] = {k: list(v) for k, v in sensor.items()}
|
||||
return store
|
||||
|
||||
async def close(self):
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def load_plugin(server):
|
||||
return TemperatureStore(server)
|
||||
Executable
+596
@@ -0,0 +1,596 @@
|
||||
#!/usr/bin/env python3
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import pathlib
|
||||
import sys
|
||||
import argparse
|
||||
import importlib
|
||||
import os
|
||||
import io
|
||||
import time
|
||||
import socket
|
||||
import logging
|
||||
import signal
|
||||
import asyncio
|
||||
from . import confighelper
|
||||
from .eventloop import EventLoop
|
||||
from .app import MoonrakerApp
|
||||
from .klippy_connection import KlippyConnection
|
||||
from .utils import ServerError, Sentinel, get_software_version
|
||||
from .loghelper import LogManager
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
List,
|
||||
Tuple,
|
||||
Union,
|
||||
TypeVar,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from .websockets import WebRequest, WebsocketManager
|
||||
from .components.file_manager.file_manager import FileManager
|
||||
from .components.machine import Machine
|
||||
from .components.extensions import ExtensionManager
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
_T = TypeVar("_T", Sentinel, Any)
|
||||
|
||||
API_VERSION = (1, 2, 1)
|
||||
CORE_COMPONENTS = [
|
||||
'dbus_manager', 'database', 'file_manager', 'klippy_apis',
|
||||
'machine', 'data_store', 'shell_command', 'proc_stats',
|
||||
'job_state', 'job_queue', 'http_client', 'announcements',
|
||||
'webcam', 'extensions',
|
||||
]
|
||||
|
||||
|
||||
class Server:
|
||||
error = ServerError
|
||||
config_error = confighelper.ConfigError
|
||||
def __init__(self,
|
||||
args: Dict[str, Any],
|
||||
log_manager: LogManager,
|
||||
event_loop: EventLoop
|
||||
) -> None:
|
||||
self.event_loop = event_loop
|
||||
self.log_manager = log_manager
|
||||
self.app_args = args
|
||||
self.events: Dict[str, List[FlexCallback]] = {}
|
||||
self.components: Dict[str, Any] = {}
|
||||
self.failed_components: List[str] = []
|
||||
self.warnings: Dict[str, str] = {}
|
||||
self._is_configured: bool = False
|
||||
|
||||
self.config = config = self._parse_config()
|
||||
self.host: str = config.get('host', "0.0.0.0")
|
||||
self.port: int = config.getint('port', 7125)
|
||||
self.ssl_port: int = config.getint('ssl_port', 7130)
|
||||
self.exit_reason: str = ""
|
||||
self.server_running: bool = False
|
||||
|
||||
# Configure Debug Logging
|
||||
config.getboolean('enable_debug_logging', False, deprecate=True)
|
||||
self.debug = args["debug"]
|
||||
log_level = logging.DEBUG if args["verbose"] else logging.INFO
|
||||
logging.getLogger().setLevel(log_level)
|
||||
self.event_loop.set_debug(args["asyncio_debug"])
|
||||
self.klippy_connection = KlippyConnection(self)
|
||||
|
||||
# Tornado Application/Server
|
||||
self.moonraker_app = app = MoonrakerApp(config)
|
||||
self.register_endpoint = app.register_local_handler
|
||||
self.register_debug_endpoint = app.register_debug_handler
|
||||
self.register_static_file_handler = app.register_static_file_handler
|
||||
self.register_upload_handler = app.register_upload_handler
|
||||
self.register_api_transport = app.register_api_transport
|
||||
self.log_manager.set_server(self)
|
||||
|
||||
for warning in args.get("startup_warnings", []):
|
||||
self.add_warning(warning)
|
||||
|
||||
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")
|
||||
|
||||
def get_app_args(self) -> Dict[str, Any]:
|
||||
return dict(self.app_args)
|
||||
|
||||
def get_event_loop(self) -> EventLoop:
|
||||
return self.event_loop
|
||||
|
||||
def get_api_version(self) -> Tuple[int, int, int]:
|
||||
return API_VERSION
|
||||
|
||||
def get_warnings(self) -> List[str]:
|
||||
return list(self.warnings.values())
|
||||
|
||||
def is_running(self) -> bool:
|
||||
return self.server_running
|
||||
|
||||
def is_configured(self) -> bool:
|
||||
return self._is_configured
|
||||
|
||||
def is_debug_enabled(self) -> bool:
|
||||
return self.debug
|
||||
|
||||
def is_verbose_enabled(self) -> bool:
|
||||
return self.app_args["verbose"]
|
||||
|
||||
def _parse_config(self) -> confighelper.ConfigHelper:
|
||||
config = confighelper.get_configuration(self, self.app_args)
|
||||
# log config file
|
||||
cfg_files = "\n".join(config.get_config_files())
|
||||
strio = io.StringIO()
|
||||
config.write_config(strio)
|
||||
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
|
||||
cfg_item += strio.getvalue()
|
||||
cfg_item += "#"*65
|
||||
cfg_item += f"\nAll Configuration Files:\n{cfg_files}\n"
|
||||
cfg_item += "#"*65
|
||||
strio.close()
|
||||
self.add_log_rollover_item('config', cfg_item)
|
||||
return config
|
||||
|
||||
async def server_init(self, start_server: bool = True) -> None:
|
||||
self.event_loop.add_signal_handler(
|
||||
signal.SIGTERM, self._handle_term_signal)
|
||||
|
||||
# Perform asynchronous init after the event loop starts
|
||||
optional_comps: List[Coroutine] = []
|
||||
for name, component in self.components.items():
|
||||
if not hasattr(component, "component_init"):
|
||||
continue
|
||||
if name in CORE_COMPONENTS:
|
||||
# Process core components in order synchronously
|
||||
await self._initialize_component(name, component)
|
||||
else:
|
||||
optional_comps.append(
|
||||
self._initialize_component(name, component))
|
||||
|
||||
# Asynchronous Optional Component Initialization
|
||||
if optional_comps:
|
||||
await asyncio.gather(*optional_comps)
|
||||
|
||||
if not self.warnings:
|
||||
await self.event_loop.run_in_thread(self.config.create_backup)
|
||||
|
||||
machine: Machine = self.lookup_component("machine")
|
||||
if await machine.validate_installation():
|
||||
return
|
||||
|
||||
if start_server:
|
||||
await self.start_server()
|
||||
|
||||
async def start_server(self, connect_to_klippy: bool = True) -> None:
|
||||
# Open Unix Socket Server
|
||||
extm: ExtensionManager = self.lookup_component("extensions")
|
||||
await extm.start_unix_server()
|
||||
|
||||
# Start HTTP Server
|
||||
logging.info(
|
||||
f"Starting Moonraker on ({self.host}, {self.port}), "
|
||||
f"Hostname: {socket.gethostname()}")
|
||||
self.moonraker_app.listen(self.host, self.port, self.ssl_port)
|
||||
self.server_running = True
|
||||
if connect_to_klippy:
|
||||
self.klippy_connection.connect()
|
||||
|
||||
def add_log_rollover_item(self, name: str, item: str,
|
||||
log: bool = True) -> None:
|
||||
self.log_manager.set_rollover_info(name, item)
|
||||
if log and item is not None:
|
||||
logging.info(item)
|
||||
|
||||
def add_warning(
|
||||
self, warning: str, warn_id: Optional[str] = None, log: bool = True
|
||||
) -> str:
|
||||
if warn_id is None:
|
||||
warn_id = str(id(warning))
|
||||
self.warnings[warn_id] = warning
|
||||
if log:
|
||||
logging.warning(warning)
|
||||
return warn_id
|
||||
|
||||
def remove_warning(self, warn_id: str) -> None:
|
||||
self.warnings.pop(warn_id, None)
|
||||
|
||||
# ***** Component Management *****
|
||||
async def _initialize_component(self, name: str, component: Any) -> None:
|
||||
logging.info(f"Performing Component Post Init: [{name}]")
|
||||
try:
|
||||
ret = component.component_init()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception as e:
|
||||
logging.exception(f"Component [{name}] failed post init")
|
||||
self.add_warning(f"Component '{name}' failed to load with "
|
||||
f"error: {e}")
|
||||
self.set_failed_component(name)
|
||||
|
||||
def load_components(self) -> None:
|
||||
config = self.config
|
||||
cfg_sections = set([s.split()[0] for s in config.sections()])
|
||||
cfg_sections.remove('server')
|
||||
|
||||
# load core components
|
||||
for component in CORE_COMPONENTS:
|
||||
self.load_component(config, component)
|
||||
if component in cfg_sections:
|
||||
cfg_sections.remove(component)
|
||||
|
||||
# load remaining optional components
|
||||
for section in cfg_sections:
|
||||
self.load_component(config, section, None)
|
||||
|
||||
self.klippy_connection.configure(config)
|
||||
config.validate_config()
|
||||
self._is_configured = True
|
||||
|
||||
def load_component(
|
||||
self,
|
||||
config: confighelper.ConfigHelper,
|
||||
component_name: str,
|
||||
default: _T = Sentinel.MISSING
|
||||
) -> Union[_T, Any]:
|
||||
if component_name in self.components:
|
||||
return self.components[component_name]
|
||||
if self.is_configured():
|
||||
raise self.error(
|
||||
"Cannot load components after configuration", 500
|
||||
)
|
||||
if component_name in self.failed_components:
|
||||
raise self.error(
|
||||
f"Component {component_name} previously failed to load", 500
|
||||
)
|
||||
try:
|
||||
full_name = f"moonraker.components.{component_name}"
|
||||
module = importlib.import_module(full_name)
|
||||
is_core = component_name in CORE_COMPONENTS
|
||||
fallback: Optional[str] = "server" if is_core else None
|
||||
config = config.getsection(component_name, fallback)
|
||||
load_func = getattr(module, "load_component")
|
||||
component = load_func(config)
|
||||
except Exception:
|
||||
msg = f"Unable to load component: ({component_name})"
|
||||
logging.exception(msg)
|
||||
if component_name not in self.failed_components:
|
||||
self.failed_components.append(component_name)
|
||||
if default is Sentinel.MISSING:
|
||||
raise
|
||||
return default
|
||||
self.components[component_name] = component
|
||||
logging.info(f"Component ({component_name}) loaded")
|
||||
return component
|
||||
|
||||
def lookup_component(
|
||||
self, component_name: str, default: _T = Sentinel.MISSING
|
||||
) -> Union[_T, Any]:
|
||||
component = self.components.get(component_name, default)
|
||||
if component is Sentinel.MISSING:
|
||||
raise ServerError(f"Component ({component_name}) not found")
|
||||
return component
|
||||
|
||||
def set_failed_component(self, component_name: str) -> None:
|
||||
if component_name not in self.failed_components:
|
||||
self.failed_components.append(component_name)
|
||||
|
||||
def register_component(self, component_name: str, component: Any) -> None:
|
||||
if component_name in self.components:
|
||||
raise self.error(
|
||||
f"Component '{component_name}' already registered")
|
||||
self.components[component_name] = component
|
||||
|
||||
def register_notification(self,
|
||||
event_name: str,
|
||||
notify_name: Optional[str] = None
|
||||
) -> None:
|
||||
wsm: WebsocketManager = self.lookup_component("websockets")
|
||||
wsm.register_notification(event_name, notify_name)
|
||||
|
||||
def register_event_handler(self,
|
||||
event: str,
|
||||
callback: FlexCallback
|
||||
) -> None:
|
||||
self.events.setdefault(event, []).append(callback)
|
||||
|
||||
def send_event(self, event: str, *args) -> asyncio.Future:
|
||||
fut = self.event_loop.create_future()
|
||||
self.event_loop.register_callback(
|
||||
self._process_event, fut, event, *args)
|
||||
return fut
|
||||
|
||||
async def _process_event(self,
|
||||
fut: asyncio.Future,
|
||||
event: str,
|
||||
*args
|
||||
) -> None:
|
||||
events = self.events.get(event, [])
|
||||
coroutines: List[Coroutine] = []
|
||||
try:
|
||||
for func in events:
|
||||
ret = func(*args)
|
||||
if ret is not None:
|
||||
coroutines.append(ret)
|
||||
if coroutines:
|
||||
await asyncio.gather(*coroutines)
|
||||
except ServerError as e:
|
||||
logging.exception(f"Error Processing Event: {fut}")
|
||||
if not fut.done():
|
||||
fut.set_result(None)
|
||||
|
||||
def register_remote_method(self,
|
||||
method_name: str,
|
||||
cb: FlexCallback
|
||||
) -> None:
|
||||
self.klippy_connection.register_remote_method(method_name, cb)
|
||||
|
||||
def get_host_info(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'hostname': socket.gethostname(),
|
||||
'address': self.host,
|
||||
'port': self.port,
|
||||
'ssl_port': self.ssl_port
|
||||
}
|
||||
|
||||
def get_klippy_info(self) -> Dict[str, Any]:
|
||||
return self.klippy_connection.klippy_info
|
||||
|
||||
def get_klippy_state(self) -> str:
|
||||
return self.klippy_connection.state
|
||||
|
||||
def _handle_term_signal(self) -> None:
|
||||
logging.info(f"Exiting with signal SIGTERM")
|
||||
self.event_loop.register_callback(self._stop_server, "terminate")
|
||||
|
||||
async def _stop_server(self, exit_reason: str = "restart") -> None:
|
||||
self.server_running = False
|
||||
# Call each component's "on_exit" method
|
||||
for name, component in self.components.items():
|
||||
if hasattr(component, "on_exit"):
|
||||
func: FlexCallback = getattr(component, "on_exit")
|
||||
try:
|
||||
ret = func()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error executing 'on_exit()' for component: {name}")
|
||||
|
||||
# Sleep for 100ms to allow connected websockets to write out
|
||||
# remaining data
|
||||
await asyncio.sleep(.1)
|
||||
try:
|
||||
await self.moonraker_app.close()
|
||||
except Exception:
|
||||
logging.exception("Error Closing App")
|
||||
|
||||
# Disconnect from Klippy
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.shield(self.klippy_connection.close(
|
||||
wait_closed=True)), 2.)
|
||||
except Exception:
|
||||
logging.exception("Klippy Disconnect Error")
|
||||
|
||||
# Close all components
|
||||
for name, component in self.components.items():
|
||||
if name in ["application", "websockets", "klippy_connection"]:
|
||||
# These components have already been closed
|
||||
continue
|
||||
if hasattr(component, "close"):
|
||||
func = getattr(component, "close")
|
||||
try:
|
||||
ret = func()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error executing 'close()' for component: {name}")
|
||||
# Allow cancelled tasks a chance to run in the eventloop
|
||||
await asyncio.sleep(.001)
|
||||
|
||||
self.exit_reason = exit_reason
|
||||
self.event_loop.remove_signal_handler(signal.SIGTERM)
|
||||
self.event_loop.stop()
|
||||
|
||||
async def _handle_server_restart(self, web_request: WebRequest) -> str:
|
||||
self.event_loop.register_callback(self._stop_server)
|
||||
return "ok"
|
||||
|
||||
async def _handle_info_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
raw = web_request.get_boolean("raw", False)
|
||||
file_manager: Optional[FileManager] = self.lookup_component(
|
||||
'file_manager', None)
|
||||
reg_dirs = []
|
||||
if file_manager is not None:
|
||||
reg_dirs = file_manager.get_registered_dirs()
|
||||
wsm: WebsocketManager = self.lookup_component('websockets')
|
||||
mreqs = self.klippy_connection.missing_requirements
|
||||
if raw:
|
||||
warnings = list(self.warnings.values())
|
||||
else:
|
||||
warnings = [
|
||||
w.replace("\n", "<br/>") for w in self.warnings.values()
|
||||
]
|
||||
return {
|
||||
'klippy_connected': self.klippy_connection.is_connected(),
|
||||
'klippy_state': self.klippy_connection.state,
|
||||
'components': list(self.components.keys()),
|
||||
'failed_components': self.failed_components,
|
||||
'registered_directories': reg_dirs,
|
||||
'warnings': warnings,
|
||||
'websocket_count': wsm.get_count(),
|
||||
'moonraker_version': self.app_args['software_version'],
|
||||
'missing_klippy_requirements': mreqs,
|
||||
'api_version': API_VERSION,
|
||||
'api_version_string': ".".join([str(v) for v in API_VERSION])
|
||||
}
|
||||
|
||||
async def _handle_config_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
cfg_file_list: List[Dict[str, Any]] = []
|
||||
cfg_parent = pathlib.Path(
|
||||
self.app_args["config_file"]
|
||||
).expanduser().resolve().parent
|
||||
for fname, sections in self.config.get_file_sections().items():
|
||||
path = pathlib.Path(fname)
|
||||
try:
|
||||
rel_path = str(path.relative_to(str(cfg_parent)))
|
||||
except ValueError:
|
||||
rel_path = fname
|
||||
cfg_file_list.append({"filename": rel_path, "sections": sections})
|
||||
return {
|
||||
'config': self.config.get_parsed_config(),
|
||||
'orig': self.config.get_orig_config(),
|
||||
'files': cfg_file_list
|
||||
}
|
||||
|
||||
def main(from_package: bool = True) -> None:
|
||||
# Parse start arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Moonraker - Klipper API Server")
|
||||
parser.add_argument(
|
||||
"-d", "--datapath", default=None,
|
||||
metavar='<data path>',
|
||||
help="Location of Moonraker Data File Path"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c", "--configfile", default=None, metavar='<configfile>',
|
||||
help="Location of moonraker configuration file")
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default=None, metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
parser.add_argument(
|
||||
"-n", "--nologfile", action='store_true',
|
||||
help="disable logging to a file")
|
||||
parser.add_argument(
|
||||
"-v", "--verbose", action="store_true",
|
||||
help="Enable verbose logging"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-g", "--debug", action="store_true",
|
||||
help="Enable Moonraker debug features"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o", "--asyncio-debug", action="store_true",
|
||||
help="Enable asyncio debug flag"
|
||||
)
|
||||
cmd_line_args = parser.parse_args()
|
||||
|
||||
startup_warnings: List[str] = []
|
||||
dp: str = cmd_line_args.datapath or "~/printer_data"
|
||||
data_path = pathlib.Path(dp).expanduser().resolve()
|
||||
if not data_path.exists():
|
||||
try:
|
||||
data_path.mkdir()
|
||||
except Exception:
|
||||
startup_warnings.append(
|
||||
f"Unable to create data path folder at {data_path}"
|
||||
)
|
||||
if cmd_line_args.configfile is not None:
|
||||
cfg_file: str = cmd_line_args.configfile
|
||||
else:
|
||||
cfg_file = str(data_path.joinpath("config/moonraker.conf"))
|
||||
app_args = {
|
||||
"data_path": str(data_path),
|
||||
"is_default_data_path": cmd_line_args.datapath is None,
|
||||
"config_file": cfg_file,
|
||||
"startup_warnings": startup_warnings,
|
||||
"verbose": cmd_line_args.verbose,
|
||||
"debug": cmd_line_args.debug,
|
||||
"asyncio_debug": cmd_line_args.asyncio_debug,
|
||||
"is_backup_config": False,
|
||||
"is_python_package": from_package
|
||||
}
|
||||
|
||||
# Setup Logging
|
||||
version = get_software_version()
|
||||
if cmd_line_args.nologfile:
|
||||
app_args["log_file"] = ""
|
||||
elif cmd_line_args.logfile:
|
||||
app_args["log_file"] = os.path.normpath(
|
||||
os.path.expanduser(cmd_line_args.logfile))
|
||||
else:
|
||||
app_args["log_file"] = str(data_path.joinpath("logs/moonraker.log"))
|
||||
app_args["software_version"] = version
|
||||
app_args["python_version"] = sys.version.replace("\n", " ")
|
||||
log_manager = LogManager(app_args, startup_warnings)
|
||||
|
||||
# Start asyncio event loop and server
|
||||
event_loop = EventLoop()
|
||||
alt_config_loaded = False
|
||||
estatus = 0
|
||||
while True:
|
||||
try:
|
||||
server = Server(app_args, log_manager, event_loop)
|
||||
server.load_components()
|
||||
except confighelper.ConfigError as e:
|
||||
backup_cfg = confighelper.find_config_backup(cfg_file)
|
||||
logging.exception("Server Config Error")
|
||||
if alt_config_loaded or backup_cfg is None:
|
||||
estatus = 1
|
||||
break
|
||||
app_args["config_file"] = backup_cfg
|
||||
app_args["is_backup_config"] = True
|
||||
warn_list = list(startup_warnings)
|
||||
app_args["startup_warnings"] = warn_list
|
||||
warn_list.append(
|
||||
f"Server configuration error: {e}\n"
|
||||
f"Loaded server from most recent working configuration:"
|
||||
f" '{app_args['config_file']}'\n"
|
||||
f"Please fix the issue in moonraker.conf and restart "
|
||||
f"the server."
|
||||
)
|
||||
alt_config_loaded = True
|
||||
continue
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
estatus = 1
|
||||
break
|
||||
try:
|
||||
event_loop.register_callback(server.server_init)
|
||||
event_loop.start()
|
||||
except Exception:
|
||||
logging.exception("Server Running Error")
|
||||
estatus = 1
|
||||
break
|
||||
if server.exit_reason == "terminate":
|
||||
break
|
||||
# Restore the original config and clear the warning
|
||||
# before the server restarts
|
||||
if alt_config_loaded:
|
||||
app_args["config_file"] = cfg_file
|
||||
app_args["startup_warnings"] = startup_warnings
|
||||
app_args["is_backup_config"] = False
|
||||
alt_config_loaded = False
|
||||
event_loop.close()
|
||||
# Since we are running outside of the the server
|
||||
# it is ok to use a blocking sleep here
|
||||
time.sleep(.5)
|
||||
logging.info("Attempting Server Restart...")
|
||||
event_loop.reset()
|
||||
event_loop.close()
|
||||
logging.info("Server Shutdown")
|
||||
log_manager.stop_logging()
|
||||
exit(estatus)
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
# package definition for thirdparty package
|
||||
+1
@@ -0,0 +1 @@
|
||||
# package definition for packagekit thirdparty files
|
||||
+768
@@ -0,0 +1,768 @@
|
||||
|
||||
# This file was autogenerated from pk-enum.h by pk-enum-converter.py
|
||||
# on Fri Jan 21 16:01:47 2022 UTC
|
||||
#
|
||||
# License for original source:
|
||||
#
|
||||
# Copyright (C) 2007-2014 Richard Hughes <richard@hughsie.com>
|
||||
#
|
||||
# Licensed under the GNU Lesser General Public License Version 2.1
|
||||
#
|
||||
# This library is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU Lesser General Public
|
||||
# License as published by the Free Software Foundation; either
|
||||
# version 2.1 of the License, or (at your option) any later version.
|
||||
#
|
||||
# This library is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
# Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public
|
||||
# License along with this library; if not, write to the Free Software
|
||||
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
#
|
||||
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
from enum import Flag, auto
|
||||
|
||||
class PkFlag(Flag):
|
||||
@classmethod
|
||||
def from_pkstring(cls, pkstring: str):
|
||||
for name, member in cls.__members__.items():
|
||||
if member.pkstring == pkstring:
|
||||
return cls(member.value)
|
||||
# Return "unknown" flag
|
||||
return cls(1)
|
||||
|
||||
@classmethod
|
||||
def from_index(cls, index: int):
|
||||
return cls(1 << index)
|
||||
|
||||
@property
|
||||
def pkstring(self) -> str:
|
||||
if self.name is None:
|
||||
return " | ".join([f.pkstring for f in self])
|
||||
return self.name.lower().replace("_", "-")
|
||||
|
||||
@property
|
||||
def desc(self) -> str:
|
||||
if self.name is None:
|
||||
return ", ".join([f.desc for f in self])
|
||||
description = self.name.lower().replace("_", " ")
|
||||
return description.capitalize()
|
||||
|
||||
@property
|
||||
def index(self) -> int:
|
||||
return self.value.bit_length() - 1
|
||||
|
||||
if sys.version_info < (3, 11):
|
||||
def __iter__(self):
|
||||
for i in range(self._value_.bit_length()):
|
||||
val = 1 << i
|
||||
if val & self._value_ == val:
|
||||
yield self.__class__(val)
|
||||
|
||||
|
||||
class Role(PkFlag):
|
||||
"""
|
||||
What we were asked to do, this never changes for the lifetime of the
|
||||
transaction.
|
||||
Icons that have to represent the whole "aim" of the transaction will use
|
||||
these constants
|
||||
|
||||
* Role.UNKNOWN: Unknow request
|
||||
* Role.CANCEL: Cancel transaction
|
||||
* Role.DEPENDS_ON: Get package dependencies
|
||||
* Role.GET_DETAILS: Get package details
|
||||
* Role.GET_FILES:
|
||||
* Role.GET_PACKAGES: Get available packages
|
||||
* Role.GET_REPO_LIST: Get repository list
|
||||
* Role.REQUIRED_BY: Get packages required by given package
|
||||
* Role.GET_UPDATE_DETAIL: Get update details
|
||||
* Role.GET_UPDATES: Get available updates
|
||||
* Role.INSTALL_FILES: Install package files
|
||||
* Role.INSTALL_PACKAGES: Install packages
|
||||
* Role.INSTALL_SIGNATURE: Install signature
|
||||
* Role.REFRESH_CACHE: Refresh cache
|
||||
* Role.REMOVE_PACKAGES: Remove packages
|
||||
* Role.REPO_ENABLE: Enable repository
|
||||
* Role.REPO_SET_DATA:
|
||||
* Role.RESOLVE: Resolve depdencies
|
||||
* Role.SEARCH_DETAILS: Search for details
|
||||
* Role.SEARCH_FILE: Search for file
|
||||
* Role.SEARCH_GROUP: Search for group
|
||||
* Role.SEARCH_NAME: Search for package name
|
||||
* Role.UPDATE_PACKAGES: Update packages
|
||||
* Role.WHAT_PROVIDES: Get what a package provides
|
||||
* Role.ACCEPT_EULA: Accept an EULA
|
||||
* Role.DOWNLOAD_PACKAGES: Download packages
|
||||
* Role.GET_DISTRO_UPGRADES: Get available distribution upgrades
|
||||
* Role.GET_CATEGORIES: Get available categories
|
||||
* Role.GET_OLD_TRANSACTIONS: Get old transation information
|
||||
* Role.REPAIR_SYSTEM: Repair system
|
||||
* Role.GET_DETAILS_LOCAL: Get details on local package
|
||||
* Role.GET_FILES_LOCAL: Get files provided by local package
|
||||
* Role.REPO_REMOVE: Remove repository
|
||||
* Role.UPGRADE_SYSTEM: Upgrade system
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
CANCEL = auto()
|
||||
DEPENDS_ON = auto()
|
||||
GET_DETAILS = auto()
|
||||
GET_FILES = auto()
|
||||
GET_PACKAGES = auto()
|
||||
GET_REPO_LIST = auto()
|
||||
REQUIRED_BY = auto()
|
||||
GET_UPDATE_DETAIL = auto()
|
||||
GET_UPDATES = auto()
|
||||
INSTALL_FILES = auto()
|
||||
INSTALL_PACKAGES = auto()
|
||||
INSTALL_SIGNATURE = auto()
|
||||
REFRESH_CACHE = auto()
|
||||
REMOVE_PACKAGES = auto()
|
||||
REPO_ENABLE = auto()
|
||||
REPO_SET_DATA = auto()
|
||||
RESOLVE = auto()
|
||||
SEARCH_DETAILS = auto()
|
||||
SEARCH_FILE = auto()
|
||||
SEARCH_GROUP = auto()
|
||||
SEARCH_NAME = auto()
|
||||
UPDATE_PACKAGES = auto()
|
||||
WHAT_PROVIDES = auto()
|
||||
ACCEPT_EULA = auto()
|
||||
DOWNLOAD_PACKAGES = auto()
|
||||
GET_DISTRO_UPGRADES = auto()
|
||||
GET_CATEGORIES = auto()
|
||||
GET_OLD_TRANSACTIONS = auto()
|
||||
REPAIR_SYSTEM = auto()
|
||||
GET_DETAILS_LOCAL = auto()
|
||||
GET_FILES_LOCAL = auto()
|
||||
REPO_REMOVE = auto()
|
||||
UPGRADE_SYSTEM = auto()
|
||||
|
||||
class Status(PkFlag):
|
||||
"""
|
||||
What status we are now; this can change for each transaction giving a
|
||||
status of what sort of thing is happening
|
||||
Icons that change to represent the current status of the transaction will
|
||||
use these constants
|
||||
If you add to these, make sure you add filenames in gpk-watch.c also
|
||||
|
||||
A typical transaction will do:
|
||||
- schedule task
|
||||
WAIT
|
||||
- run task
|
||||
SETUP
|
||||
- wait for lock
|
||||
RUNNING
|
||||
|
||||
This means that backends should run pk_backend_set_status (backend,
|
||||
PK_STATUS_ENUM_RUNNING)
|
||||
when they are ready to start running the transaction and after a lock has
|
||||
been got.
|
||||
|
||||
* Status.UNKNOWN: Unknown status
|
||||
* Status.WAIT: Waiting
|
||||
* Status.SETUP: Setting up
|
||||
* Status.RUNNING: Running
|
||||
* Status.QUERY:
|
||||
* Status.INFO:
|
||||
* Status.REMOVE: Removing
|
||||
* Status.REFRESH_CACHE: Refreshing cache
|
||||
* Status.DOWNLOAD: Downloading
|
||||
* Status.INSTALL: Installing
|
||||
* Status.UPDATE: Updating
|
||||
* Status.CLEANUP: Cleaning up
|
||||
* Status.OBSOLETE:
|
||||
* Status.DEP_RESOLVE: Resolving dependencies
|
||||
* Status.SIG_CHECK: Checking signatures
|
||||
* Status.TEST_COMMIT: Testing commit
|
||||
* Status.COMMIT: Committing
|
||||
* Status.REQUEST:
|
||||
* Status.FINISHED: Finished
|
||||
* Status.CANCEL: Cancelling
|
||||
* Status.DOWNLOAD_REPOSITORY: Downloading respository
|
||||
* Status.DOWNLOAD_PACKAGELIST: Donwloading package list
|
||||
* Status.DOWNLOAD_FILELIST: Downloading file list
|
||||
* Status.DOWNLOAD_CHANGELOG: Downloading changelog information
|
||||
* Status.DOWNLOAD_GROUP: Downloading group information
|
||||
* Status.DOWNLOAD_UPDATEINFO: Downloading update information
|
||||
* Status.REPACKAGING: Repackaging
|
||||
* Status.LOADING_CACHE: Loading cache
|
||||
* Status.SCAN_APPLICATIONS: Scanning for applications
|
||||
* Status.GENERATE_PACKAGE_LIST: Generating package list
|
||||
* Status.WAITING_FOR_LOCK: Waiting for lock
|
||||
* Status.WAITING_FOR_AUTH: Waiting for authentication/authorization
|
||||
* Status.SCAN_PROCESS_LIST: Scanning running processes
|
||||
* Status.CHECK_EXECUTABLE_FILES: Checking executable files
|
||||
* Status.CHECK_LIBRARIES: Checking libraries
|
||||
* Status.COPY_FILES: Copying files
|
||||
* Status.RUN_HOOK: Running package hook
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
WAIT = auto()
|
||||
SETUP = auto()
|
||||
RUNNING = auto()
|
||||
QUERY = auto()
|
||||
INFO = auto()
|
||||
REMOVE = auto()
|
||||
REFRESH_CACHE = auto()
|
||||
DOWNLOAD = auto()
|
||||
INSTALL = auto()
|
||||
UPDATE = auto()
|
||||
CLEANUP = auto()
|
||||
OBSOLETE = auto()
|
||||
DEP_RESOLVE = auto()
|
||||
SIG_CHECK = auto()
|
||||
TEST_COMMIT = auto()
|
||||
COMMIT = auto()
|
||||
REQUEST = auto()
|
||||
FINISHED = auto()
|
||||
CANCEL = auto()
|
||||
DOWNLOAD_REPOSITORY = auto()
|
||||
DOWNLOAD_PACKAGELIST = auto()
|
||||
DOWNLOAD_FILELIST = auto()
|
||||
DOWNLOAD_CHANGELOG = auto()
|
||||
DOWNLOAD_GROUP = auto()
|
||||
DOWNLOAD_UPDATEINFO = auto()
|
||||
REPACKAGING = auto()
|
||||
LOADING_CACHE = auto()
|
||||
SCAN_APPLICATIONS = auto()
|
||||
GENERATE_PACKAGE_LIST = auto()
|
||||
WAITING_FOR_LOCK = auto()
|
||||
WAITING_FOR_AUTH = auto()
|
||||
SCAN_PROCESS_LIST = auto()
|
||||
CHECK_EXECUTABLE_FILES = auto()
|
||||
CHECK_LIBRARIES = auto()
|
||||
COPY_FILES = auto()
|
||||
RUN_HOOK = auto()
|
||||
|
||||
class Exit(PkFlag):
|
||||
"""
|
||||
How the backend exited
|
||||
|
||||
* Exit.UNKNOWN: Unknown exit status
|
||||
* Exit.SUCCESS: Backend exited successfully
|
||||
* Exit.FAILED: Backend failed
|
||||
* Exit.CANCELLED: Backend was cancelled
|
||||
* Exit.KEY_REQUIRED: A repository encryption key needs installing
|
||||
* Exit.EULA_REQUIRED: A EULA is required to be accepted
|
||||
* Exit.KILLED: Backend was killed
|
||||
* Exit.MEDIA_CHANGE_REQUIRED: Media change required
|
||||
* Exit.NEED_UNTRUSTED:
|
||||
* Exit.CANCELLED_PRIORITY: Cancelled due to higher priority task
|
||||
* Exit.SKIP_TRANSACTION:
|
||||
* Exit.REPAIR_REQUIRED: Package database requires repairing
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
SUCCESS = auto()
|
||||
FAILED = auto()
|
||||
CANCELLED = auto()
|
||||
KEY_REQUIRED = auto()
|
||||
EULA_REQUIRED = auto()
|
||||
KILLED = auto()
|
||||
MEDIA_CHANGE_REQUIRED = auto()
|
||||
NEED_UNTRUSTED = auto()
|
||||
CANCELLED_PRIORITY = auto()
|
||||
SKIP_TRANSACTION = auto()
|
||||
REPAIR_REQUIRED = auto()
|
||||
|
||||
class Network(PkFlag):
|
||||
"""
|
||||
Network type
|
||||
|
||||
* Network.UNKNOWN: Unknown network
|
||||
* Network.OFFLINE: Offline (no network)
|
||||
* Network.ONLINE: Online (network type unknown)
|
||||
* Network.WIRED: Wired network
|
||||
* Network.WIFI: WiFi network
|
||||
* Network.MOBILE: Mobile network
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
OFFLINE = auto()
|
||||
ONLINE = auto()
|
||||
WIRED = auto()
|
||||
WIFI = auto()
|
||||
MOBILE = auto()
|
||||
|
||||
class Filter(PkFlag):
|
||||
"""
|
||||
The filter types
|
||||
|
||||
* Filter.UNKNOWN: Unknown filter
|
||||
* Filter.NONE: No filter
|
||||
* Filter.INSTALLED: Filter for installed packages
|
||||
* Filter.NOT_INSTALLED: Filter for not installed packages
|
||||
* Filter.DEVELOPMENT: Filter for development packages
|
||||
* Filter.NOT_DEVELOPMENT: Filter for non-development packages
|
||||
* Filter.GUI: Filter for GUI packages
|
||||
* Filter.NOT_GUI: Filter for non-GUI packages
|
||||
* Filter.FREE: Filter for free packages
|
||||
* Filter.NOT_FREE: Filter for non-free packages
|
||||
* Filter.VISIBLE: Filter for visible packages
|
||||
* Filter.NOT_VISIBLE: Filter for invisible packages
|
||||
* Filter.SUPPORTED: Filter for supported packages
|
||||
* Filter.NOT_SUPPORTED: Filter for not supported packages
|
||||
* Filter.BASENAME: Filter for packages that match basename
|
||||
* Filter.NOT_BASENAME: Filter for packages that don't match basename
|
||||
* Filter.NEWEST: Filter for newest packages
|
||||
* Filter.NOT_NEWEST: Filter for not newest packages
|
||||
* Filter.ARCH: Filter for packages that match architecture
|
||||
* Filter.NOT_ARCH: Filter for packages that don't match architecture
|
||||
* Filter.SOURCE: Filter for source packages
|
||||
* Filter.NOT_SOURCE: Filter for non-source packages
|
||||
* Filter.COLLECTIONS: Filter for collections
|
||||
* Filter.NOT_COLLECTIONS: Filter for not collections
|
||||
* Filter.APPLICATION: Filter for application packages
|
||||
* Filter.NOT_APPLICATION: Filter for non-application packages
|
||||
* Filter.DOWNLOADED: Filter for downloaded packages
|
||||
* Filter.NOT_DOWNLOADED: Filter for not downloaded packages
|
||||
"""
|
||||
@property
|
||||
def pkstring(self) -> str:
|
||||
pks = self.name
|
||||
if pks is None:
|
||||
return " | ".join([f.pkstring for f in self])
|
||||
if pks in ["DEVELOPMENT", "NOT_DEVELOPMENT"]:
|
||||
pks = pks[:-6]
|
||||
if pks[:4] == "NOT_":
|
||||
pks = "~" + pks[4:]
|
||||
return pks.lower().replace("_", "-")
|
||||
|
||||
UNKNOWN = auto()
|
||||
NONE = auto()
|
||||
INSTALLED = auto()
|
||||
NOT_INSTALLED = auto()
|
||||
DEVELOPMENT = auto()
|
||||
NOT_DEVELOPMENT = auto()
|
||||
GUI = auto()
|
||||
NOT_GUI = auto()
|
||||
FREE = auto()
|
||||
NOT_FREE = auto()
|
||||
VISIBLE = auto()
|
||||
NOT_VISIBLE = auto()
|
||||
SUPPORTED = auto()
|
||||
NOT_SUPPORTED = auto()
|
||||
BASENAME = auto()
|
||||
NOT_BASENAME = auto()
|
||||
NEWEST = auto()
|
||||
NOT_NEWEST = auto()
|
||||
ARCH = auto()
|
||||
NOT_ARCH = auto()
|
||||
SOURCE = auto()
|
||||
NOT_SOURCE = auto()
|
||||
COLLECTIONS = auto()
|
||||
NOT_COLLECTIONS = auto()
|
||||
APPLICATION = auto()
|
||||
NOT_APPLICATION = auto()
|
||||
DOWNLOADED = auto()
|
||||
NOT_DOWNLOADED = auto()
|
||||
|
||||
class Restart(PkFlag):
|
||||
"""
|
||||
What restart we need to after a transaction, ordered by severity
|
||||
|
||||
* Restart.UNKNOWN: Unknown restart state
|
||||
* Restart.NONE: No restart required
|
||||
* Restart.APPLICATION: Need to restart the application
|
||||
* Restart.SESSION: Need to restart the session
|
||||
* Restart.SYSTEM: Need to restart the system
|
||||
* Restart.SECURITY_SESSION:
|
||||
* Restart.SECURITY_SYSTEM:
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
NONE = auto()
|
||||
APPLICATION = auto()
|
||||
SESSION = auto()
|
||||
SYSTEM = auto()
|
||||
SECURITY_SESSION = auto()
|
||||
SECURITY_SYSTEM = auto()
|
||||
|
||||
class Error(PkFlag):
|
||||
"""
|
||||
The error type
|
||||
|
||||
* Error.UNKNOWN:
|
||||
* Error.OOM: Out of memory
|
||||
* Error.NO_NETWORK: No network access available
|
||||
* Error.NOT_SUPPORTED: Request not supported
|
||||
* Error.INTERNAL_ERROR: Undefined internal error
|
||||
* Error.GPG_FAILURE: GPG encryption failure
|
||||
* Error.PACKAGE_ID_INVALID: Invalid package ID provided
|
||||
* Error.PACKAGE_NOT_INSTALLED: Requested package not installed
|
||||
* Error.PACKAGE_NOT_FOUND: Requested package not found
|
||||
* Error.PACKAGE_ALREADY_INSTALLED: Requested package already installed
|
||||
* Error.PACKAGE_DOWNLOAD_FAILED: Failed to download package
|
||||
* Error.GROUP_NOT_FOUND: Requested group not gound
|
||||
* Error.GROUP_LIST_INVALID: Invalid group list provided
|
||||
* Error.DEP_RESOLUTION_FAILED: Failed to resolve dependencies
|
||||
* Error.FILTER_INVALID: Invalid filter provides
|
||||
* Error.CREATE_THREAD_FAILED: Failed to create thread
|
||||
* Error.TRANSACTION_ERROR: Error occurred during transaction
|
||||
* Error.TRANSACTION_CANCELLED: Transaction was cancelled
|
||||
* Error.NO_CACHE: No cache available
|
||||
* Error.REPO_NOT_FOUND: Requested repository not found
|
||||
* Error.CANNOT_REMOVE_SYSTEM_PACKAGE: Not allowed to remove system package
|
||||
* Error.PROCESS_KILL: Process killed
|
||||
* Error.FAILED_INITIALIZATION:
|
||||
* Error.FAILED_FINALISE:
|
||||
* Error.FAILED_CONFIG_PARSING: Configuration is not valid
|
||||
* Error.CANNOT_CANCEL:
|
||||
* Error.CANNOT_GET_LOCK: Cannot get lock
|
||||
* Error.NO_PACKAGES_TO_UPDATE: No packages to update
|
||||
* Error.CANNOT_WRITE_REPO_CONFIG: Cannot write repository configuration
|
||||
* Error.LOCAL_INSTALL_FAILED:
|
||||
* Error.BAD_GPG_SIGNATURE: Bad GPG signature found
|
||||
* Error.MISSING_GPG_SIGNATURE: Required GPG signature not found
|
||||
* Error.CANNOT_INSTALL_SOURCE_PACKAGE: Cannot install source package
|
||||
* Error.REPO_CONFIGURATION_ERROR:
|
||||
* Error.NO_LICENSE_AGREEMENT:
|
||||
* Error.FILE_CONFLICTS: File conflicts detected
|
||||
* Error.PACKAGE_CONFLICTS: Package conflict
|
||||
* Error.REPO_NOT_AVAILABLE: Repository not available
|
||||
* Error.INVALID_PACKAGE_FILE:
|
||||
* Error.PACKAGE_INSTALL_BLOCKED: Package installation blocked
|
||||
* Error.PACKAGE_CORRUPT: Package corruption occurred
|
||||
* Error.ALL_PACKAGES_ALREADY_INSTALLED: All packages already installed
|
||||
* Error.FILE_NOT_FOUND: Required file not found
|
||||
* Error.NO_MORE_MIRRORS_TO_TRY: Out of repository mirrors to try
|
||||
* Error.NO_DISTRO_UPGRADE_DATA: No distribution upgrade path found
|
||||
* Error.INCOMPATIBLE_ARCHITECTURE: Incompatible architecture found
|
||||
* Error.NO_SPACE_ON_DEVICE: Out of required disk space
|
||||
* Error.MEDIA_CHANGE_REQUIRED: Need to change media
|
||||
* Error.NOT_AUTHORIZED: Authorization failed
|
||||
* Error.UPDATE_NOT_FOUND: Update not found
|
||||
* Error.CANNOT_INSTALL_REPO_UNSIGNED:
|
||||
Installation repository missing signature
|
||||
* Error.CANNOT_UPDATE_REPO_UNSIGNED: Update repository missing signature
|
||||
* Error.CANNOT_GET_FILELIST: Cannot get file list
|
||||
* Error.CANNOT_GET_REQUIRES: Cannot get package requirements
|
||||
* Error.CANNOT_DISABLE_REPOSITORY: Cannot disable reposoitory
|
||||
* Error.RESTRICTED_DOWNLOAD:
|
||||
* Error.PACKAGE_FAILED_TO_CONFIGURE: Package failed to configure
|
||||
* Error.PACKAGE_FAILED_TO_BUILD: Package failed to build
|
||||
* Error.PACKAGE_FAILED_TO_INSTALL: Package failed to install
|
||||
* Error.PACKAGE_FAILED_TO_REMOVE: Package failed to remove
|
||||
* Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
|
||||
* Error.PACKAGE_DATABASE_CHANGED:
|
||||
* Error.PROVIDE_TYPE_NOT_SUPPORTED:
|
||||
* Error.INSTALL_ROOT_INVALID: Installtion root not suitable
|
||||
* Error.CANNOT_FETCH_SOURCES: Cannot fetch sources
|
||||
* Error.CANCELLED_PRIORITY: Cancelled due to higher priority task
|
||||
* Error.UNFINISHED_TRANSACTION: Transaction unfinished
|
||||
* Error.LOCK_REQUIRED: Required lock not available
|
||||
* Error.REPO_ALREADY_SET:
|
||||
"""
|
||||
@property
|
||||
def pkstring(self) -> str:
|
||||
if self == Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
|
||||
return "failed-due-to-running-process"
|
||||
return super().pkstring
|
||||
|
||||
UNKNOWN = auto()
|
||||
OUT_OF_MEMORY = auto()
|
||||
NO_NETWORK = auto()
|
||||
NOT_SUPPORTED = auto()
|
||||
INTERNAL_ERROR = auto()
|
||||
GPG_FAILURE = auto()
|
||||
PACKAGE_ID_INVALID = auto()
|
||||
PACKAGE_NOT_INSTALLED = auto()
|
||||
PACKAGE_NOT_FOUND = auto()
|
||||
PACKAGE_ALREADY_INSTALLED = auto()
|
||||
PACKAGE_DOWNLOAD_FAILED = auto()
|
||||
GROUP_NOT_FOUND = auto()
|
||||
GROUP_LIST_INVALID = auto()
|
||||
DEP_RESOLUTION_FAILED = auto()
|
||||
FILTER_INVALID = auto()
|
||||
CREATE_THREAD_FAILED = auto()
|
||||
TRANSACTION_ERROR = auto()
|
||||
TRANSACTION_CANCELLED = auto()
|
||||
NO_CACHE = auto()
|
||||
REPO_NOT_FOUND = auto()
|
||||
CANNOT_REMOVE_SYSTEM_PACKAGE = auto()
|
||||
PROCESS_KILL = auto()
|
||||
FAILED_INITIALIZATION = auto()
|
||||
FAILED_FINALISE = auto()
|
||||
FAILED_CONFIG_PARSING = auto()
|
||||
CANNOT_CANCEL = auto()
|
||||
CANNOT_GET_LOCK = auto()
|
||||
NO_PACKAGES_TO_UPDATE = auto()
|
||||
CANNOT_WRITE_REPO_CONFIG = auto()
|
||||
LOCAL_INSTALL_FAILED = auto()
|
||||
BAD_GPG_SIGNATURE = auto()
|
||||
MISSING_GPG_SIGNATURE = auto()
|
||||
CANNOT_INSTALL_SOURCE_PACKAGE = auto()
|
||||
REPO_CONFIGURATION_ERROR = auto()
|
||||
NO_LICENSE_AGREEMENT = auto()
|
||||
FILE_CONFLICTS = auto()
|
||||
PACKAGE_CONFLICTS = auto()
|
||||
REPO_NOT_AVAILABLE = auto()
|
||||
INVALID_PACKAGE_FILE = auto()
|
||||
PACKAGE_INSTALL_BLOCKED = auto()
|
||||
PACKAGE_CORRUPT = auto()
|
||||
ALL_PACKAGES_ALREADY_INSTALLED = auto()
|
||||
FILE_NOT_FOUND = auto()
|
||||
NO_MORE_MIRRORS_TO_TRY = auto()
|
||||
NO_DISTRO_UPGRADE_DATA = auto()
|
||||
INCOMPATIBLE_ARCHITECTURE = auto()
|
||||
NO_SPACE_ON_DEVICE = auto()
|
||||
MEDIA_CHANGE_REQUIRED = auto()
|
||||
NOT_AUTHORIZED = auto()
|
||||
UPDATE_NOT_FOUND = auto()
|
||||
CANNOT_INSTALL_REPO_UNSIGNED = auto()
|
||||
CANNOT_UPDATE_REPO_UNSIGNED = auto()
|
||||
CANNOT_GET_FILELIST = auto()
|
||||
CANNOT_GET_REQUIRES = auto()
|
||||
CANNOT_DISABLE_REPOSITORY = auto()
|
||||
RESTRICTED_DOWNLOAD = auto()
|
||||
PACKAGE_FAILED_TO_CONFIGURE = auto()
|
||||
PACKAGE_FAILED_TO_BUILD = auto()
|
||||
PACKAGE_FAILED_TO_INSTALL = auto()
|
||||
PACKAGE_FAILED_TO_REMOVE = auto()
|
||||
UPDATE_FAILED_DUE_TO_RUNNING_PROCESS = auto()
|
||||
PACKAGE_DATABASE_CHANGED = auto()
|
||||
PROVIDE_TYPE_NOT_SUPPORTED = auto()
|
||||
INSTALL_ROOT_INVALID = auto()
|
||||
CANNOT_FETCH_SOURCES = auto()
|
||||
CANCELLED_PRIORITY = auto()
|
||||
UNFINISHED_TRANSACTION = auto()
|
||||
LOCK_REQUIRED = auto()
|
||||
REPO_ALREADY_SET = auto()
|
||||
OOM = OUT_OF_MEMORY
|
||||
|
||||
class Group(PkFlag):
|
||||
"""
|
||||
The group type
|
||||
|
||||
* Group.UNKNOWN: Unknown group
|
||||
* Group.ACCESSIBILITY: Accessibility related packages
|
||||
* Group.ACCESSORIES: Accessory packages
|
||||
* Group.ADMIN_TOOLS: Administration tools packages
|
||||
* Group.COMMUNICATION: Communication packages
|
||||
* Group.DESKTOP_GNOME: GNOME packages
|
||||
* Group.DESKTOP_KDE: KDE packages
|
||||
* Group.DESKTOP_OTHER: Other desktop packages
|
||||
* Group.DESKTOP_XFCE: XFCE packages
|
||||
* Group.EDUCATION: Education packages
|
||||
* Group.FONTS: Fonts
|
||||
* Group.GAMES: Games
|
||||
* Group.GRAPHICS: Graphics related packages
|
||||
* Group.INTERNET: Internet related packages
|
||||
* Group.LEGACY: Legacy packages
|
||||
* Group.LOCALIZATION: Localization related packages
|
||||
* Group.MAPS: Map related packages
|
||||
* Group.MULTIMEDIA: Multimedia packages
|
||||
* Group.NETWORK: Network related packages
|
||||
* Group.OFFICE: Office packages
|
||||
* Group.OTHER:
|
||||
* Group.POWER_MANAGEMENT: Power-management related packages
|
||||
* Group.PROGRAMMING: Programming packages
|
||||
* Group.PUBLISHING: Publishing related packages
|
||||
* Group.REPOS:
|
||||
* Group.SECURITY: Security packages
|
||||
* Group.SERVERS: Server related packages
|
||||
* Group.SYSTEM: System packages
|
||||
* Group.VIRTUALIZATION: Virtualization packages
|
||||
* Group.SCIENCE: Science related packages
|
||||
* Group.DOCUMENTATION: Documentation
|
||||
* Group.ELECTRONICS: Electronics package
|
||||
* Group.COLLECTIONS:
|
||||
* Group.VENDOR: Vendor defined group
|
||||
* Group.NEWEST: Special group for recently updated packages
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
ACCESSIBILITY = auto()
|
||||
ACCESSORIES = auto()
|
||||
ADMIN_TOOLS = auto()
|
||||
COMMUNICATION = auto()
|
||||
DESKTOP_GNOME = auto()
|
||||
DESKTOP_KDE = auto()
|
||||
DESKTOP_OTHER = auto()
|
||||
DESKTOP_XFCE = auto()
|
||||
EDUCATION = auto()
|
||||
FONTS = auto()
|
||||
GAMES = auto()
|
||||
GRAPHICS = auto()
|
||||
INTERNET = auto()
|
||||
LEGACY = auto()
|
||||
LOCALIZATION = auto()
|
||||
MAPS = auto()
|
||||
MULTIMEDIA = auto()
|
||||
NETWORK = auto()
|
||||
OFFICE = auto()
|
||||
OTHER = auto()
|
||||
POWER_MANAGEMENT = auto()
|
||||
PROGRAMMING = auto()
|
||||
PUBLISHING = auto()
|
||||
REPOS = auto()
|
||||
SECURITY = auto()
|
||||
SERVERS = auto()
|
||||
SYSTEM = auto()
|
||||
VIRTUALIZATION = auto()
|
||||
SCIENCE = auto()
|
||||
DOCUMENTATION = auto()
|
||||
ELECTRONICS = auto()
|
||||
COLLECTIONS = auto()
|
||||
VENDOR = auto()
|
||||
NEWEST = auto()
|
||||
|
||||
class UpdateState(PkFlag):
|
||||
"""
|
||||
What state the update is in
|
||||
|
||||
* UpdateState.UNKNOWN: Update stability unknown
|
||||
* UpdateState.STABLE: Update is a stable release
|
||||
* UpdateState.UNSTABLE: Update is an unstable release
|
||||
* UpdateState.TESTING: Update is a testing release
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
STABLE = auto()
|
||||
UNSTABLE = auto()
|
||||
TESTING = auto()
|
||||
|
||||
class Info(PkFlag):
|
||||
"""
|
||||
The enumerated types used in Package() - these have to refer to a specific
|
||||
package action, rather than a general state
|
||||
|
||||
* Info.UNKNOWN: Package status is unknown
|
||||
* Info.INSTALLED: Package is installed
|
||||
* Info.AVAILABLE: Package is available to be installed
|
||||
* Info.LOW:
|
||||
* Info.ENHANCEMENT:
|
||||
* Info.NORMAL:
|
||||
* Info.BUGFIX:
|
||||
* Info.IMPORTANT:
|
||||
* Info.SECURITY:
|
||||
* Info.BLOCKED: Package is blocked
|
||||
* Info.DOWNLOADING: Package is downloading
|
||||
* Info.UPDATING: Package is updating
|
||||
* Info.INSTALLING: Package is being installed
|
||||
* Info.REMOVING: Package is being removed
|
||||
* Info.CLEANUP: Package is running cleanup
|
||||
* Info.OBSOLETING:
|
||||
* Info.COLLECTION_INSTALLED:
|
||||
* Info.COLLECTION_AVAILABLE:
|
||||
* Info.FINISHED:
|
||||
* Info.REINSTALLING: Package is being reinstalled
|
||||
* Info.DOWNGRADING: Package is being downgraded
|
||||
* Info.PREPARING: Package is preparing for installation/removal
|
||||
* Info.DECOMPRESSING: Package is decompressing
|
||||
* Info.UNTRUSTED:
|
||||
* Info.TRUSTED:
|
||||
* Info.UNAVAILABLE: Package is unavailable
|
||||
* Info.CRITICAL: Update severity is critical; Since: 1.2.4
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
INSTALLED = auto()
|
||||
AVAILABLE = auto()
|
||||
LOW = auto()
|
||||
ENHANCEMENT = auto()
|
||||
NORMAL = auto()
|
||||
BUGFIX = auto()
|
||||
IMPORTANT = auto()
|
||||
SECURITY = auto()
|
||||
BLOCKED = auto()
|
||||
DOWNLOADING = auto()
|
||||
UPDATING = auto()
|
||||
INSTALLING = auto()
|
||||
REMOVING = auto()
|
||||
CLEANUP = auto()
|
||||
OBSOLETING = auto()
|
||||
COLLECTION_INSTALLED = auto()
|
||||
COLLECTION_AVAILABLE = auto()
|
||||
FINISHED = auto()
|
||||
REINSTALLING = auto()
|
||||
DOWNGRADING = auto()
|
||||
PREPARING = auto()
|
||||
DECOMPRESSING = auto()
|
||||
UNTRUSTED = auto()
|
||||
TRUSTED = auto()
|
||||
UNAVAILABLE = auto()
|
||||
CRITICAL = auto()
|
||||
|
||||
class DistroUpgrade(PkFlag):
|
||||
"""
|
||||
The distro upgrade status
|
||||
|
||||
* DistroUpgrade.UNKNOWN: Unknown disto upgrade state
|
||||
* DistroUpgrade.STABLE: Upgraded to stable release
|
||||
* DistroUpgrade.UNSTABLE: Upgraded to unstable release
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
STABLE = auto()
|
||||
UNSTABLE = auto()
|
||||
|
||||
class SigType(PkFlag):
|
||||
"""
|
||||
The signature type type
|
||||
|
||||
* SigType.UNKNOWN: Unkwown signature type
|
||||
* SigType.GPG: GPG signature
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
GPG = auto()
|
||||
|
||||
class MediaType(PkFlag):
|
||||
"""
|
||||
The media type
|
||||
|
||||
* MediaType.UNKNOWN: Unknown media type
|
||||
* MediaType.CD: Media is a CD
|
||||
* MediaType.DVD: Media is a DVD
|
||||
* MediaType.DISC: Media is a disc (not CD or DVD)
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
CD = auto()
|
||||
DVD = auto()
|
||||
DISC = auto()
|
||||
|
||||
class Authorize(PkFlag):
|
||||
"""
|
||||
The authorization result
|
||||
|
||||
* Authorize.UNKNOWN: Unknown authorization status
|
||||
* Authorize.YES: Authorized
|
||||
* Authorize.NO: Not authorized
|
||||
* Authorize.INTERACTIVE: Interaction required for authorization
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
YES = auto()
|
||||
NO = auto()
|
||||
INTERACTIVE = auto()
|
||||
|
||||
class UpgradeKind(PkFlag):
|
||||
"""
|
||||
The type of distribution upgrade to perform
|
||||
|
||||
* UpgradeKind.UNKNOWN:
|
||||
* UpgradeKind.MINIMAL: Perform minimal upgrade
|
||||
* UpgradeKind.DEFAULT: Perform default upgrade
|
||||
* UpgradeKind.COMPLETE: Perform complete upgrade
|
||||
"""
|
||||
UNKNOWN = auto()
|
||||
MINIMAL = auto()
|
||||
DEFAULT = auto()
|
||||
COMPLETE = auto()
|
||||
|
||||
class TransactionFlag(PkFlag):
|
||||
"""
|
||||
The transaction flags that alter how the transaction is handled
|
||||
|
||||
* TransactionFlag.NONE: No transaction flag
|
||||
* TransactionFlag.ONLY_TRUSTED: Only allow trusted packages
|
||||
* TransactionFlag.SIMULATE: Simulate transaction
|
||||
* TransactionFlag.ONLY_DOWNLOAD: Only download packages
|
||||
* TransactionFlag.ALLOW_REINSTALL: Allow package reinstallation
|
||||
* TransactionFlag.JUST_REINSTALL: Only allow package reinstallation
|
||||
* TransactionFlag.ALLOW_DOWNGRADE: Allow packages to be downgraded
|
||||
"""
|
||||
NONE = auto()
|
||||
ONLY_TRUSTED = auto()
|
||||
SIMULATE = auto()
|
||||
ONLY_DOWNLOAD = auto()
|
||||
ALLOW_REINSTALL = auto()
|
||||
JUST_REINSTALL = auto()
|
||||
ALLOW_DOWNGRADE = auto()
|
||||
@@ -1,70 +0,0 @@
|
||||
# General Server Utilities
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
class ServerError(Exception):
|
||||
def __init__(self, message, status_code=400):
|
||||
Exception.__init__(self, message)
|
||||
self.status_code = status_code
|
||||
|
||||
# XXX - Currently logging over the socket is not implemented.
|
||||
# I don't think it would be wise to log everything over the
|
||||
# socket, however it may be useful to log some specific items.
|
||||
# Decide what to do, then either finish the implementation or
|
||||
# remove this code
|
||||
class SocketLoggingHandler(logging.Handler):
|
||||
def __init__(self, server_manager):
|
||||
super(SocketLoggingHandler, self).__init__()
|
||||
self.server_manager = server_manager
|
||||
|
||||
def emit(self, record):
|
||||
record.msg = "[MOONRAKER]: " + record.msg
|
||||
# XXX - Convert log record to dict before sending,
|
||||
# the klippy_send function will handle serialization
|
||||
|
||||
self.server_manager.klippy_send(record)
|
||||
|
||||
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
|
||||
def __init__(self, filename, **kwargs):
|
||||
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
|
||||
self.header = "Moonraker Log Start...\n"
|
||||
self.header += "Git Version: " + get_software_version() + "\n"
|
||||
self.header += "="*80 + "\n"
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
|
||||
def doRollover(self):
|
||||
super(MoonrakerLoggingHandler, self).doRollover()
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
|
||||
# Parse the git version from the command line. This code
|
||||
# is borrowed from Klipper.
|
||||
def get_software_version():
|
||||
moonraker_path = os.path.join(
|
||||
os.path.dirname(__file__), '..')
|
||||
|
||||
# Obtain version info from "git" program
|
||||
prog = ('git', '-C', moonraker_path, 'describe', '--always',
|
||||
'--tags', '--long', '--dirty', "--all")
|
||||
try:
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
ver, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode == 0:
|
||||
version = ver.strip()
|
||||
if isinstance(version, bytes):
|
||||
version = version.decode()
|
||||
return version
|
||||
else:
|
||||
logging.debug("Error getting git version: %s", err)
|
||||
except OSError:
|
||||
logging.exception("Error runing git describe")
|
||||
|
||||
return "?"
|
||||
@@ -0,0 +1,196 @@
|
||||
# General Server Utilities
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import os
|
||||
import glob
|
||||
import importlib
|
||||
import pathlib
|
||||
import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
import re
|
||||
import struct
|
||||
import socket
|
||||
import enum
|
||||
from . import source_info
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
List,
|
||||
Optional,
|
||||
ClassVar,
|
||||
Tuple,
|
||||
Dict,
|
||||
Union
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from types import ModuleType
|
||||
from asyncio.trsock import TransportSocket
|
||||
|
||||
SYS_MOD_PATHS = glob.glob("/usr/lib/python3*/dist-packages")
|
||||
SYS_MOD_PATHS += glob.glob("/usr/lib/python3*/site-packages")
|
||||
|
||||
class ServerError(Exception):
|
||||
def __init__(self, message: str, status_code: int = 400) -> None:
|
||||
Exception.__init__(self, message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class Sentinel(enum.Enum):
|
||||
MISSING = object()
|
||||
|
||||
def _run_git_command(cmd: str) -> str:
|
||||
prog = shlex.split(cmd)
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
ret, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode == 0:
|
||||
return ret.strip().decode()
|
||||
raise Exception(f"Failed to run git command: {cmd}")
|
||||
|
||||
def _retrieve_git_tag(source_path: str) -> str:
|
||||
cmd = f"git -C {source_path} rev-list --tags --max-count=1"
|
||||
hash = _run_git_command(cmd)
|
||||
cmd = f"git -C {source_path} describe --tags {hash}"
|
||||
tag = _run_git_command(cmd)
|
||||
cmd = f"git -C {source_path} rev-list {tag}..HEAD --count"
|
||||
count = _run_git_command(cmd)
|
||||
return f"{tag}-{count}"
|
||||
|
||||
# Parse the git version from the command line. This code
|
||||
# is borrowed from Klipper.
|
||||
def retrieve_git_version(source_path: str) -> str:
|
||||
# Obtain version info from "git" program
|
||||
cmd = f"git -C {source_path} describe --always --tags --long --dirty"
|
||||
ver = _run_git_command(cmd)
|
||||
tag_match = re.match(r"v\d+\.\d+\.\d+", ver)
|
||||
if tag_match is not None:
|
||||
return ver
|
||||
# This is likely a shallow clone. Resolve the tag and manually create
|
||||
# the version string
|
||||
tag = _retrieve_git_tag(source_path)
|
||||
return f"t{tag}-g{ver}-shallow"
|
||||
|
||||
def get_software_version() -> str:
|
||||
pkg_ver = source_info.package_version()
|
||||
if pkg_ver is not None:
|
||||
return pkg_ver
|
||||
version: str = "?"
|
||||
src_path = source_info.source_path()
|
||||
try:
|
||||
version = retrieve_git_version(str(src_path))
|
||||
except Exception:
|
||||
vfile = src_path.joinpath("moonraker/.version")
|
||||
if vfile.exists():
|
||||
try:
|
||||
version = vfile.read_text().strip()
|
||||
except Exception:
|
||||
logging.exception("Unable to extract version from file")
|
||||
version = "?"
|
||||
return version
|
||||
|
||||
|
||||
def hash_directory(
|
||||
dir_path: Union[str, pathlib.Path],
|
||||
ignore_exts: List[str],
|
||||
ignore_dirs: List[str]
|
||||
) -> str:
|
||||
if isinstance(dir_path, str):
|
||||
dir_path = pathlib.Path(dir_path)
|
||||
checksum = hashlib.blake2s()
|
||||
if not dir_path.exists():
|
||||
return ""
|
||||
for dpath, dnames, fnames in os.walk(dir_path):
|
||||
valid_dirs: List[str] = []
|
||||
for dname in sorted(dnames):
|
||||
if dname[0] == '.' or dname in ignore_dirs:
|
||||
continue
|
||||
valid_dirs.append(dname)
|
||||
dnames[:] = valid_dirs
|
||||
for fname in sorted(fnames):
|
||||
ext = os.path.splitext(fname)[-1].lower()
|
||||
if fname[0] == '.' or ext in ignore_exts:
|
||||
continue
|
||||
fpath = pathlib.Path(os.path.join(dpath, fname))
|
||||
try:
|
||||
checksum.update(fpath.read_bytes())
|
||||
except Exception:
|
||||
pass
|
||||
return checksum.hexdigest()
|
||||
|
||||
def verify_source(
|
||||
path: Optional[Union[str, pathlib.Path]] = None
|
||||
) -> Optional[Tuple[str, bool]]:
|
||||
if path is None:
|
||||
path = source_info.source_path()
|
||||
elif isinstance(path, str):
|
||||
path = pathlib.Path(path)
|
||||
rfile = path.joinpath(".release_info")
|
||||
if not rfile.exists():
|
||||
return None
|
||||
try:
|
||||
rinfo = json.loads(rfile.read_text())
|
||||
except Exception:
|
||||
return None
|
||||
orig_chksum = rinfo['source_checksum']
|
||||
ign_dirs = rinfo['ignored_dirs']
|
||||
ign_exts = rinfo['ignored_exts']
|
||||
checksum = hash_directory(path, ign_exts, ign_dirs)
|
||||
return checksum, checksum == orig_chksum
|
||||
|
||||
def load_system_module(name: str) -> ModuleType:
|
||||
for module_path in SYS_MOD_PATHS:
|
||||
sys.path.insert(0, module_path)
|
||||
try:
|
||||
module = importlib.import_module(name)
|
||||
except ImportError as e:
|
||||
if not isinstance(e, ModuleNotFoundError):
|
||||
logging.exception(f"Failed to load {name} module")
|
||||
sys.path.pop(0)
|
||||
else:
|
||||
sys.path.pop(0)
|
||||
break
|
||||
else:
|
||||
raise ServerError(f"Unable to import module {name}")
|
||||
return module
|
||||
|
||||
def get_unix_peer_credentials(
|
||||
writer: asyncio.StreamWriter, name: str
|
||||
) -> Dict[str, int]:
|
||||
sock: TransportSocket
|
||||
sock = writer.get_extra_info("socket", None)
|
||||
if sock is None:
|
||||
logging.debug(
|
||||
f"Unable to get underlying Unix Socket for {name}, "
|
||||
"cant fetch peer credentials"
|
||||
)
|
||||
return {}
|
||||
data: bytes = b""
|
||||
try:
|
||||
size = struct.calcsize("3I")
|
||||
data = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, size)
|
||||
pid, uid, gid = struct.unpack("3I", data)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Failed to get Unix Socket Peer Credentials for {name}"
|
||||
f", raw: 0x{data.hex()}"
|
||||
)
|
||||
return {}
|
||||
return {
|
||||
"process_id": pid,
|
||||
"user_id": uid,
|
||||
"group_id": gid
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
# General Server Utilities
|
||||
#
|
||||
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import importlib.resources as ilr
|
||||
import pathlib
|
||||
import sys
|
||||
import site
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
Optional,
|
||||
)
|
||||
|
||||
def package_path() -> pathlib.Path:
|
||||
return pathlib.Path(__file__).parent.parent
|
||||
|
||||
def source_path() -> pathlib.Path:
|
||||
return package_path().parent
|
||||
|
||||
def is_git_repo(src_path: Optional[pathlib.Path] = None) -> bool:
|
||||
if src_path is None:
|
||||
return source_path().joinpath(".git").is_dir()
|
||||
return src_path.joinpath(".git").is_dir()
|
||||
|
||||
def is_dist_package(src_path: Optional[pathlib.Path] = None) -> bool:
|
||||
if src_path is None:
|
||||
# Fetch dist info for moonraker. This should be the most reliable
|
||||
# method
|
||||
src_path = source_path()
|
||||
site_dirs = site.getsitepackages()
|
||||
return str(src_path) in site_dirs
|
||||
else:
|
||||
# Make an assumption based on the source path. If its name is
|
||||
# site-packages or dist-packages then presumably it is an
|
||||
# installed package
|
||||
return src_path.name in ["dist-packages", "site-packages"]
|
||||
|
||||
def package_version() -> Optional[str]:
|
||||
try:
|
||||
import moonraker.__version__ as ver # type: ignore
|
||||
version = ver.__version__
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
if version:
|
||||
return version
|
||||
return None
|
||||
|
||||
def read_asset(asset_name: str) -> Optional[str]:
|
||||
if sys.version_info < (3, 10):
|
||||
with ilr.path("moonraker.assets", asset_name) as p:
|
||||
if not p.is_file():
|
||||
return None
|
||||
return p.read_text()
|
||||
else:
|
||||
files = ilr.files("moonraker.assets")
|
||||
with ilr.as_file(files.joinpath(asset_name)) as p:
|
||||
if not p.is_file():
|
||||
return None
|
||||
return p.read_text()
|
||||
|
||||
def get_asset_path() -> Optional[pathlib.Path]:
|
||||
if sys.version_info < (3, 10):
|
||||
with ilr.path("moonraker.assets", "__init__.py") as p:
|
||||
asset_path = p.parent
|
||||
else:
|
||||
files = ilr.files("moonraker.assets")
|
||||
with ilr.as_file(files.joinpath("__init__.py")) as p:
|
||||
asset_path = p.parent
|
||||
if not asset_path.is_dir():
|
||||
# Somehow running in a zipapp. This is an error.
|
||||
return None
|
||||
return asset_path
|
||||
+923
-167
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,674 @@
|
||||
# This file is @generated by PDM.
|
||||
# It is not intended for manual editing.
|
||||
|
||||
[[package]]
|
||||
name = "apprise"
|
||||
version = "1.2.1"
|
||||
requires_python = ">=3.6"
|
||||
summary = "Push Notifications that work with just about every platform!"
|
||||
dependencies = [
|
||||
"PyYAML",
|
||||
"certifi",
|
||||
"click>=5.0",
|
||||
"markdown",
|
||||
"requests",
|
||||
"requests-oauthlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-timeout"
|
||||
version = "4.0.2"
|
||||
requires_python = ">=3.6"
|
||||
summary = "Timeout context manager for asyncio programs"
|
||||
dependencies = [
|
||||
"typing-extensions>=3.6.5; python_version < \"3.8\"",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2022.12.7"
|
||||
requires_python = ">=3.6"
|
||||
summary = "Python package for providing Mozilla's CA Bundle."
|
||||
|
||||
[[package]]
|
||||
name = "charset-normalizer"
|
||||
version = "3.0.1"
|
||||
summary = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
|
||||
|
||||
[[package]]
|
||||
name = "click"
|
||||
version = "8.1.3"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Composable command line interface toolkit"
|
||||
dependencies = [
|
||||
"colorama; platform_system == \"Windows\"",
|
||||
"importlib-metadata; python_version < \"3.8\"",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "colorama"
|
||||
version = "0.4.6"
|
||||
requires_python = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
|
||||
summary = "Cross-platform colored terminal text."
|
||||
|
||||
[[package]]
|
||||
name = "dbus-next"
|
||||
version = "0.2.3"
|
||||
requires_python = ">=3.6.0"
|
||||
summary = "A zero-dependency DBus library for Python with asyncio support"
|
||||
|
||||
[[package]]
|
||||
name = "distro"
|
||||
version = "1.8.0"
|
||||
requires_python = ">=3.6"
|
||||
summary = "Distro - an OS platform information API"
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "3.4"
|
||||
requires_python = ">=3.5"
|
||||
summary = "Internationalized Domain Names in Applications (IDNA)"
|
||||
|
||||
[[package]]
|
||||
name = "ifaddr"
|
||||
version = "0.2.0"
|
||||
summary = "Cross-platform network interface and IP address enumeration library"
|
||||
|
||||
[[package]]
|
||||
name = "importlib-metadata"
|
||||
version = "6.0.0"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Read metadata from Python packages"
|
||||
dependencies = [
|
||||
"typing-extensions>=3.6.4; python_version < \"3.8\"",
|
||||
"zipp>=0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify-simple"
|
||||
version = "1.3.5"
|
||||
requires_python = ">=2.7, !=3.0.*, !=3.1.*"
|
||||
summary = "A simple wrapper around inotify. No fancy bells and whistles, just a literal wrapper with ctypes. Under 100 lines of code!"
|
||||
|
||||
[[package]]
|
||||
name = "jinja2"
|
||||
version = "3.1.2"
|
||||
requires_python = ">=3.7"
|
||||
summary = "A very fast and expressive template engine."
|
||||
dependencies = [
|
||||
"MarkupSafe>=2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ldap3"
|
||||
version = "2.9.1"
|
||||
summary = "A strictly RFC 4510 conforming LDAP V3 pure Python client library"
|
||||
dependencies = [
|
||||
"pyasn1>=0.4.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libnacl"
|
||||
version = "1.8.0"
|
||||
summary = "Python bindings for libsodium based on ctypes"
|
||||
|
||||
[[package]]
|
||||
name = "lmdb"
|
||||
version = "1.3.0"
|
||||
summary = "Universal Python binding for the LMDB 'Lightning' Database"
|
||||
|
||||
[[package]]
|
||||
name = "markdown"
|
||||
version = "3.4.1"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Python implementation of Markdown."
|
||||
dependencies = [
|
||||
"importlib-metadata>=4.4; python_version < \"3.10\"",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "markupsafe"
|
||||
version = "2.1.2"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Safely add untrusted strings to HTML/XML markup."
|
||||
|
||||
[[package]]
|
||||
name = "oauthlib"
|
||||
version = "3.2.2"
|
||||
requires_python = ">=3.6"
|
||||
summary = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic"
|
||||
|
||||
[[package]]
|
||||
name = "paho-mqtt"
|
||||
version = "1.6.1"
|
||||
summary = "MQTT version 5.0/3.1.1 client class"
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "9.3.0"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Python Imaging Library (Fork)"
|
||||
|
||||
[[package]]
|
||||
name = "preprocess-cancellation"
|
||||
version = "0.2.0"
|
||||
requires_python = ">=3.6.2"
|
||||
summary = "GCode processor to add klipper cancel-object markers"
|
||||
|
||||
[[package]]
|
||||
name = "pyasn1"
|
||||
version = "0.4.8"
|
||||
summary = "ASN.1 types and codecs"
|
||||
|
||||
[[package]]
|
||||
name = "pyserial"
|
||||
version = "3.4"
|
||||
summary = "Python Serial Port Extension"
|
||||
|
||||
[[package]]
|
||||
name = "pyserial-asyncio"
|
||||
version = "0.6"
|
||||
summary = "Python Serial Port Extension - Asynchronous I/O support"
|
||||
dependencies = [
|
||||
"pyserial",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyyaml"
|
||||
version = "6.0"
|
||||
requires_python = ">=3.6"
|
||||
summary = "YAML parser and emitter for Python"
|
||||
|
||||
[[package]]
|
||||
name = "requests"
|
||||
version = "2.28.2"
|
||||
requires_python = ">=3.7, <4"
|
||||
summary = "Python HTTP for Humans."
|
||||
dependencies = [
|
||||
"certifi>=2017.4.17",
|
||||
"charset-normalizer<4,>=2",
|
||||
"idna<4,>=2.5",
|
||||
"urllib3<1.27,>=1.21.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "requests-oauthlib"
|
||||
version = "1.3.1"
|
||||
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
|
||||
summary = "OAuthlib authentication support for Requests."
|
||||
dependencies = [
|
||||
"oauthlib>=3.0.0",
|
||||
"requests>=2.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "streaming-form-data"
|
||||
version = "1.11.0"
|
||||
requires_python = ">=3.6"
|
||||
summary = "Streaming parser for multipart/form-data"
|
||||
|
||||
[[package]]
|
||||
name = "tornado"
|
||||
version = "6.2"
|
||||
requires_python = ">= 3.7"
|
||||
summary = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed."
|
||||
|
||||
[[package]]
|
||||
name = "typing-extensions"
|
||||
version = "4.4.0"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Backported and Experimental Type Hints for Python 3.7+"
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "1.26.14"
|
||||
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"
|
||||
summary = "HTTP library with thread-safe connection pooling, file post, and more."
|
||||
|
||||
[[package]]
|
||||
name = "zeroconf"
|
||||
version = "0.39.4"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Pure Python Multicast DNS Service Discovery Library (Bonjour/Avahi compatible)"
|
||||
dependencies = [
|
||||
"async-timeout>=4.0.1",
|
||||
"ifaddr>=0.1.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zipp"
|
||||
version = "3.13.0"
|
||||
requires_python = ">=3.7"
|
||||
summary = "Backport of pathlib-compatible object wrapper for zip files"
|
||||
|
||||
[metadata]
|
||||
lock_version = "4.1"
|
||||
content_hash = "sha256:0e54d8cb135fb11f1588c0d0208221cfcdbae6d54ed3ffa43012ec460bae6b34"
|
||||
|
||||
[metadata.files]
|
||||
"apprise 1.2.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/a4/3a/52ec5cf9ed71e3a068a208603e38471b686a59b548dda771f2975166e4a9/apprise-1.2.1-py2.py3-none-any.whl", hash = "sha256:679fb5d6232ec7748eef308bda9fe0f0707fa5e48eab247bfde83c3a024a21d1"},
|
||||
{url = "https://files.pythonhosted.org/packages/d2/04/4285d864569dde4eece4b0e7bfa447a68e99240898537b10926cb5a53145/apprise-1.2.1.tar.gz", hash = "sha256:67e0c227eecee260000980dbbf8ba1e5eebdbe494f4730808297c9e645c03579"},
|
||||
]
|
||||
"async-timeout 4.0.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/54/6e/9678f7b2993537452710ffb1750c62d2c26df438aa621ad5fa9d1507a43a/async-timeout-4.0.2.tar.gz", hash = "sha256:2163e1640ddb52b7a8c80d0a67a08587e5d245cc9c553a74a847056bc2976b15"},
|
||||
{url = "https://files.pythonhosted.org/packages/d6/c1/8991e7c5385b897b8c020cdaad718c5b087a6626d1d11a23e1ea87e325a7/async_timeout-4.0.2-py3-none-any.whl", hash = "sha256:8ca1e4fcf50d07413d66d1a5e416e42cfdf5851c981d679a09851a6853383b3c"},
|
||||
]
|
||||
"certifi 2022.12.7" = [
|
||||
{url = "https://files.pythonhosted.org/packages/37/f7/2b1b0ec44fdc30a3d31dfebe52226be9ddc40cd6c0f34ffc8923ba423b69/certifi-2022.12.7.tar.gz", hash = "sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3"},
|
||||
{url = "https://files.pythonhosted.org/packages/71/4c/3db2b8021bd6f2f0ceb0e088d6b2d49147671f25832fb17970e9b583d742/certifi-2022.12.7-py3-none-any.whl", hash = "sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18"},
|
||||
]
|
||||
"charset-normalizer 3.0.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/00/35/830c29e5dab61932224c7a6c89427090164a3e425cf03486ce7a3ce60623/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9d9153257a3f70d5f69edf2325357251ed20f772b12e593f3b3377b5f78e7ef8"},
|
||||
{url = "https://files.pythonhosted.org/packages/01/ff/9ee4a44e8c32fe96dfc12daa42f29294608a55eadc88f327939327fb20fb/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:72966d1b297c741541ca8cf1223ff262a6febe52481af742036a0b296e35fa5a"},
|
||||
{url = "https://files.pythonhosted.org/packages/02/49/78b4c1bc8b1b0e0fc66fb31ce30d8302f10a1412ba75de72c57532f0beb0/charset_normalizer-3.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:87701167f2a5c930b403e9756fab1d31d4d4da52856143b609e30a1ce7160f3c"},
|
||||
{url = "https://files.pythonhosted.org/packages/03/5e/e81488c74e86eef85cf085417ed945da2dcca87ed22d76202680c16bd3c3/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:39049da0ffb96c8cbb65cbf5c5f3ca3168990adf3551bd1dee10c48fce8ae820"},
|
||||
{url = "https://files.pythonhosted.org/packages/0b/8b/3cf0eff3c8b6734cd4336c23a3141846d579931a31e6476c8091961f1e25/charset_normalizer-3.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:eaa379fcd227ca235d04152ca6704c7cb55564116f8bc52545ff357628e10602"},
|
||||
{url = "https://files.pythonhosted.org/packages/0e/d3/c5fa421dc69bb77c581ed561f1ec6656109c97731ad1128aa93d8bad3053/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:024e606be3ed92216e2b6952ed859d86b4cfa52cd5bc5f050e7dc28f9b43ec42"},
|
||||
{url = "https://files.pythonhosted.org/packages/0e/fd/0d099502582af039ef8a8c954d69d7dadbe5f425cb1b24d175eb0034ea9e/charset_normalizer-3.0.1-cp37-cp37m-win32.whl", hash = "sha256:0bf2dae5291758b6f84cf923bfaa285632816007db0330002fa1de38bfcb7154"},
|
||||
{url = "https://files.pythonhosted.org/packages/0f/45/f462f534dd2853ebbc186ed859661db454665b1dc9ae6c690d982153cda9/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:503e65837c71b875ecdd733877d852adbc465bd82c768a067badd953bf1bc5a3"},
|
||||
{url = "https://files.pythonhosted.org/packages/12/e5/aa09a1c39c3e444dd223d63e2c816c18ed78d035cff954143b2a539bdc9e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0a590235ccd933d9892c627dec5bc7511ce6ad6c1011fdf5b11363022746c1"},
|
||||
{url = "https://files.pythonhosted.org/packages/16/bd/671f11f920dfb46de848e9176d84ddb25b3bbdffac6751cbbf691c0b5b17/charset_normalizer-3.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3e45867f1f2ab0711d60c6c71746ac53537f1684baa699f4f668d4c6f6ce8e14"},
|
||||
{url = "https://files.pythonhosted.org/packages/17/67/4b25c0358a2e812312b551e734d58855d58f47d0e0e9d1573930003910cb/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8eade758719add78ec36dc13201483f8e9b5d940329285edcd5f70c0a9edbd7f"},
|
||||
{url = "https://files.pythonhosted.org/packages/17/da/fdf8ffc33716c82cae06008159a55a581fa515e8dd02e3395dcad42ff83d/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81d6741ab457d14fdedc215516665050f3822d3e56508921cc7239f8c8e66a58"},
|
||||
{url = "https://files.pythonhosted.org/packages/20/a2/16b2cbf5f73bdd10624b94647b85c008ba25059792a5c7b4fdb8358bceeb/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e696f0dd336161fca9adbb846875d40752e6eba585843c768935ba5c9960722b"},
|
||||
{url = "https://files.pythonhosted.org/packages/25/19/298089cef2eb82fd3810d982aa239d4226594f99e1fe78494cb9b47b03c9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:0f438ae3532723fb6ead77e7c604be7c8374094ef4ee2c5e03a3a17f1fca256c"},
|
||||
{url = "https://files.pythonhosted.org/packages/25/b5/f477e419b06e49f3bae446cbdc1fd71d2599be8b12b4d45c641c5a4495b1/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:911d8a40b2bef5b8bbae2e36a0b103f142ac53557ab421dc16ac4aafee6f53dc"},
|
||||
{url = "https://files.pythonhosted.org/packages/27/b1/8dfcfa5d9978b845466cd41973b3d714eba3926fcb50f6fcddd45cfb75a2/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:083c8d17153ecb403e5e1eb76a7ef4babfc2c48d58899c98fcaa04833e7a2f9a"},
|
||||
{url = "https://files.pythonhosted.org/packages/2d/02/0f875eb6a1cf347bd3a6098f458f79796aafa3b51090fd7b2784736dc67d/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:44ba614de5361b3e5278e1241fda3dc1838deed864b50a10d7ce92983797fa76"},
|
||||
{url = "https://files.pythonhosted.org/packages/2e/7b/5053a4a46fac017fd2aea3dc9abdd9983fd4cef153b6eb6aedcb0d7cb6e3/charset_normalizer-3.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:9ab77acb98eba3fd2a85cd160851816bfce6871d944d885febf012713f06659c"},
|
||||
{url = "https://files.pythonhosted.org/packages/31/06/f6330ee70c041a032ee1a5d32785d69748cfa41f64b6d327cc08cae51de9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ab5de034a886f616a5668aa5d098af2b5385ed70142090e2a31bcbd0af0fdb3d"},
|
||||
{url = "https://files.pythonhosted.org/packages/31/af/67b7653a35dbd56f6bb9ff54652a551eae8420d1d0545f0042c5bdb15fb0/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f6f45710b4459401609ebebdbcfb34515da4fc2aa886f95107f556ac69a9147e"},
|
||||
{url = "https://files.pythonhosted.org/packages/35/86/d85885ed7ac236a297b0b8beab5f0703fc0516f803ddf7b1910f255b83f3/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:7eb33a30d75562222b64f569c642ff3dc6689e09adda43a082208397f016c39a"},
|
||||
{url = "https://files.pythonhosted.org/packages/37/00/ca188e0a2b3cd3184cdd2521b8765cf579327d128caa8aedc3dc7614020a/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0298eafff88c99982a4cf66ba2efa1128e4ddaca0b05eec4c456bbc7db691d8d"},
|
||||
{url = "https://files.pythonhosted.org/packages/37/60/7a01f3a129d1af1f26ab2c56aae89a72dbf33fd46a467c1aa994ec62b90b/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8af03d2e37866d023ad0ddea594edefc31e827fee64f8de5611a1dbc373174"},
|
||||
{url = "https://files.pythonhosted.org/packages/3a/91/a233f06d33dc3ac90a9991d238fbc68c59615d9f71be1801e14ac4e42d7f/charset_normalizer-3.0.1-cp38-cp38-win32.whl", hash = "sha256:4457ea6774b5611f4bed5eaa5df55f70abde42364d498c5134b7ef4c6958e20e"},
|
||||
{url = "https://files.pythonhosted.org/packages/46/69/9f42514a9f58c602ab89a2af89081a475dccd959f9bc01ba7e61372d31bd/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c95a03c79bbe30eec3ec2b7f076074f4281526724c8685a42872974ef4d36b72"},
|
||||
{url = "https://files.pythonhosted.org/packages/55/2b/35619e03725bfa4af4a902e1996c9ee8052d6bce005ff79c9bd988820cb4/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:31a9ddf4718d10ae04d9b18801bd776693487cbb57d74cc3458a7673f6f34639"},
|
||||
{url = "https://files.pythonhosted.org/packages/56/5d/275fb120957dfe5a2262d04f28bc742fd4bcc2bd270d19bb8757e09737ef/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9cf4e8ad252f7c38dd1f676b46514f92dc0ebeb0db5552f5f403509705e24753"},
|
||||
{url = "https://files.pythonhosted.org/packages/5a/d8/9e76846e70e729de85ecc6af21edc584a2adfef202dc5f5ae00a02622e3d/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:11b53acf2411c3b09e6af37e4b9005cba376c872503c8f28218c7243582df45d"},
|
||||
{url = "https://files.pythonhosted.org/packages/5b/e7/5527effca09d873e07e128d3daac7c531203b5105cb4e2956c2b7a8cc41c/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:109487860ef6a328f3eec66f2bf78b0b72400280d8f8ea05f69c51644ba6521a"},
|
||||
{url = "https://files.pythonhosted.org/packages/67/c6/cf4e8a8f41201284bdf200f764b29a87f6f7d22fe3c9eddab602af489acc/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:cd6056167405314a4dc3c173943f11249fa0f1b204f8b51ed4bde1a9cd1834dc"},
|
||||
{url = "https://files.pythonhosted.org/packages/68/2b/02e9d6a98ddb73fa238d559a9edcc30b247b8dc4ee848b6184c936e99dc0/charset_normalizer-3.0.1-py3-none-any.whl", hash = "sha256:7e189e2e1d3ed2f4aebabd2d5b0f931e883676e51c7624826e0a4e5fe8a0bf24"},
|
||||
{url = "https://files.pythonhosted.org/packages/6a/ab/3a00ecbddabe25132c20c1bd45e6f90c537b5f7a0b5bcaba094c4922928c/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8499ca8f4502af841f68135133d8258f7b32a53a1d594aa98cc52013fff55678"},
|
||||
{url = "https://files.pythonhosted.org/packages/6e/a3/997ff79260f76210b1d73463b9081ae7edbf16ff3d611b67f5e72c685cab/charset_normalizer-3.0.1-cp39-cp39-win32.whl", hash = "sha256:39cf9ed17fe3b1bc81f33c9ceb6ce67683ee7526e65fde1447c772afc54a1bb8"},
|
||||
{url = "https://files.pythonhosted.org/packages/6e/d7/1d4035fcbf7d0f2e89588a142628355d8d1cd652a227acefb9ec85908cd4/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:772b87914ff1152b92a197ef4ea40efe27a378606c39446ded52c8f80f79702e"},
|
||||
{url = "https://files.pythonhosted.org/packages/71/67/79be03bf7ab4198d994c2e8da869ca354487bfa25656b95cf289cf6338a2/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:16a8663d6e281208d78806dbe14ee9903715361cf81f6d4309944e4d1e59ac5b"},
|
||||
{url = "https://files.pythonhosted.org/packages/80/54/183163f9910936e57a60ee618f4f5cc91c2f8333ee2d4ebc6c50f6c8684d/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4a8fcf28c05c1f6d7e177a9a46a1c52798bfe2ad80681d275b10dcf317deaf0b"},
|
||||
{url = "https://files.pythonhosted.org/packages/82/49/ab81421d5aa25bc8535896a017c93204cb4051f2a4e72b1ad8f3b594e072/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:761e8904c07ad053d285670f36dd94e1b6ab7f16ce62b9805c475b7aa1cffde6"},
|
||||
{url = "https://files.pythonhosted.org/packages/84/0e/5965dd90991e4f2588718b865115a78c8b040193ac3676f757b7fb6af9d0/charset_normalizer-3.0.1-cp311-cp311-win32.whl", hash = "sha256:71140351489970dfe5e60fc621ada3e0f41104a5eddaca47a7acb3c1b851d6d3"},
|
||||
{url = "https://files.pythonhosted.org/packages/84/ff/78a4942ef1ea4d1c464cc9a132122b36c5390c5cf6301ed0f9e3e6e24bd9/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8ac7b6a045b814cf0c47f3623d21ebd88b3e8cf216a14790b455ea7ff0135d18"},
|
||||
{url = "https://files.pythonhosted.org/packages/86/eb/31c9025b4ed7eddd930c5f2ac269efb953de33140608c7539675d74a2081/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:5995f0164fa7df59db4746112fec3f49c461dd6b31b841873443bdb077c13cfc"},
|
||||
{url = "https://files.pythonhosted.org/packages/87/5d/0ebaee2249a04fd20bb4baeb9ea2c29dee17317175d9d67b4f5f34cf048d/charset_normalizer-3.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:e62164b50f84e20601c1ff8eb55620d2ad25fb81b59e3cd776a1902527a788af"},
|
||||
{url = "https://files.pythonhosted.org/packages/89/87/c237a299a658b35d19fd531eeb8247480627fc2fb4b7a471334b48850f45/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:f9d0c5c045a3ca9bedfc35dca8526798eb91a07aa7a2c0fee134c6c6f321cbd7"},
|
||||
{url = "https://files.pythonhosted.org/packages/8f/e2/73ea48d2608f71a879588b607e093d550b8eaa177eb31bbdf1c01e515818/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:f5057856d21e7586765171eac8b9fc3f7d44ef39425f85dbcccb13b3ebea806c"},
|
||||
{url = "https://files.pythonhosted.org/packages/90/2c/bb5e4f7e2e9871793b5c0fb5c6c4056458a148a05143143320f2d4a410a9/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:59e5686dd847347e55dffcc191a96622f016bc0ad89105e24c14e0d6305acbc6"},
|
||||
{url = "https://files.pythonhosted.org/packages/90/59/941e2e5ae6828a688c6437ad16e026eb3606d0cfdd13ea5c9090980f3ffd/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a8d0fc946c784ff7f7c3742310cc8a57c5c6dc31631269876a88b809dbeff3d3"},
|
||||
{url = "https://files.pythonhosted.org/packages/92/00/b8dc8dd725297b05f1ab4929c9d7e879f31746131534221c5c8948bc7563/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:12db3b2c533c23ab812c2b25934f60383361f8a376ae272665f8e48b88e8e1c6"},
|
||||
{url = "https://files.pythonhosted.org/packages/93/d1/569445a704414e150f198737c245ab96b40d28d5b68045a62c414a5157de/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:02a51034802cbf38db3f89c66fb5d2ec57e6fe7ef2f4a44d070a593c3688667b"},
|
||||
{url = "https://files.pythonhosted.org/packages/96/d7/1675d9089a1f4677df5eb29c3f8b064aa1e70c1251a0a8a127803158942d/charset-normalizer-3.0.1.tar.gz", hash = "sha256:ebea339af930f8ca5d7a699b921106c6e29c617fe9606fa7baa043c1cdae326f"},
|
||||
{url = "https://files.pythonhosted.org/packages/97/f9/366db2d2cf69d641159d6448b813ac9b1b5f9807a46fde6c50b36c1387f8/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:93ad6d87ac18e2a90b0fe89df7c65263b9a99a0eb98f0a3d2e079f12a0735837"},
|
||||
{url = "https://files.pythonhosted.org/packages/98/e4/d4685870fda1cc7c5e29899ec329500460418e54f4f5df76ee520e30689a/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c512accbd6ff0270939b9ac214b84fb5ada5f0409c44298361b2f5e13f9aed9e"},
|
||||
{url = "https://files.pythonhosted.org/packages/98/f4/5ca33ee1e0b3412cbd13eae230321a9fe819acf1a99ad6482420fb97cc6b/charset_normalizer-3.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:601f36512f9e28f029d9481bdaf8e89e5148ac5d89cffd3b05cd533eeb423b59"},
|
||||
{url = "https://files.pythonhosted.org/packages/99/24/eb846dc9a797da58e6e5b3b5a71d3ff17264de3f424fb29aaa5d27173b55/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3b590df687e3c5ee0deef9fc8c547d81986d9a1b56073d82de008744452d6541"},
|
||||
{url = "https://files.pythonhosted.org/packages/9a/bf/c9fa15ccf216a69aaaa735c961d7fac2a2801a1b01023fe05d194bf076b4/charset_normalizer-3.0.1-cp36-cp36m-win32.whl", hash = "sha256:95dea361dd73757c6f1c0a1480ac499952c16ac83f7f5f4f84f0658a01b8ef41"},
|
||||
{url = "https://files.pythonhosted.org/packages/9c/42/c1ebc736c57459aab28bfb8aa28c6a047796f2ea46050a3b129b4920dbe4/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4b0d02d7102dd0f997580b51edc4cebcf2ab6397a7edf89f1c73b586c614272c"},
|
||||
{url = "https://files.pythonhosted.org/packages/9c/94/1725fc3e0dbe8918a4ec6dd317ec1ef388e701bdfb5053e1f34f5c6d5a8e/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df2c707231459e8a4028eabcd3cfc827befd635b3ef72eada84ab13b52e1574d"},
|
||||
{url = "https://files.pythonhosted.org/packages/9f/5a/9dc8932d1e5f8eeaa502e3c3fce91c86be20c04eb3ec202d2b7d74b567e5/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2edb64ee7bf1ed524a1da60cdcd2e1f6e2b4f66ef7c077680739f1641f62f555"},
|
||||
{url = "https://files.pythonhosted.org/packages/a0/98/7b0d3a853af59e092cdd77c7e1c67ca92fd6acc126285240dbb552b4162f/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:74292fc76c905c0ef095fe11e188a32ebd03bc38f3f3e9bcb85e4e6db177b7ea"},
|
||||
{url = "https://files.pythonhosted.org/packages/a2/93/0b1aa4dbc0ae2aa2e1b2e6d037ab8984dc09912d6b26d63ced14da07e3a7/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a16418ecf1329f71df119e8a65f3aa68004a3f9383821edcb20f0702934d8087"},
|
||||
{url = "https://files.pythonhosted.org/packages/a2/a7/adc963ad8f8fddadd6be088e636972705ec9d1d92d1b45e6119eb02b7e9e/charset_normalizer-3.0.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:358a7c4cb8ba9b46c453b1dd8d9e431452d5249072e4f56cfda3149f6ab1405e"},
|
||||
{url = "https://files.pythonhosted.org/packages/a3/09/a837b27b122e710dfad15b0b5df04cd0623c8d8d3382e4298f50798fb84a/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:2e396d70bc4ef5325b72b593a72c8979999aa52fb8bcf03f701c1b03e1166918"},
|
||||
{url = "https://files.pythonhosted.org/packages/a3/4b/f565c852163312a0991c30598f403fd06796a12e408d7839cc46ca8d7f4a/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62595ab75873d50d57323a91dd03e6966eb79c41fa834b7a1661ed043b2d404d"},
|
||||
{url = "https://files.pythonhosted.org/packages/aa/a4/2d6255d4db5d4558a92458fd8dacddfdda2fb4ad9c0a87db6f6034aded34/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:f97e83fa6c25693c7a35de154681fcc257c1c41b38beb0304b9c4d2d9e164479"},
|
||||
{url = "https://files.pythonhosted.org/packages/af/63/2c00ff4e657fb9bb76306ffbc7878fd52067e39716f5e8b0dd5582caf1fa/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70990b9c51340e4044cfc394a81f614f3f90d41397104d226f21e66de668730d"},
|
||||
{url = "https://files.pythonhosted.org/packages/b2/4c/9a4f30042bfee22d34d80daf75f51817cdd23180d718e0160aab235c4faf/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:88600c72ef7587fe1708fd242b385b6ed4b8904976d5da0893e31df8b3480cb6"},
|
||||
{url = "https://files.pythonhosted.org/packages/b5/1a/932d86fde86bb0d2992c74552c9a422883fe0890132bbc9a5e2211f03318/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00d3ffdaafe92a5dc603cb9bd5111aaa36dfa187c8285c543be562e61b755f6b"},
|
||||
{url = "https://files.pythonhosted.org/packages/b6/c2/da108d835354b49aa5c738906e9b6a197b071bc5d77d223f6cd98119172a/charset_normalizer-3.0.1-cp310-cp310-win32.whl", hash = "sha256:502218f52498a36d6bf5ea77081844017bf7982cdbe521ad85e64cabee1b608b"},
|
||||
{url = "https://files.pythonhosted.org/packages/c0/4d/6b82099e3f25a9ed87431e2f51156c14f3a9ce8fad73880a3856cd95f1d5/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:14e76c0f23218b8f46c4d87018ca2e441535aed3632ca134b10239dfb6dadd6b"},
|
||||
{url = "https://files.pythonhosted.org/packages/c1/06/b7b1d3d186e0f288500b8a1161ede6b38a0abbf878c2033d667e815e6bd7/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:292d5e8ba896bbfd6334b096e34bffb56161c81408d6d036a7dfa6929cff8783"},
|
||||
{url = "https://files.pythonhosted.org/packages/c1/b2/d81606aebeb7e9a33dc877ff3a206c9946f5bb374c99d22d4a28825aa270/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a60332922359f920193b1d4826953c507a877b523b2395ad7bc716ddd386d866"},
|
||||
{url = "https://files.pythonhosted.org/packages/c4/d4/94f1ea460cce04483d2460efba6fd4d66e6f60ad6fc6075dba13e3501e48/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9cb3032517f1627cc012dbc80a8ec976ae76d93ea2b5feaa9d2a5b8882597579"},
|
||||
{url = "https://files.pythonhosted.org/packages/c8/a2/8f873138c99423de3b402daf8ccd7a538632c83d0c129444a6a18ef34e03/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c22d3fe05ce11d3671297dc8973267daa0f938b93ec716e12e0f6dee81591dc1"},
|
||||
{url = "https://files.pythonhosted.org/packages/c9/dd/80a5e8c080b7e1cc2b0ca35f0d6aeedafd7bbd06d25031ac20868b1366d6/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:608862a7bf6957f2333fc54ab4399e405baad0163dc9f8d99cb236816db169d4"},
|
||||
{url = "https://files.pythonhosted.org/packages/d2/7f/3c8a6db3eda16ce79a01552ec85ac8fd0ea6265976eb4db250a60b7416ab/charset_normalizer-3.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:84c3990934bae40ea69a82034912ffe5a62c60bbf6ec5bc9691419641d7d5c9a"},
|
||||
{url = "https://files.pythonhosted.org/packages/d3/5b/4031145fcfb9ceaf49dad2fbf9a44e062eb2c08aff36f71d8aafbecf4567/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ff6f3db31555657f3163b15a6b7c6938d08df7adbfc9dd13d9d19edad678f1e8"},
|
||||
{url = "https://files.pythonhosted.org/packages/d9/7a/60d45c9453212b30eebbf8b5cddbdef330eebddfcf335bce7920c43fb72e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79909e27e8e4fcc9db4addea88aa63f6423ebb171db091fb4373e3312cb6d603"},
|
||||
{url = "https://files.pythonhosted.org/packages/dc/ff/2c7655d83b1d6d6a0e132d50d54131fcb8da763b417ccc6c4a506aa0e08c/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2ac1b08635a8cd4e0cbeaf6f5e922085908d48eb05d44c5ae9eabab148512ca"},
|
||||
{url = "https://files.pythonhosted.org/packages/df/2f/4806e155191f75e720aca98a969581c6b2676f0379dd315c34c388bbf8b5/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cadaeaba78750d58d3cc6ac4d1fd867da6fc73c88156b7a3212a3cd4819d679d"},
|
||||
{url = "https://files.pythonhosted.org/packages/df/c5/dd3a17a615775d0ffc3e12b0e47833d8b7e0a4871431dad87a3f92382a19/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c7fe7afa480e3e82eed58e0ca89f751cd14d767638e2550c77a92a9e749c317"},
|
||||
{url = "https://files.pythonhosted.org/packages/e1/7f/64b51f144fa9e74da63fa690d9563eae627f4df6cc6ae5185a781e1912e5/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c75ffc45f25324e68ab238cb4b5c0a38cd1c3d7f1fb1f72b5541de469e2247db"},
|
||||
{url = "https://files.pythonhosted.org/packages/e3/96/8cdbce165c96cce5f2c9c7748f7ed8e0cf0c5d03e213bbc90b7c3e918bf5/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ae1de54a77dc0d6d5fcf623290af4266412a7c4be0b1ff7444394f03f5c54e3"},
|
||||
{url = "https://files.pythonhosted.org/packages/e7/0d/5eaceb5abfc000cca204af9f50e9839462dc0bb1c4e0f4b14ed370e3febd/charset_normalizer-3.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:0a11e971ed097d24c534c037d298ad32c6ce81a45736d31e0ff0ad37ab437d59"},
|
||||
{url = "https://files.pythonhosted.org/packages/e8/80/141f6af05332cbb811ab469f64deb1e1d4cc9e8b0c003aa8a38d689ce84a/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:37f8febc8ec50c14f3ec9637505f28e58d4f66752207ea177c1d67df25da5aed"},
|
||||
{url = "https://files.pythonhosted.org/packages/f0/78/30d853a3073c866b47abede6d86b5532aa99ac67a95e86077d20be1ce481/charset_normalizer-3.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:db72b07027db150f468fbada4d85b3b2729a3db39178abf5c543b784c1254539"},
|
||||
{url = "https://files.pythonhosted.org/packages/f1/14/ed5990189a6a25ae9f8d63e74cd0336189f9ad7e51f066ba2f6cb73e8126/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4c39b0e3eac288fedc2b43055cfc2ca7a60362d0e5e87a637beac5d801ef478"},
|
||||
{url = "https://files.pythonhosted.org/packages/f1/ff/9a1c65d8c44958f45ae40cd558ab63bd499a35198a2014e13c0887c07ed1/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:a152f5f33d64a6be73f1d30c9cc82dfc73cec6477ec268e7c6e4c7d23c2d2291"},
|
||||
{url = "https://files.pythonhosted.org/packages/f5/84/cac681144a28114bd9e40d3cdbfd961c14ecc2b56f1baec2094afd6744c7/charset_normalizer-3.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3fc1c4a2ffd64890aebdb3f97e1278b0cc72579a08ca4de8cd2c04799a3a22be"},
|
||||
{url = "https://files.pythonhosted.org/packages/f5/ec/a9bed59079bd0267d34ada58a4048c96a59b3621e7f586ea85840d41831d/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:356541bf4381fa35856dafa6a965916e54bed415ad8a24ee6de6e37deccf2786"},
|
||||
{url = "https://files.pythonhosted.org/packages/fc/64/443267b7824283b3e0e33cee4240c079939a970c2c9a5a3164fc988d690b/charset_normalizer-3.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:2c03cc56021a4bd59be889c2b9257dae13bf55041a3372d3295416f86b295fb5"},
|
||||
]
|
||||
"click 8.1.3" = [
|
||||
{url = "https://files.pythonhosted.org/packages/59/87/84326af34517fca8c58418d148f2403df25303e02736832403587318e9e8/click-8.1.3.tar.gz", hash = "sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e"},
|
||||
{url = "https://files.pythonhosted.org/packages/c2/f1/df59e28c642d583f7dacffb1e0965d0e00b218e0186d7858ac5233dce840/click-8.1.3-py3-none-any.whl", hash = "sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48"},
|
||||
]
|
||||
"colorama 0.4.6" = [
|
||||
{url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
|
||||
{url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
|
||||
]
|
||||
"dbus-next 0.2.3" = [
|
||||
{url = "https://files.pythonhosted.org/packages/ce/45/6a40fbe886d60a8c26f480e7d12535502b5ba123814b3b9a0b002ebca198/dbus_next-0.2.3.tar.gz", hash = "sha256:f4eae26909332ada528c0a3549dda8d4f088f9b365153952a408e28023a626a5"},
|
||||
{url = "https://files.pythonhosted.org/packages/d2/fc/c0a3f4c4eaa5a22fbef91713474666e13d0ea2a69c84532579490a9f2cc8/dbus_next-0.2.3-py3-none-any.whl", hash = "sha256:58948f9aff9db08316734c0be2a120f6dc502124d9642f55e90ac82ffb16a18b"},
|
||||
]
|
||||
"distro 1.8.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/4b/89/eaa3a3587ebf8bed93e45aa79be8c2af77d50790d15b53f6dfc85b57f398/distro-1.8.0.tar.gz", hash = "sha256:02e111d1dc6a50abb8eed6bf31c3e48ed8b0830d1ea2a1b78c61765c2513fdd8"},
|
||||
{url = "https://files.pythonhosted.org/packages/f4/2c/c90a3adaf0ddb70afe193f5ebfb539612af57cffe677c3126be533df3098/distro-1.8.0-py3-none-any.whl", hash = "sha256:99522ca3e365cac527b44bde033f64c6945d90eb9f769703caaec52b09bbd3ff"},
|
||||
]
|
||||
"idna 3.4" = [
|
||||
{url = "https://files.pythonhosted.org/packages/8b/e1/43beb3d38dba6cb420cefa297822eac205a277ab43e5ba5d5c46faf96438/idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"},
|
||||
{url = "https://files.pythonhosted.org/packages/fc/34/3030de6f1370931b9dbb4dad48f6ab1015ab1d32447850b9fc94e60097be/idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"},
|
||||
]
|
||||
"ifaddr 0.2.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748"},
|
||||
{url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4"},
|
||||
]
|
||||
"importlib-metadata 6.0.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/26/a7/9da7d5b23fc98ab3d424ac2c65613d63c1f401efb84ad50f2fa27b2caab4/importlib_metadata-6.0.0-py3-none-any.whl", hash = "sha256:7efb448ec9a5e313a57655d35aa54cd3e01b7e1fbcf72dce1bf06119420f5bad"},
|
||||
{url = "https://files.pythonhosted.org/packages/90/07/6397ad02d31bddf1841c9ad3ec30a693a3ff208e09c2ef45c9a8a5f85156/importlib_metadata-6.0.0.tar.gz", hash = "sha256:e354bedeb60efa6affdcc8ae121b73544a7aa74156d047311948f6d711cd378d"},
|
||||
]
|
||||
"inotify-simple 1.3.5" = [
|
||||
{url = "https://files.pythonhosted.org/packages/51/41/59ca6011f5463d5e5eefcfed2e7fe470922d3a958b7f3aad95eda208d7d3/inotify_simple-1.3.5.tar.gz", hash = "sha256:8440ffe49c4ae81a8df57c1ae1eb4b6bfa7acb830099bfb3e305b383005cc128"},
|
||||
]
|
||||
"jinja2 3.1.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/7a/ff/75c28576a1d900e87eb6335b063fab47a8ef3c8b4d88524c4bf78f670cce/Jinja2-3.1.2.tar.gz", hash = "sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852"},
|
||||
{url = "https://files.pythonhosted.org/packages/bc/c3/f068337a370801f372f2f8f6bad74a5c140f6fda3d9de154052708dd3c65/Jinja2-3.1.2-py3-none-any.whl", hash = "sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61"},
|
||||
]
|
||||
"ldap3 2.9.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/43/ac/96bd5464e3edbc61595d0d69989f5d9969ae411866427b2500a8e5b812c0/ldap3-2.9.1.tar.gz", hash = "sha256:f3e7fc4718e3f09dda568b57100095e0ce58633bcabbed8667ce3f8fbaa4229f"},
|
||||
{url = "https://files.pythonhosted.org/packages/4e/f6/71d6ec9f18da0b2201287ce9db6afb1a1f637dedb3f0703409558981c723/ldap3-2.9.1-py2.py3-none-any.whl", hash = "sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70"},
|
||||
]
|
||||
"libnacl 1.8.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/9b/dd/395854871aa26b2d082d9c583a5ec807e26132029b0a5a935510b6ae515b/libnacl-1.8.0-py2.py3-none-any.whl", hash = "sha256:a2a4721e9d3d65a2630f9f904ab6624bb6f9e57ab0574244f666d1b58cea0f33"},
|
||||
{url = "https://files.pythonhosted.org/packages/db/ab/1111466244a682121a86cf5360fb7c804e6c21edaf0b439bfd898f4a11fe/libnacl-1.8.0.tar.gz", hash = "sha256:f1037b85ca31fd8b02c43d66f78c2049bc58480e6a395dc9d27e6821b5fe185d"},
|
||||
]
|
||||
"lmdb 1.3.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/19/78/bf28525ae03487162cee2e013cec3aeced349c3c2a8325a7dbfdcd61e680/lmdb-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:df2724bad7820114a205472994091097d0fa65a3e5fff5a8e688d123fb8c6326"},
|
||||
{url = "https://files.pythonhosted.org/packages/2b/50/47b7cfe3973f787d2dc47ff3c41aac3dc37d0a10994ccd1129b18b64af68/lmdb-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ddd590e1c7fcb395931aa3782fb89b9db4550ab2d81d006ecd239e0d462bc41"},
|
||||
{url = "https://files.pythonhosted.org/packages/3c/4e/bf7177e502593ac31a6a9fd05db2d767474483cde8a1702189f9e271ffb3/lmdb-1.3.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:eefb392f6b5cd43aada49258c5a79be11cb2c8cd3fc3e2d9319a1e0b9f906458"},
|
||||
{url = "https://files.pythonhosted.org/packages/3f/31/fcdaedcbfdee59fc2a5643ced9c5af59ef54b8b11d8b40f3f420719c2b33/lmdb-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:d6a816954d212f40fd15007cd81ab7a6bebb77436d949a6a9ae04af57fc127f3"},
|
||||
{url = "https://files.pythonhosted.org/packages/4c/e2/fb76e5f8bd60fda8d6672c921fc3f024542720bc0f35fa5e1f541f00c006/lmdb-1.3.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:008243762decf8f6c90430a9bced56290ebbcdb5e877d90e42343bb97033e494"},
|
||||
{url = "https://files.pythonhosted.org/packages/4d/cf/3230b1c9b0bec406abb85a9332ba5805bdd03a1d24025c6bbcfb8ed71539/lmdb-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:17215a42a4b9814c383deabecb160581e4fb75d00198eef0e3cea54f230ffbea"},
|
||||
{url = "https://files.pythonhosted.org/packages/50/e7/fb9f704d7db6fe10315ce22d173e2307565b62ee81df34079ca7f23d8b60/lmdb-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:18c69fabdaf04efaf246587739cc1062b3e57c6ef0743f5c418df89e5e7e7b9b"},
|
||||
{url = "https://files.pythonhosted.org/packages/57/cc/36832bc3e04fa3a4cb61f02db0641b245d94b205ab215b967448ee36e3c9/lmdb-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:4172fba19417d7b29409beca7d73c067b54e5d8ab1fb9b51d7b4c1445d20a167"},
|
||||
{url = "https://files.pythonhosted.org/packages/5b/f5/a20bb77dced2aadc7bd45cb7a136dc748119d78d405e2bf5746ed1325fc6/lmdb-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65334eafa5d430b18d81ebd5362559a41483c362e1931f6e1b15bab2ecb7d75d"},
|
||||
{url = "https://files.pythonhosted.org/packages/60/af/f84c4dd2953e757701e2f027bc0637cce7f2784ea47297bd4d5ee98a14c9/lmdb-1.3.0-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:abbc439cd9fe60ffd6197009087ea885ac150017dc85384093b1d376f83f0ec4"},
|
||||
{url = "https://files.pythonhosted.org/packages/62/66/764b581d5568d3f31340e970d8abc5a1c93cb65d1d0f3dd59f606bff6817/lmdb-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cfa4aa9c67f8aee89b23005e98d1f3f32490b6b905fd1cb604b207cbd5755ab"},
|
||||
{url = "https://files.pythonhosted.org/packages/62/b1/b53765aafa2d508285718cdc7088332d3093ce36a8c989a224413783bdd8/lmdb-1.3.0-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:fa6439356e591d3249ab0e1778a6f8d8408e993f66dc911914c78208f5310309"},
|
||||
{url = "https://files.pythonhosted.org/packages/65/01/ee604f15c55d72eb1216ab27eb36ca613a967ab05d6f83b44b7a36d73f29/lmdb-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:6260a526e4ad85b1f374a5ba9475bf369fb07e7728ea6ec57226b02c40d1976b"},
|
||||
{url = "https://files.pythonhosted.org/packages/79/fb/36d8a180284d8967be737b68ef1ae163f00be8a38c1a77b840de8d6306fb/lmdb-1.3.0-pp27-pypy_73-win_amd64.whl", hash = "sha256:08f4b5129f4683802569b02581142e415c8dcc0ff07605983ec1b07804cecbad"},
|
||||
{url = "https://files.pythonhosted.org/packages/7d/7d/9f45a8b64b398d0acedcfd5fe0049286b7488bf7d34a6a710520cff26d0c/lmdb-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:7da05d70fcc6561ac6b09e9fb1bf64b7ca294652c64c8a2889273970cee796b9"},
|
||||
{url = "https://files.pythonhosted.org/packages/90/fd/788b49864b367199fe5ae97d391617b0d520645e65c9903884c10f89be2f/lmdb-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:62ab28e3593bdc318ea2f2fa1574e5fca3b6d1f264686d773ba54a637d4f563b"},
|
||||
{url = "https://files.pythonhosted.org/packages/97/47/1e73bc4b4879d1be8dfed4d1dcd139d2f8dfd0c6f63ef4ff5e132b8890e9/lmdb-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e568ae0887ae196340947d9800136e90feaed6b86a261ef01f01b2ba65fc8106"},
|
||||
{url = "https://files.pythonhosted.org/packages/a3/c8/832b2310460d1eeee9d51410dcb4ce41cbe17a9eeb8eba7c4f5eb9cf8beb/lmdb-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:394df860c3f93cfd92b6f4caba785f38208cc9614c18b3803f83a2cc1695042f"},
|
||||
{url = "https://files.pythonhosted.org/packages/a4/8d/e27d341de15eb9cc3755d38542cc448ced1037e0eb641e38ad66a564ff6a/lmdb-1.3.0-pp27-pypy_73-macosx_10_7_x86_64.whl", hash = "sha256:e6a704b3baced9182836c7f77b769f23856f3a8f62d0282b1bc1feaf81a86712"},
|
||||
{url = "https://files.pythonhosted.org/packages/aa/4a/a404ce11f448c424994096dc7c8a85c5e317cfaec98afc6f90a814e7c706/lmdb-1.3.0-cp35-cp35m-win_amd64.whl", hash = "sha256:c6adbd6f7f9048e97f31a069e652eb51020a81e80a0ce92dbb9810d21da2409a"},
|
||||
{url = "https://files.pythonhosted.org/packages/af/ad/092d8863b765ccac995ce799c725d340d81b225e50c950d3cf801dba49ef/lmdb-1.3.0-pp36-pypy36_pp73-win32.whl", hash = "sha256:f291e3f561f58dddf63a92a5a6a4b8af3a0920b6705d35e2f80e52e86ee238a2"},
|
||||
{url = "https://files.pythonhosted.org/packages/bb/6b/3cec989d03e31f4b7eac453de8ab394df24eb2ee75114b9135f0e2cd9e2a/lmdb-1.3.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:41318717ab5d15ad2d6d263d34fbf614a045210f64b25e59ce734bb2105e421f"},
|
||||
{url = "https://files.pythonhosted.org/packages/c5/72/109e7264a6441b4d9d0031be67776d9ef5cf69448ebec71d00a877a2babd/lmdb-1.3.0-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:63cb73fe7ce9eb93d992d632c85a0476b4332670d9e6a2802b5062f603b7809f"},
|
||||
{url = "https://files.pythonhosted.org/packages/d0/5b/8147d8ab13bfa57c5175803fd8796479da27298b828c95aa1d05e4b60c20/lmdb-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d9103aa4908f0bca43c5911ca067d4e3d01f682dff0c0381a1239bd2bd757984"},
|
||||
{url = "https://files.pythonhosted.org/packages/db/bf/1fa60f5893263ef4d0a74994104650a002d2a970b183608e5b7497836bfc/lmdb-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5a14aca2651c3af6f0d0a6b9168200eea0c8f2d27c40b01a442f33329a6e8dff"},
|
||||
{url = "https://files.pythonhosted.org/packages/ed/61/41f3c7cbd8a67202ef24fad3375ed936093a0547dc645581dd11c09581b7/lmdb-1.3.0.tar.gz", hash = "sha256:60a11efc21aaf009d06518996360eed346f6000bfc9de05114374230879f992e"},
|
||||
{url = "https://files.pythonhosted.org/packages/f8/f7/4a889009d678cf7ce4e2349ed48a4f7c97c380018246e4f68b373192da75/lmdb-1.3.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:2df38115dd9428a54d59ae7c712a4c7cce0d6b1d66056de4b1a8c38718066106"},
|
||||
]
|
||||
"markdown 3.4.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/85/7e/133e943e97a943d2f1d8bae0c5060f8ac50e6691754eb9dbe036b047a9bb/Markdown-3.4.1.tar.gz", hash = "sha256:3b809086bb6efad416156e00a0da66fe47618a5d6918dd688f53f40c8e4cfeff"},
|
||||
{url = "https://files.pythonhosted.org/packages/86/be/ad281f7a3686b38dd8a307fa33210cdf2130404dfef668a37a4166d737ca/Markdown-3.4.1-py3-none-any.whl", hash = "sha256:08fb8465cffd03d10b9dd34a5c3fea908e20391a2a90b88d66362cb05beed186"},
|
||||
]
|
||||
"markupsafe 2.1.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/02/2c/18d55e5df6a9ea33709d6c33e08cb2e07d39e20ad05d8c6fbf9c9bcafd54/MarkupSafe-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:835fb5e38fd89328e9c81067fd642b3593c33e1e17e2fdbf77f5676abb14a156"},
|
||||
{url = "https://files.pythonhosted.org/packages/04/cf/9464c3c41b7cdb8df660cda75676697e7fb49ce1be7691a1162fc88da078/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:085fd3201e7b12809f9e6e9bc1e5c96a368c8523fad5afb02afe3c051ae4afcc"},
|
||||
{url = "https://files.pythonhosted.org/packages/06/3b/d026c21cd1dbee89f41127e93113dcf5fa85c6660d108847760b59b3a66d/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40dfd3fefbef579ee058f139733ac336312663c6706d1163b82b3003fb1925c4"},
|
||||
{url = "https://files.pythonhosted.org/packages/0a/88/78cb3d95afebd183d8b04442685ab4c70cfc1138b850ba20e2a07aff2f53/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65608c35bfb8a76763f37036547f7adfd09270fbdbf96608be2bead319728fcd"},
|
||||
{url = "https://files.pythonhosted.org/packages/0d/15/82b108c697bec4c26c00aed6975b778cf0eac6cbb77598862b10550b7fcc/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2298c859cfc5463f1b64bd55cb3e602528db6fa0f3cfd568d3605c50678f8f03"},
|
||||
{url = "https://files.pythonhosted.org/packages/19/00/3b8eb0093c885576a1ce7f2263e7b8c01e55b9977433f8246f57cd81b0be/MarkupSafe-2.1.2-cp311-cp311-win32.whl", hash = "sha256:7df70907e00c970c60b9ef2938d894a9381f38e6b9db73c5be35e59d92e06625"},
|
||||
{url = "https://files.pythonhosted.org/packages/1f/20/76f6337f1e7238a626ab34405ddd634636011b2ff947dcbd8995f16a7776/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1bea30e9bf331f3fef67e0a3877b2288593c98a21ccb2cf29b74c581a4eb3af0"},
|
||||
{url = "https://files.pythonhosted.org/packages/22/88/9c0cae2f5ada778182f2842b377dd273d6be689953345c10b165478831eb/MarkupSafe-2.1.2-cp39-cp39-win32.whl", hash = "sha256:137678c63c977754abe9086a3ec011e8fd985ab90631145dfb9294ad09c102a7"},
|
||||
{url = "https://files.pythonhosted.org/packages/29/d2/243e6b860d97c18d848fc2bee2f39d102755a2b04a5ce4d018d839711b46/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:8db032bf0ce9022a8e41a22598eefc802314e81b879ae093f36ce9ddf39ab1ba"},
|
||||
{url = "https://files.pythonhosted.org/packages/30/3e/0a69a24adb38df83e2f6989c38d68627a5f27181c82ecaa1fd03d1236dca/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ca244fa73f50a800cf8c3ebf7fd93149ec37f5cb9596aa8873ae2c1d23498601"},
|
||||
{url = "https://files.pythonhosted.org/packages/34/19/64b0abc021b22766e86efee32b0e2af684c4b731ce8ac1d519c791800c13/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:340bea174e9761308703ae988e982005aedf427de816d1afe98147668cc03036"},
|
||||
{url = "https://files.pythonhosted.org/packages/37/b2/6f4d5cac75ba6fe9f17671304fe339ea45a73c5609b5f5e652aa79c915c8/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:665a36ae6f8f20a4676b53224e33d456a6f5a72657d9c83c2aa00765072f31f7"},
|
||||
{url = "https://files.pythonhosted.org/packages/39/8d/5c5ce72deb8567ab48a18fbd99dc0af3dd651b6691b8570947e54a28e0f3/MarkupSafe-2.1.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6d6607f98fcf17e534162f0709aaad3ab7a96032723d8ac8750ffe17ae5a0666"},
|
||||
{url = "https://files.pythonhosted.org/packages/3d/66/2f636ba803fd6eb4cee7b3106ae02538d1e84a7fb7f4f8775c6528a87d31/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:28057e985dace2f478e042eaa15606c7efccb700797660629da387eb289b9323"},
|
||||
{url = "https://files.pythonhosted.org/packages/41/54/6e88795c64ab5dcda31b06406c062c2740d1a64db18219d4e21fc90928c1/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c0a33bc9f02c2b17c3ea382f91b4db0e6cde90b63b296422a939886a7a80de1c"},
|
||||
{url = "https://files.pythonhosted.org/packages/46/0c/10ee33673c5e36fa3809cf136971f81d951ca38516188ee11a965d9b2fe9/MarkupSafe-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:0576fe974b40a400449768941d5d0858cc624e3249dfd1e0c33674e5c7ca7aed"},
|
||||
{url = "https://files.pythonhosted.org/packages/48/cc/d027612e17b56088cfccd2c8e083518995fcb25a7b4f17fc146362a0499d/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f8ffb705ffcf5ddd0e80b65ddf7bed7ee4f5a441ea7d3419e861a12eaf41af58"},
|
||||
{url = "https://files.pythonhosted.org/packages/4b/34/dc837e5ad9e14634aac4342eb8b12a9be20a4f74f50cc0d765f7aa2fc1e3/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a4abaec6ca3ad8660690236d11bfe28dfd707778e2442b45addd2f086d6ef094"},
|
||||
{url = "https://files.pythonhosted.org/packages/50/41/1442b693a40eb76d835ca2016e86a01479f17d7fd8288f9830f6790e366a/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b8526c6d437855442cdd3d87eede9c425c4445ea011ca38d937db299382e6fa3"},
|
||||
{url = "https://files.pythonhosted.org/packages/52/36/b35c577c884ea352fc0c1eaed9ca4946ffc22cc9c3527a70408bfa9e9496/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f"},
|
||||
{url = "https://files.pythonhosted.org/packages/56/0d/c9818629672a3368b773fa94597d79da77bdacc3186f097bb85023f785f6/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:0b462104ba25f1ac006fdab8b6a01ebbfbce9ed37fd37fd4acd70c67c973e460"},
|
||||
{url = "https://files.pythonhosted.org/packages/5a/94/d056bf5dbadf7f4b193ee2a132b3d49ffa1602371e3847518b2982045425/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2bfb563d0211ce16b63c7cb9395d2c682a23187f54c3d79bfec33e6705473c6"},
|
||||
{url = "https://files.pythonhosted.org/packages/5e/f6/8eb8a5692c1986b6e863877b0b8a83628aff14e5fbfaf11d9522b532bd9d/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22152d00bf4a9c7c83960521fc558f55a1adbc0631fbb00a9471e097b19d72e1"},
|
||||
{url = "https://files.pythonhosted.org/packages/66/21/dadb671aade8eb67ef96e0d8f90b1bd5e8cfb6ad9d8c7fa2c870ec0c257b/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:55f44b440d491028addb3b88f72207d71eeebfb7b5dbf0643f7c023ae1fba619"},
|
||||
{url = "https://files.pythonhosted.org/packages/76/b5/05ce70a3e31ecebcd3628cd180dc4761293aa496db85170fdc085ed2d79a/MarkupSafe-2.1.2-cp38-cp38-win32.whl", hash = "sha256:50c42830a633fa0cf9e7d27664637532791bfc31c731a87b202d2d8ac40c3ea2"},
|
||||
{url = "https://files.pythonhosted.org/packages/77/26/af46880038c6eac3832e751298f1965f3a550f38d1e9ddaabd674860076b/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8bca7e26c1dd751236cfb0c6c72d4ad61d986e9a41bbf76cb445f69488b2a2bd"},
|
||||
{url = "https://files.pythonhosted.org/packages/78/e6/91c9a20a943ea231c59024e181c4c5480097daf132428f2272670974637f/MarkupSafe-2.1.2-cp310-cp310-win32.whl", hash = "sha256:c4a549890a45f57f1ebf99c067a4ad0cb423a05544accaf2b065246827ed9603"},
|
||||
{url = "https://files.pythonhosted.org/packages/79/e2/b818bf277fa6b01244943498cb2127372c01dde5eff7682837cc72740618/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da25303d91526aac3672ee6d49a2f3db2d9502a4a60b55519feb1a4c7714e07d"},
|
||||
{url = "https://files.pythonhosted.org/packages/7b/0f/0e99c2f342933c43af69849a6ba63f2eef54e14c6d0e10a26470fb6b40a9/MarkupSafe-2.1.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a6e40afa7f45939ca356f348c8e23048e02cb109ced1eb8420961b2f40fb373a"},
|
||||
{url = "https://files.pythonhosted.org/packages/7c/e6/454df09f18e0ea34d189b447a9e1a9f66c2aa332b77fd5577ebc7ca14d42/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2"},
|
||||
{url = "https://files.pythonhosted.org/packages/80/64/ccb65aadd71e7685caa69a885885a673e8748525a243fb26acea37201b44/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f03a532d7dee1bed20bc4884194a16160a2de9ffc6354b3878ec9682bb623c54"},
|
||||
{url = "https://files.pythonhosted.org/packages/82/70/b3978786c7b576c25d84b009d2a20a11b5300d252fc3ce984e37b932e97c/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2e7821bffe00aa6bd07a23913b7f4e01328c3d5cc0b40b36c0bd81d362faeb65"},
|
||||
{url = "https://files.pythonhosted.org/packages/82/e3/4efcd74f10a7999783955aec36386f71082e6d7dafcc06b77b9df72b325a/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99625a92da8229df6d44335e6fcc558a5037dd0a760e11d84be2260e6f37002f"},
|
||||
{url = "https://files.pythonhosted.org/packages/87/a1/d0f05a09c6c1aef89d1eea0ab0ff1ea897d4117d27f1571034a7e3ff515b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf877ab4ed6e302ec1d04952ca358b381a882fbd9d1b07cccbfd61783561f98a"},
|
||||
{url = "https://files.pythonhosted.org/packages/93/ca/1c3ae0c6a5712d4ba98610cada03781ea0448436b17d1dcd4759115b15a1/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d9d971ec1e79906046aa3ca266de79eac42f1dbf3612a05dc9368125952bd1a1"},
|
||||
{url = "https://files.pythonhosted.org/packages/93/fa/d72f68f84f8537ee8aa3e0764d1eb11e5e025a5ca90c16e94a40f894c2fc/MarkupSafe-2.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:bb06feb762bade6bf3c8b844462274db0c76acc95c52abe8dbed28ae3d44a147"},
|
||||
{url = "https://files.pythonhosted.org/packages/95/7e/68018b70268fb4a2a605e2be44ab7b4dd7ce7808adae6c5ef32e34f4b55a/MarkupSafe-2.1.2.tar.gz", hash = "sha256:abcabc8c2b26036d62d4c746381a6f7cf60aafcc653198ad678306986b09450d"},
|
||||
{url = "https://files.pythonhosted.org/packages/95/88/8c8cce021ac1b1eedde349c6a41f6c256da60babf95e572071361ff3f66b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63ba06c9941e46fa389d389644e2d8225e0e3e5ebcc4ff1ea8506dce646f8c8a"},
|
||||
{url = "https://files.pythonhosted.org/packages/96/92/a873b4a7fa20c2e30bffe883bb560330f3b6ce03aaf278f75f96d161935b/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:7e007132af78ea9df29495dbf7b5824cb71648d7133cf7848a2a5dd00d36f9ff"},
|
||||
{url = "https://files.pythonhosted.org/packages/9d/80/8320f182d06a9b289b1a9f266f593feb91d3781c7e104bbe09e0c4c11439/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4cf06cdc1dda95223e9d2d3c58d3b178aa5dacb35ee7e3bbac10e4e1faacb419"},
|
||||
{url = "https://files.pythonhosted.org/packages/be/18/988e1913a40cc8eb725b1e073eacc130f7803a061577bdc0b9343eb3c696/MarkupSafe-2.1.2-cp37-cp37m-win32.whl", hash = "sha256:7668b52e102d0ed87cb082380a7e2e1e78737ddecdde129acadb0eccc5423859"},
|
||||
{url = "https://files.pythonhosted.org/packages/c3/e5/42842a44bfd9ba2955c562b1139334a2f64cedb687e8969777fd07de42a9/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f1cd098434e83e656abf198f103a8207a8187c0fc110306691a2e94a78d0abb2"},
|
||||
{url = "https://files.pythonhosted.org/packages/c7/0e/22d0c8e6ee84414e251bd1bc555b2705af6b3fb99f0ba1ead2a0f51d423b/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22731d79ed2eb25059ae3df1dfc9cb1546691cc41f4e3130fe6bfbc3ecbbecfa"},
|
||||
{url = "https://files.pythonhosted.org/packages/cf/c1/d7596976a868fe3487212a382cc121358a53dc8e8d85ff2ee2c3d3b40f04/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:9cad97ab29dfc3f0249b483412c85c8ef4766d96cdf9dcf5a1e3caa3f3661cf1"},
|
||||
{url = "https://files.pythonhosted.org/packages/d1/10/ff89b23d4a24051c4e4f689b79ee06f230d7e9431445e24f5dd9d9a89730/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:a806db027852538d2ad7555b203300173dd1b77ba116de92da9afbc3a3be3eed"},
|
||||
{url = "https://files.pythonhosted.org/packages/e3/a9/e366665c7eae59c9c9d34b747cd5a3994847719a2304e0c8dec8b604dd98/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2ec4f2d48ae59bbb9d1f9d7efb9236ab81429a764dedca114f5fdabbc3788013"},
|
||||
{url = "https://files.pythonhosted.org/packages/e6/ff/d2378ca3cb3ac4a37af767b820b0f0bf3f5e9193a6acce0eefc379425c1c/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:608e7073dfa9e38a85d38474c082d4281f4ce276ac0010224eaba11e929dd53a"},
|
||||
{url = "https://files.pythonhosted.org/packages/e9/c6/2da36728c1310f141395176556500aeedfdea8c2b02a3b72ba61b69280e8/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:a6f2fcca746e8d5910e18782f976489939d54a91f9411c32051b4aab2bd7c513"},
|
||||
{url = "https://files.pythonhosted.org/packages/ea/60/2400ba59cf2465fa136487ee7299f52121a9d04b2cf8539ad43ad10e70e8/MarkupSafe-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:e55e40ff0cc8cc5c07996915ad367fa47da6b3fc091fdadca7f5403239c5fec3"},
|
||||
{url = "https://files.pythonhosted.org/packages/f9/aa/ebcd114deab08f892b1d70badda4436dbad1747f9e5b72cffb3de4c7129d/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:7313ce6a199651c4ed9d7e4cfb4aa56fe923b1adf9af3b420ee14e6d9a73df65"},
|
||||
]
|
||||
"oauthlib 3.2.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/6d/fa/fbf4001037904031639e6bfbfc02badfc7e12f137a8afa254df6c4c8a670/oauthlib-3.2.2.tar.gz", hash = "sha256:9859c40929662bec5d64f34d01c99e093149682a3f38915dc0655d5a633dd918"},
|
||||
{url = "https://files.pythonhosted.org/packages/7e/80/cab10959dc1faead58dc8384a781dfbf93cb4d33d50988f7a69f1b7c9bbe/oauthlib-3.2.2-py3-none-any.whl", hash = "sha256:8139f29aac13e25d502680e9e19963e83f16838d48a0d71c287fe40e7067fbca"},
|
||||
]
|
||||
"paho-mqtt 1.6.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/f8/dd/4b75dcba025f8647bc9862ac17299e0d7d12d3beadbf026d8c8d74215c12/paho-mqtt-1.6.1.tar.gz", hash = "sha256:2a8291c81623aec00372b5a85558a372c747cbca8e9934dfe218638b8eefc26f"},
|
||||
]
|
||||
"pillow 9.3.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/00/73/000575ca7b7635ecd4075e71925b71f2648300d725b6c9a1f969fe2d5a87/Pillow-9.3.0-cp37-cp37m-macosx_10_10_x86_64.whl", hash = "sha256:772a91fc0e03eaf922c63badeca75e91baa80fe2f5f87bdaed4280662aad25c9"},
|
||||
{url = "https://files.pythonhosted.org/packages/06/2f/c17a2d559009b875f7da804a3a4e0f47baca6df2dfedb29a1df641c51e1a/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:12ce4932caf2ddf3e41d17fc9c02d67126935a44b86df6a206cf0d7161548627"},
|
||||
{url = "https://files.pythonhosted.org/packages/0d/87/f696d8464c949c5a7ac133c8b7297a4243e0319fd29ae3a90b4ac90f0a5b/Pillow-9.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7db8b751ad307d7cf238f02101e8e36a128a6cb199326e867d1398067381bff4"},
|
||||
{url = "https://files.pythonhosted.org/packages/15/13/232be66adb8482f0636b3f3e254d9e18d7093bd1848b3610ffaf72717924/Pillow-9.3.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:829f97c8e258593b9daa80638aee3789b7df9da5cf1336035016d76f03b8860c"},
|
||||
{url = "https://files.pythonhosted.org/packages/16/11/da8d395299ca166aa56d9436e26fe8440e5443471de16ccd9a1d06f5993a/Pillow-9.3.0.tar.gz", hash = "sha256:c935a22a557a560108d780f9a0fc426dd7459940dc54faa49d83249c8d3e760f"},
|
||||
{url = "https://files.pythonhosted.org/packages/1d/15/054644ecbed79d3af017a56eaabd13bf712b21c3a667b8a67a335174f4b7/Pillow-9.3.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:89dca0ce00a2b49024df6325925555d406b14aa3efc2f752dbb5940c52c56b11"},
|
||||
{url = "https://files.pythonhosted.org/packages/23/b3/20f97e1bacd02b89953b50b2502be1b10e01d36a0618fb197e4a055e50f4/Pillow-9.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68943d632f1f9e3dce98908e873b3a090f6cba1cbb1b892a9e8d97c938871fbe"},
|
||||
{url = "https://files.pythonhosted.org/packages/26/d6/9355d59a2ee9406e4d5129ff0ff99835e7f6adb6133815fab2099e1879b5/Pillow-9.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:0b7257127d646ff8676ec8a15520013a698d1fdc48bc2a79ba4e53df792526f2"},
|
||||
{url = "https://files.pythonhosted.org/packages/2c/3d/36cd1f6c04ab30ab7e6bc8d17a4337fc29fa5b35ebd4c520d916ce7e39e6/Pillow-9.3.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:b03ae6f1a1878233ac620c98f3459f79fd77c7e3c2b20d460284e1fb370557d4"},
|
||||
{url = "https://files.pythonhosted.org/packages/2c/74/109e3d1fd2847c19c556fe4ce9b3f4aac2147b56c7b5d0924ae9586d2a47/Pillow-9.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9a65733d103311331875c1dca05cb4606997fd33d6acfed695b1232ba1df193"},
|
||||
{url = "https://files.pythonhosted.org/packages/2e/c8/03495501bb9beabf34979781b14cc625f39cbd8ff5310a93a85e45987590/Pillow-9.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:4390e9ce199fc1951fcfa65795f239a8a4944117b5935a9317fb320e7767b40f"},
|
||||
{url = "https://files.pythonhosted.org/packages/2f/73/ec6b3e3f6b311cf1468eafc92a890f690a2cacac0cfd0f1bcc2b891d1334/Pillow-9.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af0372acb5d3598f36ec0914deed2a63f6bcdb7b606da04dc19a88d31bf0c05b"},
|
||||
{url = "https://files.pythonhosted.org/packages/39/5e/585dfbe0eb4660ea3ee082289625f94e402239282458c4bf78ecc84fbb93/Pillow-9.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40e1ce476a7804b0fb74bcfa80b0a2206ea6a882938eaba917f7a0f004b42502"},
|
||||
{url = "https://files.pythonhosted.org/packages/40/57/c8695a77561a83bd39eba30daf4d894b0b910aad55e2b60f0ef1b1b5205c/Pillow-9.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:9f47eabcd2ded7698106b05c2c338672d16a6f2a485e74481f524e2a23c2794b"},
|
||||
{url = "https://files.pythonhosted.org/packages/41/e9/7bae68c360de8d1e7e32aeab252c6dc9336c0d779c9ad5e24ce475d523fd/Pillow-9.3.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ab388aaa3f6ce52ac1cb8e122c4bd46657c15905904b3120a6248b5b8b0bc228"},
|
||||
{url = "https://files.pythonhosted.org/packages/47/b2/6e5fc952713bfee71c5e25e7917b18207b6f445d81746008b14d9c80a91b/Pillow-9.3.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:15c42fb9dea42465dfd902fb0ecf584b8848ceb28b41ee2b58f866411be33f07"},
|
||||
{url = "https://files.pythonhosted.org/packages/48/92/820b43fcb333fe7f4cf726ed3c0cfcfd062f65b8fd23c0e6972a6107f440/Pillow-9.3.0-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:b59430236b8e58840a0dfb4099a0e8717ffb779c952426a69ae435ca1f57210c"},
|
||||
{url = "https://files.pythonhosted.org/packages/4b/f9/2fa7d6cce0b9867ec3917878d03d5298d7a88522ed7dadc6cac4642bce8b/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bca31dd6014cb8b0b2db1e46081b0ca7d936f856da3b39744aef499db5d84d02"},
|
||||
{url = "https://files.pythonhosted.org/packages/4e/8c/84131e85d4ebd600a823fad1707157d55055a7ea80ce6c8c2f6e2de93f2c/Pillow-9.3.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a0a06a052c5f37b4ed81c613a455a81f9a3a69429b4fd7bb913c3fa98abefc20"},
|
||||
{url = "https://files.pythonhosted.org/packages/56/02/2c8fde18b251c6ce2061b23b4fa04f3e71d386c725a09753bad19649e1b1/Pillow-9.3.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:51e0e543a33ed92db9f5ef69a0356e0b1a7a6b6a71b80df99f1d181ae5875636"},
|
||||
{url = "https://files.pythonhosted.org/packages/5b/48/1e4437f90c0531c0a8f5c5b1e793e0f234fe8203019de04001213b4fb38e/Pillow-9.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:90fb88843d3902fe7c9586d439d1e8c05258f41da473952aa8b328d8b907498c"},
|
||||
{url = "https://files.pythonhosted.org/packages/5f/1e/8a26e1ff2064b665f3923a727cb9240919cdcdce303e4800729635aefc40/Pillow-9.3.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0915e734b33a474d76c28e07292f196cdf2a590a0d25bcc06e64e545f2d146c"},
|
||||
{url = "https://files.pythonhosted.org/packages/5f/71/ad106c6e3a28f7ff81b2e172a05c158181b61de2a6292896355f0e50f46c/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c7025dce65566eb6e89f56c9509d4f628fddcedb131d9465cacd3d8bac337e7e"},
|
||||
{url = "https://files.pythonhosted.org/packages/6c/a8/3cb2d902c4094b6ad06f069b937c2696fd47c5fc02da107e33470f468534/Pillow-9.3.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:3dd6caf940756101205dffc5367babf288a30043d35f80936f9bfb37f8355b32"},
|
||||
{url = "https://files.pythonhosted.org/packages/6d/d2/610687610050eb3ce0ebdd0a3f87d4bb3f1637a89f9fe00060a080a167da/Pillow-9.3.0-1-cp37-cp37m-win32.whl", hash = "sha256:e6ea6b856a74d560d9326c0f5895ef8050126acfdc7ca08ad703eb0081e82b74"},
|
||||
{url = "https://files.pythonhosted.org/packages/6f/64/3acfbffd532ec2e82f69d4f22de9c29197540ae61926f5b7072654281e91/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa4107d1b306cdf8953edde0534562607fe8811b6c4d9a486298ad31de733b2"},
|
||||
{url = "https://files.pythonhosted.org/packages/77/56/bb8dc927b3c44df0ca938b4a17b08c59ef5e1e7cc06300bddf20d4e2935f/Pillow-9.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:276a5ca930c913f714e372b2591a22c4bd3b81a418c0f6635ba832daec1cbcfc"},
|
||||
{url = "https://files.pythonhosted.org/packages/78/8c/ae0c7cfb6cae4eb0946b7369258f78e3104c22eeffda45ad6228bc0838f5/Pillow-9.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3033fbe1feb1b59394615a1cafaee85e49d01b51d54de0cbf6aa8e64182518a1"},
|
||||
{url = "https://files.pythonhosted.org/packages/88/9f/012551c5a9d8b4d0304b66d16119b9c79bac052e0b0bd37de29b64c1bf0c/Pillow-9.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:073adb2ae23431d3b9bcbcff3fe698b62ed47211d0716b067385538a1b0f28b8"},
|
||||
{url = "https://files.pythonhosted.org/packages/8a/e8/124718316b3f4f9fa24e4b7e915d8e02d58d43a5e3c44fcbceef17d60647/Pillow-9.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b90f7616ea170e92820775ed47e136208e04c967271c9ef615b6fbd08d9af0e3"},
|
||||
{url = "https://files.pythonhosted.org/packages/a0/6c/6e11abff7f944b51dbeea1bdfe14ad21976858e822ef667fa4eb82ec6f7c/Pillow-9.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:41e0051336807468be450d52b8edd12ac60bebaa97fe10c8b660f116e50b30e4"},
|
||||
{url = "https://files.pythonhosted.org/packages/a1/81/10f4f9665ce366c7501141c973c755cd5c9ebe577886ebfa7ca3e9a115f0/Pillow-9.3.0-cp38-cp38-win32.whl", hash = "sha256:f1ff2ee69f10f13a9596480335f406dd1f70c3650349e2be67ca3139280cade0"},
|
||||
{url = "https://files.pythonhosted.org/packages/a7/9e/8acd4d170596fa876b0baaae3542de3b6d0a709b4652ce78285aff59e849/Pillow-9.3.0-cp37-cp37m-win32.whl", hash = "sha256:82409ffe29d70fd733ff3c1025a602abb3e67405d41b9403b00b01debc4c9a29"},
|
||||
{url = "https://files.pythonhosted.org/packages/ac/0b/cb7ecd88cea2422818057db720966bbb56bbcec3b359f4a5cafdf737d9e5/Pillow-9.3.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9aaa107275d8527e9d6e7670b64aabaaa36e5b6bd71a1015ddd21da0d4e06448"},
|
||||
{url = "https://files.pythonhosted.org/packages/af/7f/c5f7a35fd7053a4aee79c41fc4b125281745577c6ce3445e57ed8b4eff56/Pillow-9.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e0918e03aa0c72ea56edbb00d4d664294815aa11291a11504a377ea018330d3"},
|
||||
{url = "https://files.pythonhosted.org/packages/b7/34/7a88f5ec5f26ac68d3d7a158c67c0a610a4e6b6d22c35266d0e715485b09/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:6c738585d7a9961d8c2821a1eb3dcb978d14e238be3d70f0a706f7fa9316946b"},
|
||||
{url = "https://files.pythonhosted.org/packages/b9/b8/3e2c23766019a9a03ee26ac6b7af9392aba8574806ce10e5074733987240/Pillow-9.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1c7c8ae3864846fc95f4611c78129301e203aaa2af813b703c55d10cc1628535"},
|
||||
{url = "https://files.pythonhosted.org/packages/bb/0e/83dd785dff8d62b4d663391ac62390ffadfcdfa4bd11959742f90d02127c/Pillow-9.3.0-cp39-cp39-win32.whl", hash = "sha256:bac18ab8d2d1e6b4ce25e3424f709aceef668347db8637c2296bcf41acb7cf48"},
|
||||
{url = "https://files.pythonhosted.org/packages/bc/28/0bcf18f0c22cd89626ee2e071edbe5736d54f9031fe986ae94389776864b/Pillow-9.3.0-cp310-cp310-win32.whl", hash = "sha256:655a83b0058ba47c7c52e4e2df5ecf484c1b0b0349805896dd350cbc416bdd91"},
|
||||
{url = "https://files.pythonhosted.org/packages/be/3e/a757fd2fdd5814aa0e9e1e838f79d33e0098e10a2e3afb7acdcb72278290/Pillow-9.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03150abd92771742d4a8cd6f2fa6246d847dcd2e332a18d0c15cc75bf6703040"},
|
||||
{url = "https://files.pythonhosted.org/packages/c0/47/4023dab2d77ea3f687939770b06e0c191b4a5a20590f158a6e8dbb03e357/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:77ec3e7be99629898c9a6d24a09de089fa5356ee408cdffffe62d67bb75fdd72"},
|
||||
{url = "https://files.pythonhosted.org/packages/c0/8f/dfa473f3a6241bff91ae8bb905bd0afceb827f37de2917a94b5c4b1112bf/Pillow-9.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:b472b5ea442148d1c3e2209f20f1e0bb0eb556538690fa70b5e1f79fa0ba8dc2"},
|
||||
{url = "https://files.pythonhosted.org/packages/c1/c3/be8222fce0553e05264bfe66f2cc73483567b961f144acef88753fba9c6c/Pillow-9.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d77adcd56a42d00cc1be30843d3426aa4e660cab4a61021dc84467123f7a00c"},
|
||||
{url = "https://files.pythonhosted.org/packages/c2/1d/5d0fd887bb790a42a9efb7fe742358f1eae332ee3120a7d4f79ee37358c9/Pillow-9.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:57751894f6618fd4308ed8e0c36c333e2f5469744c34729a27532b3db106ee20"},
|
||||
{url = "https://files.pythonhosted.org/packages/c8/7c/f5fe5b37b6a8f2218db98f33d2278f2900e0fc4ef019cd4d9e522d6e3206/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae5331c23ce118c53b172fa64a4c037eb83c9165aba3a7ba9ddd3ec9fa64a699"},
|
||||
{url = "https://files.pythonhosted.org/packages/c9/b8/27c526c45f482450a53c0faab6c0c4baf9cddee0a8f879a8526f7dd8adf0/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:828989c45c245518065a110434246c44a56a8b2b2f6347d1409c787e6e4651ee"},
|
||||
{url = "https://files.pythonhosted.org/packages/ca/97/9677bf1d97c408779e5940b89675e38a8ebe8bcc9dbae8adfc9e7080a314/Pillow-9.3.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:73bd195e43f3fadecfc50c682f5055ec32ee2c933243cafbfdec69ab1aa87cad"},
|
||||
{url = "https://files.pythonhosted.org/packages/cf/22/fed65d07e5e7b19cc608754e940a9b101bebe78cb6cd9d764639717848a4/Pillow-9.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:ebf2029c1f464c59b8bdbe5143c79fa2045a581ac53679733d3a91d400ff9efb"},
|
||||
{url = "https://files.pythonhosted.org/packages/d0/ae/b5e8750a7e745926e2227a43766d905c8c6a0f03739c7aec5aea9e975355/Pillow-9.3.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:871b72c3643e516db4ecf20efe735deb27fe30ca17800e661d769faab45a18d7"},
|
||||
{url = "https://files.pythonhosted.org/packages/d1/6f/b5e87428a5566563b6d661824c694bbc4b0386aed1c939b9aec47d9ee573/Pillow-9.3.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22b012ea2d065fd163ca096f4e37e47cd8b59cf4b0fd47bfca6abb93df70b34c"},
|
||||
{url = "https://files.pythonhosted.org/packages/d4/0d/e8f6ed8e2328007020bb242a0443d925f23ee06d059486c5f1308f2a5e26/Pillow-9.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:18498994b29e1cf86d505edcb7edbe814d133d2232d256db8c7a8ceb34d18cef"},
|
||||
{url = "https://files.pythonhosted.org/packages/d5/31/b026f9f7c87adf8027f51f98f392f6558982485b7202af5f9276492b2141/Pillow-9.3.0-1-cp37-cp37m-win_amd64.whl", hash = "sha256:32a44128c4bdca7f31de5be641187367fe2a450ad83b833ef78910397db491aa"},
|
||||
{url = "https://files.pythonhosted.org/packages/d5/79/191ea841f818aba4eb9783b9f91a3c16c51deff7326f5a2f47de54959a28/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dbb8e7f2abee51cef77673be97760abff1674ed32847ce04b4af90f610144c7b"},
|
||||
{url = "https://files.pythonhosted.org/packages/d6/be/996d629efd03aa305472a17183fcdfe2dd8529acea767d0ba2242d90cbfa/Pillow-9.3.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:801ec82e4188e935c7f5e22e006d01611d6b41661bba9fe45b60e7ac1a8f84de"},
|
||||
{url = "https://files.pythonhosted.org/packages/db/b0/6438c96e80d4cad5b6381ba774018de9d8eae591d65bdfd80e3ad630928a/Pillow-9.3.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:97aabc5c50312afa5e0a2b07c17d4ac5e865b250986f8afe2b02d772567a380c"},
|
||||
{url = "https://files.pythonhosted.org/packages/dc/20/30e5ea4ecb35b36d9bc4ff4e8edc048e017a8e3d2e087a512b0622bfdde3/Pillow-9.3.0-cp311-cp311-win32.whl", hash = "sha256:3168434d303babf495d4ba58fc22d6604f6e2afb97adc6a423e917dab828939c"},
|
||||
{url = "https://files.pythonhosted.org/packages/e0/59/74d88751801101259abd695f77c44b97a828b6a4e7981a79a75d2c3379ae/Pillow-9.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:502526a2cbfa431d9fc2a079bdd9061a2397b842bb6bc4239bb176da00993812"},
|
||||
{url = "https://files.pythonhosted.org/packages/ec/4f/bc65f543b4d774d6c888cb0936a8b91cf7c5fbb25e16f923e332822b279b/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b4012d06c846dc2b80651b120e2cdd787b013deb39c09f407727ba90015c684f"},
|
||||
{url = "https://files.pythonhosted.org/packages/f1/e4/2f7e4efeb79ab0a2c5ecba320b2e5a3aad7a49cc543407f4c1268ed804bb/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:0b07fffc13f474264c336298d1b4ce01d9c5a011415b79d4ee5527bb69ae6f65"},
|
||||
{url = "https://files.pythonhosted.org/packages/f7/11/763c3992c3e6d00e9f6de81b0d721306757bb7201155d135a16032460943/Pillow-9.3.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:ad58d27a5b0262c0c19b47d54c5802db9b34d38bbf886665b626aff83c74bacd"},
|
||||
{url = "https://files.pythonhosted.org/packages/fc/12/32101461796addca02fd14dc4d2b76068a2cbf895002ed668550caf3fcc1/Pillow-9.3.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:be55f8457cd1eac957af0c3f5ece7bc3f033f89b114ef30f710882717670b2a8"},
|
||||
]
|
||||
"preprocess-cancellation 0.2.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/64/45/8043211de9ecddf6c25fdd743abb168b198a4ee5e417012ec8f10c6ac91f/preprocess_cancellation-0.2.0-py3-none-any.whl", hash = "sha256:936e2d6f95eaf1c0dd8a00d4c9a0663fbb3ea9a6504bde36aa63509e079d9ee7"},
|
||||
{url = "https://files.pythonhosted.org/packages/96/02/c8bd237196ca3ec99b0757744e591b3d7c64d7269c991bb7ca50008b6f8d/preprocess_cancellation-0.2.0.tar.gz", hash = "sha256:eb68494e35c0a1fe83716f2a14e12b3e1cdedf9458752be1cace00f944d90760"},
|
||||
]
|
||||
"pyasn1 0.4.8" = [
|
||||
{url = "https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl", hash = "sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d"},
|
||||
{url = "https://files.pythonhosted.org/packages/a4/db/fffec68299e6d7bad3d504147f9094830b704527a7fc098b721d38cc7fa7/pyasn1-0.4.8.tar.gz", hash = "sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba"},
|
||||
]
|
||||
"pyserial 3.4" = [
|
||||
{url = "https://files.pythonhosted.org/packages/0d/e4/2a744dd9e3be04a0c0907414e2a01a7c88bb3915cbe3c8cc06e209f59c30/pyserial-3.4-py2.py3-none-any.whl", hash = "sha256:e0770fadba80c31013896c7e6ef703f72e7834965954a78e71a3049488d4d7d8"},
|
||||
{url = "https://files.pythonhosted.org/packages/cc/74/11b04703ec416717b247d789103277269d567db575d2fd88f25d9767fe3d/pyserial-3.4.tar.gz", hash = "sha256:6e2d401fdee0eab996cf734e67773a0143b932772ca8b42451440cfed942c627"},
|
||||
]
|
||||
"pyserial-asyncio 0.6" = [
|
||||
{url = "https://files.pythonhosted.org/packages/27/24/c820cf15f87f7b164e83710c1852d4f900d9793961579e5ef64189bc0c10/pyserial_asyncio-0.6-py3-none-any.whl", hash = "sha256:de9337922619421b62b9b1a84048634b3ac520e1d690a674ed246a2af7ce1fc5"},
|
||||
{url = "https://files.pythonhosted.org/packages/4a/9a/8477699dcbc1882ea51dcff4d3c25aa3f2063ed8f7d7a849fd8f610506b6/pyserial-asyncio-0.6.tar.gz", hash = "sha256:b6032923e05e9d75ec17a5af9a98429c46d2839adfaf80604d52e0faacd7a32f"},
|
||||
]
|
||||
"pyyaml 6.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/02/25/6ba9f6bb50a3d4fbe22c1a02554dc670682a07c8701d1716d19ddea2c940/PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5"},
|
||||
{url = "https://files.pythonhosted.org/packages/08/f4/ffa743f860f34a5e8c60abaaa686f82c9ac7a2b50e5a1c3b1eb564d59159/PyYAML-6.0-cp39-cp39-win_amd64.whl", hash = "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c"},
|
||||
{url = "https://files.pythonhosted.org/packages/0f/93/5f81d1925ce3b531f5ff215376445ec220887cd1c9a8bde23759554dbdfd/PyYAML-6.0-cp310-cp310-win32.whl", hash = "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513"},
|
||||
{url = "https://files.pythonhosted.org/packages/12/fc/a4d5a7554e0067677823f7265cb3ae22aed8a238560b5133b58cda252dad/PyYAML-6.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0"},
|
||||
{url = "https://files.pythonhosted.org/packages/21/67/b42191239c5650c9e419c4a08a7a022bbf1abf55b0391c380a72c3af5462/PyYAML-6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803"},
|
||||
{url = "https://files.pythonhosted.org/packages/2e/b3/13dfd4eeb5e4b2d686b6d1822b40702e991bf3a4194ca5cbcce8d43749db/PyYAML-6.0-cp39-cp39-win32.whl", hash = "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb"},
|
||||
{url = "https://files.pythonhosted.org/packages/36/2b/61d51a2c4f25ef062ae3f74576b01638bebad5e045f747ff12643df63844/PyYAML-6.0.tar.gz", hash = "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"},
|
||||
{url = "https://files.pythonhosted.org/packages/44/e5/4fea13230bcebf24b28c0efd774a2dd65a0937a2d39e94a4503438b078ed/PyYAML-6.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53"},
|
||||
{url = "https://files.pythonhosted.org/packages/4d/7d/c2ab8da648cd2b937de11fb35649b127adab4851cbeaf5fd9b60a2dab0f7/PyYAML-6.0-cp36-cp36m-win32.whl", hash = "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293"},
|
||||
{url = "https://files.pythonhosted.org/packages/55/e3/507a92589994a5b3c3d7f2a7a066339d6ff61c5c839bae56f7eff03d9c7b/PyYAML-6.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86"},
|
||||
{url = "https://files.pythonhosted.org/packages/56/8f/e8b49ad21d26111493dc2d5cae4d7efbd0e2e065440665f5023515f87f64/PyYAML-6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:432557aa2c09802be39460360ddffd48156e30721f5e8d917f01d31694216782"},
|
||||
{url = "https://files.pythonhosted.org/packages/59/00/30e33fcd2a4562cd40c49c7740881009240c5cbbc0e41ca79ca4bba7c24b/PyYAML-6.0-cp311-cp311-win_amd64.whl", hash = "sha256:01b45c0191e6d66c470b6cf1b9531a771a83c1c4208272ead47a3ae4f2f603bf"},
|
||||
{url = "https://files.pythonhosted.org/packages/5e/f4/7b4bb01873be78fc9fde307f38f62e380b7111862c165372cf094ca2b093/PyYAML-6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc"},
|
||||
{url = "https://files.pythonhosted.org/packages/63/6b/f5dc7942bac17192f4ef00b2d0cdd1ae45eea453d05c1944c0573debe945/PyYAML-6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34"},
|
||||
{url = "https://files.pythonhosted.org/packages/67/d4/b95266228a25ef5bd70984c08b4efce2c035a4baa5ccafa827b266e3dc36/PyYAML-6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174"},
|
||||
{url = "https://files.pythonhosted.org/packages/68/3f/c027422e49433239267c62323fbc6320d6ac8d7d50cf0cb2a376260dad5f/PyYAML-6.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dbad0e9d368bb989f4515da330b88a057617d16b6a8245084f1b05400f24609f"},
|
||||
{url = "https://files.pythonhosted.org/packages/6c/3d/524c642f3db37e7e7ab8d13a3f8b0c72d04a619abc19100097d987378fc6/PyYAML-6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba"},
|
||||
{url = "https://files.pythonhosted.org/packages/74/68/3c13deaa496c14a030c431b7b828d6b343f79eb241b4848c7918091a64a2/PyYAML-6.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92"},
|
||||
{url = "https://files.pythonhosted.org/packages/77/da/e845437ffe0dffae4e7562faf23a4f264d886431c5d2a2816c853288dc8e/PyYAML-6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3"},
|
||||
{url = "https://files.pythonhosted.org/packages/7f/d9/6a0d14ac8d3b5605dc925d177c1d21ee9f0b7b39287799db1e50d197b2f4/PyYAML-6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa17f5bc4d1b10afd4466fd3a44dc0e245382deca5b3c353d8b757f9e3ecb8d"},
|
||||
{url = "https://files.pythonhosted.org/packages/81/59/561f7e46916b78f3c4cab8d0c307c81656f11e32c846c0c97fda0019ed76/PyYAML-6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4"},
|
||||
{url = "https://files.pythonhosted.org/packages/89/26/0bfd7b756b34c68f8fd158b7bc762b6b1705fc1b3cebf4cdbb53fd9ea75b/PyYAML-6.0-cp36-cp36m-win_amd64.whl", hash = "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57"},
|
||||
{url = "https://files.pythonhosted.org/packages/91/49/d46d7b15cddfa98533e89f3832f391aedf7e31f37b4d4df3a7a7855a7073/PyYAML-6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c"},
|
||||
{url = "https://files.pythonhosted.org/packages/9d/f6/7e91fbb58c9ee528759aea5892e062cccb426720c5830ddcce92eba00ff1/PyYAML-6.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c"},
|
||||
{url = "https://files.pythonhosted.org/packages/a4/ba/e508fc780e3c94c12753a54fe8f74de535741a10d33b29a576a9bec03500/PyYAML-6.0-cp38-cp38-win32.whl", hash = "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78"},
|
||||
{url = "https://files.pythonhosted.org/packages/a4/e6/4d7a01bc0730c8f958a62d6a4c4f3df23b6139ad68c132b168970d84f192/PyYAML-6.0-cp37-cp37m-win32.whl", hash = "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737"},
|
||||
{url = "https://files.pythonhosted.org/packages/a8/32/1bbe38477fb23f1d83041fefeabf93ef1cd6f0efcf44c221519507315d92/PyYAML-6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f"},
|
||||
{url = "https://files.pythonhosted.org/packages/a8/5b/c4d674846ea4b07ee239fbf6010bcc427c4e4552ba5655b446e36b9a40a7/PyYAML-6.0-cp38-cp38-win_amd64.whl", hash = "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07"},
|
||||
{url = "https://files.pythonhosted.org/packages/b3/85/79b9e5b4e8d3c0ac657f4e8617713cca8408f6cdc65d2ee6554217cedff1/PyYAML-6.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4"},
|
||||
{url = "https://files.pythonhosted.org/packages/b7/09/2f6f4851bbca08642fef087bade095edc3c47f28d1e7bff6b20de5262a77/PyYAML-6.0-cp310-cp310-win_amd64.whl", hash = "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a"},
|
||||
{url = "https://files.pythonhosted.org/packages/cb/5f/05dd91f5046e2256e35d885f3b8f0f280148568f08e1bf20421887523e9a/PyYAML-6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:81957921f441d50af23654aa6c5e5eaf9b06aba7f0a19c18a538dc7ef291c5a1"},
|
||||
{url = "https://files.pythonhosted.org/packages/d1/c0/4fe04181b0210ee2647cfbb89ecd10a36eef89f10d8aca6a192c201bbe58/PyYAML-6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d"},
|
||||
{url = "https://files.pythonhosted.org/packages/d7/42/7ad4b6d67a16229496d4f6e74201bdbebcf4bc1e87d5a70c9297d4961bd2/PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287"},
|
||||
{url = "https://files.pythonhosted.org/packages/db/4e/74bc723f2d22677387ab90cd9139e62874d14211be7172ed8c9f9a7c81a9/PyYAML-6.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b"},
|
||||
{url = "https://files.pythonhosted.org/packages/df/75/ee0565bbf65133e5b6ffa154db43544af96ea4c42439e6b58c1e0eb44b4e/PyYAML-6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0"},
|
||||
{url = "https://files.pythonhosted.org/packages/eb/5f/6e6fe6904e1a9c67bc2ca5629a69e7a5a0b17f079da838bab98a1e548b25/PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9"},
|
||||
{url = "https://files.pythonhosted.org/packages/ef/ad/b443cce94539e57e1a745a845f95c100ad7b97593d7e104051e43f730ecd/PyYAML-6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b"},
|
||||
{url = "https://files.pythonhosted.org/packages/f5/6f/b8b4515346af7c33d3b07cd8ca8ea0700ca72e8d7a750b2b87ac0268ca4e/PyYAML-6.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b"},
|
||||
{url = "https://files.pythonhosted.org/packages/f8/54/799b059314b13e1063473f76e908f44106014d18f54b16c83a16edccd5ec/PyYAML-6.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d4b0ba9512519522b118090257be113b9468d804b19d63c71dbcf4a48fa32358"},
|
||||
{url = "https://files.pythonhosted.org/packages/fc/48/531ecd926fe0a374346dd811bf1eda59a95583595bb80eadad511f3269b8/PyYAML-6.0-cp311-cp311-win32.whl", hash = "sha256:bfaef573a63ba8923503d27530362590ff4f576c626d86a9fed95822a8255fd7"},
|
||||
]
|
||||
"requests 2.28.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/9d/ee/391076f5937f0a8cdf5e53b701ffc91753e87b07d66bae4a09aa671897bf/requests-2.28.2.tar.gz", hash = "sha256:98b1b2782e3c6c4904938b84c0eb932721069dfdb9134313beff7c83c2df24bf"},
|
||||
{url = "https://files.pythonhosted.org/packages/d2/f4/274d1dbe96b41cf4e0efb70cbced278ffd61b5c7bb70338b62af94ccb25b/requests-2.28.2-py3-none-any.whl", hash = "sha256:64299f4909223da747622c030b781c0d7811e359c37124b4bd368fb8c6518baa"},
|
||||
]
|
||||
"requests-oauthlib 1.3.1" = [
|
||||
{url = "https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl", hash = "sha256:2577c501a2fb8d05a304c09d090d6e47c306fef15809d102b327cf8364bddab5"},
|
||||
{url = "https://files.pythonhosted.org/packages/95/52/531ef197b426646f26b53815a7d2a67cb7a331ef098bb276db26a68ac49f/requests-oauthlib-1.3.1.tar.gz", hash = "sha256:75beac4a47881eeb94d5ea5d6ad31ef88856affe2332b9aafb52c6452ccf0d7a"},
|
||||
]
|
||||
"streaming-form-data 1.11.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/04/2f/2f35fbb41fc402f379081cf32f78cd750304fcb801b01d1307831225222b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:fe46eff0cb5aebcc752c7ee3258bbeaa6aa9007bad9c32cfbd46d00df5c1f4d4"},
|
||||
{url = "https://files.pythonhosted.org/packages/08/7f/dcffefffde61a3cdcac981a81ff57164c44b64c92154c69742bdc8a27a7d/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:52fd1ea2a8c0b4ac56b99903214e239f0e8b9266f65c8cae6c00787aaf1f9cfe"},
|
||||
{url = "https://files.pythonhosted.org/packages/0a/f1/a9f862f8d097371ca464ff723221568010762c55d2cdcc200821048d29e0/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:ab59d14825cb4ed9d96eb17a2f78f5a96935fb4e8e6b98fcae5ce07fcd6e0fa9"},
|
||||
{url = "https://files.pythonhosted.org/packages/1d/cc/9110eaa9a045274d7ff48a66e9185af64ba42349ab7d9da0828606fa06bc/streaming_form_data-1.11.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9ff76ec968a1c04dcc94fd66fae343b9fc576cb455fdd3f93370dad5fa1d8771"},
|
||||
{url = "https://files.pythonhosted.org/packages/1f/55/d09ebcc68fc24c15bea4c119247f4da38afbaefc302bfc90f567e3ab8394/streaming_form_data-1.11.0-cp36-cp36m-win_amd64.whl", hash = "sha256:5dfb34b8e147c4f30ada3ab333b517cbc8c273e06a0f464c85f92e70647bbbd6"},
|
||||
{url = "https://files.pythonhosted.org/packages/2c/6c/a6666cadf14b7bcb27f214a2325b9c72a35a0f3f34fbcda3890e53488468/streaming-form-data-1.11.0.tar.gz", hash = "sha256:202cea84200e8d412dd22b3ae522e1896a8a7d041aae809278b003b64ed1712b"},
|
||||
{url = "https://files.pythonhosted.org/packages/39/0c/5f68bd2f004a66af88b1509d15e8aab121a83d94b15103eef347a8378953/streaming_form_data-1.11.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:e551dc5604af5b971224c5c82c132ec8d99bc3da627ad6228ff899f1b1043839"},
|
||||
{url = "https://files.pythonhosted.org/packages/3c/3f/2a637fee6d3ec836a24d3deb0bad343aec76458b24aebf5599d7265e0255/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:5358cc32bf775944d366525c2854620e55548563f40868f01ea4af6f252b682b"},
|
||||
{url = "https://files.pythonhosted.org/packages/3f/2c/120ddd55d727e63a93a05e5da17a9d54f26570bf6cb5353211a0191bd858/streaming_form_data-1.11.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a780dc298ff4da1d20c9deae02f817c08de59e0094b591627727efe6e94574af"},
|
||||
{url = "https://files.pythonhosted.org/packages/4b/70/7a372bddb2e413170fe3a2f90a4aef33efd8aa655b7dadf521d19512895e/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:f7bf111cd071853089b3904ec9dd9250959a45e88ea05ce078b2632375597cef"},
|
||||
{url = "https://files.pythonhosted.org/packages/57/66/82ac7a98357c2062890cd2c2a19d7081ab877808bc49f5e8da779e7c63be/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:1eccecf020053de8bfba7844ac9e0ed2cb1ca2a3d39980aa9077ca3f31048b1f"},
|
||||
{url = "https://files.pythonhosted.org/packages/63/6f/3df5b7b134c1d3e971a0319b9ffce963269cdab4810cd9977fff9fb22963/streaming_form_data-1.11.0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:27a21a95d9d05448f638c049b2da1406a6d4ac357c6e8bec4268d9a2f99bdd76"},
|
||||
{url = "https://files.pythonhosted.org/packages/6e/00/c562082e709b96c54956a8631dcf086895a2504f46c25bbc1fa60e1b961b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:1428e0fe38d7d5dea984a772a235955a4f4e6e846d2f377239b7b8a42b2ab455"},
|
||||
{url = "https://files.pythonhosted.org/packages/89/59/632ec49c341df95597f291eb7e818749287089b7166823b1e5397d1e855a/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:301dba4f0b634d4e7e632172cc9fb6e0db136ce6a12b0f5cf118d25f0aaa484e"},
|
||||
{url = "https://files.pythonhosted.org/packages/9a/c5/4d6b7a2bc2b01c0f2085db522cb0c2785dd011e5d9f13c8b35c987a79e55/streaming_form_data-1.11.0-cp39-cp39-win_amd64.whl", hash = "sha256:d33096083ae86837b7f8dfd3653b7cf87044d7ffb6b52102114e46a74a3a1164"},
|
||||
{url = "https://files.pythonhosted.org/packages/a3/64/efed10d21c999c79d87f7b187c861918c80af1e8243ab4f1d3fafcca0625/streaming_form_data-1.11.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:adc810f256214af1dc45b9351cca1f8e7af60fb9de07bb3ab9ba1379770c51f7"},
|
||||
{url = "https://files.pythonhosted.org/packages/af/d7/da423d9a38e9459089155d8583e32e46ca61f6ae5f429022557603ff721d/streaming_form_data-1.11.0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:1fbdd0df497465524e2010ae1465582663c9fb2a1f933075fddb6710a0cf9f17"},
|
||||
{url = "https://files.pythonhosted.org/packages/b2/2e/1d6a4ffe8650af67f3dbd9b84d2d369df14edc4559f4afb53c72914a1010/streaming_form_data-1.11.0-cp37-cp37m-win_amd64.whl", hash = "sha256:cf8de78d747e95db780cd18672783735bcb811ea495b8e4546c8fa534829d90d"},
|
||||
{url = "https://files.pythonhosted.org/packages/bc/f6/804ff40efb9de1f4256f60e3faa507058349bc9086c5adad568692216a28/streaming_form_data-1.11.0-cp38-cp38-win32.whl", hash = "sha256:70321f427e0600c7d5b74fd8f91a4478edb92143bd9fd051dd11a18c1e08a37c"},
|
||||
{url = "https://files.pythonhosted.org/packages/be/b0/91c341a58ea61c12c56dfc9ab101e495c08632bb74b1e6247e32641aea55/streaming_form_data-1.11.0-cp39-cp39-win32.whl", hash = "sha256:b208c0918cdf2e274d286c78f3f6b1fd5e9c0cf35bc1dc33a60d1c3c4edf0b51"},
|
||||
{url = "https://files.pythonhosted.org/packages/d0/5b/f7ab5b7357fa274ce76f159d67ca6e52103e626ff9bbc82fc55cfa172888/streaming_form_data-1.11.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:f348e67d55dcb60ce8571647dd0e18aa4205091c9c1d1f1b0ee2816e8f612421"},
|
||||
{url = "https://files.pythonhosted.org/packages/d3/28/b6cabf9b1e0c50140162bc369ff65d3535cef459f0264822d77b72a80ada/streaming_form_data-1.11.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:b073baa08f349ab4737ebb673e8dc5c4cd19be6c8d18f43262e659d95b290733"},
|
||||
{url = "https://files.pythonhosted.org/packages/d8/e9/79041e6ed6b2ed56d8928eabaa5943da273dea3caf7b2e628c4a8c8e9a03/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:5bffc52d57f6733c5462b8fb19b4d7ce54c2faea3c7d5b12725b86740be1c7c9"},
|
||||
{url = "https://files.pythonhosted.org/packages/df/63/c4fc00a6b4808b97f1fc46c2682a5154b81b99d2d3f2f4cd8bc61190426d/streaming_form_data-1.11.0-cp36-cp36m-win32.whl", hash = "sha256:8db536c6387d27b2ce9b89e58269ff79d8da197f1f3c300f53dc130271bb5f78"},
|
||||
{url = "https://files.pythonhosted.org/packages/e0/4c/99315996886639c3887d5030f172ec14b6ffe5c9fffc4386ffbca95f3eff/streaming_form_data-1.11.0-cp38-cp38-win_amd64.whl", hash = "sha256:406cd5a23eef77f360b549b93fa64a8ee724309063ab1dce528e1c8e397cb56f"},
|
||||
{url = "https://files.pythonhosted.org/packages/e0/51/09006f1ec2b562e3ca6d6fe82f878d8b2c66cd0ef56ce85d6225b8a6acc6/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:aa07f1c565436319862abb338e3a9ae68855b09fc5ceb83564c34a53af852c52"},
|
||||
{url = "https://files.pythonhosted.org/packages/e2/91/a1172ef7d998efb97fe9fd5a56f13fad43d56bf7c53c87ec96c379654b53/streaming_form_data-1.11.0-cp37-cp37m-win32.whl", hash = "sha256:267a4921decbd3a800463d72b6a8df362e17cad7825924a5a61e3cbc7bacf96d"},
|
||||
{url = "https://files.pythonhosted.org/packages/ee/1e/0c7f836410c809d9001c31fb2bf31bdc40a38671fc8e6820021e0f8cd878/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:1d56ac0fb880cb8143cbfd5c67361fc6caa0ab5e9863074555304ad27c1d0e2b"},
|
||||
{url = "https://files.pythonhosted.org/packages/f0/37/5f4162304049e1a25974de914c9e21543bafd2218b396c2c3a313d575126/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:89a20560924bbbd07fc51f3f7b6710744e8b845028a9af338b6caa9c2611f7bb"},
|
||||
]
|
||||
"tornado 6.2" = [
|
||||
{url = "https://files.pythonhosted.org/packages/11/30/ac70f5c5f03cf1cd0ae8199c80382387a9fe57e8f68853d5c9527c0219e5/tornado-6.2-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b8150f721c101abdef99073bf66d3903e292d851bee51910839831caba341a75"},
|
||||
{url = "https://files.pythonhosted.org/packages/19/bb/b6c3d1668d2b10ad38a584f3a1ec9737984e274f8b708e09fcbb96427f5c/tornado-6.2-cp37-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3a2f5999215a3a06a4fc218026cd84c61b8b2b40ac5296a6db1f1451ef04c1e"},
|
||||
{url = "https://files.pythonhosted.org/packages/1c/26/cbfa1103e74a02e09dd53291e419da3ad4c5b948f52aea5800e6671b56e0/tornado-6.2-cp37-abi3-win_amd64.whl", hash = "sha256:e5f923aa6a47e133d1cf87d60700889d7eae68988704e20c75fb2d65677a8e4b"},
|
||||
{url = "https://files.pythonhosted.org/packages/5c/0c/cbc0a98f7b8ef833bcb13c58d35d09e2c288ae67a35af4c8960b88f99ae9/tornado-6.2-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:87dcafae3e884462f90c90ecc200defe5e580a7fbbb4365eda7c7c1eb809ebc9"},
|
||||
{url = "https://files.pythonhosted.org/packages/60/08/e630a348b34a9ddd640aed67dafc6f0df425d8ac07d2fa60288f38321c69/tornado-6.2-cp37-abi3-musllinux_1_1_i686.whl", hash = "sha256:6fdfabffd8dfcb6cf887428849d30cf19a3ea34c2c248461e1f7d718ad30b66b"},
|
||||
{url = "https://files.pythonhosted.org/packages/71/cc/c1342382484d0178a79029109c433e406a60095da1c3605ca966775a70e5/tornado-6.2-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ba09ef14ca9893954244fd872798b4ccb2367c165946ce2dd7376aebdde8e3ac"},
|
||||
{url = "https://files.pythonhosted.org/packages/cd/a4/761e45cea12b2af076d36240d464b371ab1231272948cdc49b7d81855c5c/tornado-6.2-cp37-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:5f8c52d219d4995388119af7ccaa0bcec289535747620116a58d830e7c25d8a8"},
|
||||
{url = "https://files.pythonhosted.org/packages/ec/01/93e63530851ba8ef9685f1a9b91e324b28d28323a6b67400114ea65c5110/tornado-6.2-cp37-abi3-win32.whl", hash = "sha256:5c87076709343557ef8032934ce5f637dbb552efa7b21d08e89ae7619ed0eb23"},
|
||||
{url = "https://files.pythonhosted.org/packages/f3/9e/225a41452f2d9418d89be5e32cf824c84fe1e639d350d6e8d49db5b7f73a/tornado-6.2.tar.gz", hash = "sha256:9b630419bde84ec666bfd7ea0a4cb2a8a651c2d5cccdbdd1972a0c859dfc3c13"},
|
||||
{url = "https://files.pythonhosted.org/packages/f9/51/6f63a166d9a3077be100cbb13dcbce434e5654daaaa7003b0a045b9f6edf/tornado-6.2-cp37-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:1d54d13ab8414ed44de07efecb97d4ef7c39f7438cf5e976ccd356bebb1b5fca"},
|
||||
{url = "https://files.pythonhosted.org/packages/fb/bd/074254a55bfc82d7a1886abbd803600ef01cbd76ee66bc30307b2724130b/tornado-6.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:20f638fd8cc85f3cbae3c732326e96addff0a15e22d80f049e00121651e82e72"},
|
||||
]
|
||||
"typing-extensions 4.4.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/0b/8e/f1a0a5a76cfef77e1eb6004cb49e5f8d72634da638420b9ea492ce8305e8/typing_extensions-4.4.0-py3-none-any.whl", hash = "sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e"},
|
||||
{url = "https://files.pythonhosted.org/packages/e3/a7/8f4e456ef0adac43f452efc2d0e4b242ab831297f1bac60ac815d37eb9cf/typing_extensions-4.4.0.tar.gz", hash = "sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa"},
|
||||
]
|
||||
"urllib3 1.26.14" = [
|
||||
{url = "https://files.pythonhosted.org/packages/c5/52/fe421fb7364aa738b3506a2d99e4f3a56e079c0a798e9f4fa5e14c60922f/urllib3-1.26.14.tar.gz", hash = "sha256:076907bf8fd355cde77728471316625a4d2f7e713c125f51953bb5b3eecf4f72"},
|
||||
{url = "https://files.pythonhosted.org/packages/fe/ca/466766e20b767ddb9b951202542310cba37ea5f2d792dae7589f1741af58/urllib3-1.26.14-py2.py3-none-any.whl", hash = "sha256:75edcdc2f7d85b137124a6c3c9fc3933cdeaa12ecb9a6a959f22797a0feca7e1"},
|
||||
]
|
||||
"zeroconf 0.39.4" = [
|
||||
{url = "https://files.pythonhosted.org/packages/3f/ff/a8d7faaa3573b6e4c775cacbf911a0afbcb4928ce71b3de43119227a396a/zeroconf-0.39.4-py3-none-any.whl", hash = "sha256:d60eae9e9c99d1a168ce9ff9de7e7398c23754a0c2004ded230f8d529c5260a0"},
|
||||
{url = "https://files.pythonhosted.org/packages/f5/4f/c47cea73d7ae5467b63de3999d7207fd5b14d70cb2f35ce81c4ab7d7a52e/zeroconf-0.39.4.tar.gz", hash = "sha256:701e4d697f89fe952aa9c13a512ed6bf472dcf4f0a6d275e71085604b3882295"},
|
||||
]
|
||||
"zipp 3.13.0" = [
|
||||
{url = "https://files.pythonhosted.org/packages/95/7b/1608a7344743f54a8c072d64d2a279934fd204d6d015278b0a0ed4ce104b/zipp-3.13.0-py3-none-any.whl", hash = "sha256:e8b2a36ea17df80ffe9e2c4fda3f693c3dad6df1697d3cd3af232db680950b0b"},
|
||||
{url = "https://files.pythonhosted.org/packages/d1/2f/ba544a8a6ad5ad9dcec1b00f536bb9fb078f5f50d1a1408876de18a9151b/zipp-3.13.0.tar.gz", hash = "sha256:23f70e964bc11a34cef175bc90ba2914e1e4545ea1e3e2f67c079671883f9cb6"},
|
||||
]
|
||||
@@ -0,0 +1,64 @@
|
||||
[project]
|
||||
name = "moonraker"
|
||||
dynamic = ["version"]
|
||||
description = "API Server for Klipper"
|
||||
authors = [
|
||||
{name = "Eric Callahan"},
|
||||
{email = "arksine.code@gmail.com"},
|
||||
]
|
||||
dependencies = [
|
||||
"tornado==6.2.0",
|
||||
"pyserial==3.4",
|
||||
"pyserial-asyncio==0.6",
|
||||
"pillow==9.3.0",
|
||||
"lmdb==1.3.0",
|
||||
"streaming-form-data==1.11.0",
|
||||
"distro==1.8.0",
|
||||
"inotify-simple==1.3.5",
|
||||
"libnacl==1.8.0",
|
||||
"paho-mqtt==1.6.1",
|
||||
"zeroconf==0.39.4",
|
||||
"preprocess-cancellation==0.2.0",
|
||||
"jinja2==3.1.2",
|
||||
"dbus-next==0.2.3",
|
||||
"apprise==1.2.1",
|
||||
"ldap3==2.9.1"
|
||||
]
|
||||
requires-python = ">=3.7"
|
||||
readme = "README.md"
|
||||
license = {text = "GPL-3.0-only"}
|
||||
keywords = ["klipper", "3D printing", "server", "moonraker"]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.7",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
homepage = "https://github.com/Arksine/moonraker"
|
||||
repository = "https://github.com/Arksine/moonraker"
|
||||
documentation = "https://moonraker.readthedocs.io"
|
||||
changelog = "https://moonraker.readthedocs.io/en/latest/changelog/"
|
||||
|
||||
[tool.pdm.version]
|
||||
source = "scm"
|
||||
write_to = "moonraker/__version__.py"
|
||||
write_template = "__version__ = '{}'\n"
|
||||
|
||||
[tool.pdm.build]
|
||||
excludes = ["./**/.git", "moonraker/moonraker.py"]
|
||||
includes = ["moonraker"]
|
||||
editable-backend = "path"
|
||||
custom-hook = "scripts/pdm_build_dist.py"
|
||||
|
||||
[project.scripts]
|
||||
moonraker = "moonraker.server:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["pdm-backend>=2.0.2"]
|
||||
build-backend = "pdm.backend"
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
[pytest]
|
||||
minversion = 7.0
|
||||
pythonpath = moonraker scripts
|
||||
testpaths = tests
|
||||
required_plugins =
|
||||
pytest-asyncio>=0.17.2
|
||||
pytest-timeout>=2.1.0
|
||||
asyncio_mode = strict
|
||||
timeout = 60
|
||||
timeout_method = signal
|
||||
markers =
|
||||
run_paths
|
||||
no_ws_connect
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/bin/bash
|
||||
# LMDB Database backup utility
|
||||
|
||||
DATABASE_PATH="${HOME}/printer_data/database"
|
||||
MOONRAKER_ENV="${HOME}/moonraker-env"
|
||||
OUPUT_FILE="${HOME}/database.backup"
|
||||
|
||||
print_help()
|
||||
{
|
||||
echo "Moonraker Database Backup Utility"
|
||||
echo
|
||||
echo "usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]"
|
||||
echo
|
||||
echo "optional arguments:"
|
||||
echo " -h show this message"
|
||||
echo " -e <env path> Moonraker Python Environment"
|
||||
echo " -d <database path> Moonraker LMDB database to backup"
|
||||
echo " -o <output file> backup file to save to"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "he:d:o:" arg; do
|
||||
case $arg in
|
||||
h) print_help;;
|
||||
e) MOONRAKER_ENV=$OPTARG;;
|
||||
d) DATABASE_PATH=$OPTARG;;
|
||||
o) OUPUT_FILE=$OPTARG;;
|
||||
esac
|
||||
done
|
||||
|
||||
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
|
||||
DB_TOOL="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/dbtool.py"
|
||||
|
||||
if [ ! -f $PYTHON_BIN ]; then
|
||||
echo "No Python binary found at '${PYTHON_BIN}'"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -f "$DATABASE_PATH/data.mdb" ]; then
|
||||
echo "No Moonraker database found at '${DATABASE_PATH}'"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -f $DB_TOOL ]; then
|
||||
echo "Unable to locate dbtool.py at '${DB_TOOL}'"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
${PYTHON_BIN} ${DB_TOOL} backup ${DATABASE_PATH} ${OUPUT_FILE}
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# This script builds a zipped source release for Moonraker and Klipper.
|
||||
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-dev curl"
|
||||
|
||||
# Update system package info
|
||||
report_status "Running apt-get update..."
|
||||
sudo apt-get update
|
||||
|
||||
# Install desired packages
|
||||
report_status "Installing packages..."
|
||||
sudo apt-get install --yes $PKGLIST
|
||||
}
|
||||
|
||||
report_status()
|
||||
{
|
||||
echo -e "\n\n###### $1"
|
||||
}
|
||||
|
||||
verify_ready()
|
||||
{
|
||||
if [ "$EUID" -eq 0 ]; then
|
||||
echo "This script must not run as root"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -d "$SRCDIR/.git" ]; then
|
||||
echo "This script must be run from a git repo"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -d "$KLIPPER_DIR/.git" ]; then
|
||||
echo "This script must be run from a git repo"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
# Force script to exit if an error occurs
|
||||
set -e
|
||||
|
||||
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
|
||||
OUTPUT_DIR="$SRCDIR/.dist"
|
||||
KLIPPER_DIR="$HOME/klipper"
|
||||
BETA=""
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "o:k:b" arg; do
|
||||
case $arg in
|
||||
o) OUTPUT_DIR=$OPTARG;;
|
||||
k) KLIPPER_DIR=$OPTARG;;
|
||||
b) BETA="-b";;
|
||||
esac
|
||||
done
|
||||
|
||||
[ ! -d $OUTPUT_DIR ] && mkdir $OUTPUT_DIR
|
||||
verify_ready
|
||||
if [ "$BETA" = "" ]; then
|
||||
releaseTag=$( git -C $KLIPPER_DIR describe --tags `git -C $KLIPPER_DIR rev-list --tags --max-count=1` )
|
||||
echo "Checking out Klipper release $releaseTag"
|
||||
git -C $KLIPPER_DIR checkout $releaseTag
|
||||
fi
|
||||
python3 "$SRCDIR/scripts/build_release.py" -k $KLIPPER_DIR -o $OUTPUT_DIR $BETA
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user