Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ed102edfb | ||
|
|
5b81a641d6 | ||
|
|
4ba6fd228f | ||
|
|
e8d4a66fc9 | ||
|
|
9fc3a70570 | ||
|
|
5f8a801a45 | ||
|
|
9e6eeead5b | ||
|
|
7e92d8a2a9 | ||
|
|
811347c663 | ||
|
|
fb257f8ab8 | ||
|
|
3fbe6ee218 | ||
|
|
293a4cfc21 | ||
|
|
179011f29f | ||
|
|
3252bc232b | ||
|
|
1e84ecaadd | ||
|
|
4637d70ac1 | ||
|
|
343bba4c60 | ||
|
|
3e29720cb2 | ||
|
|
290e537a84 | ||
|
|
16e530eb66 | ||
|
|
a577b061ac | ||
|
|
6e6d51c213 | ||
|
|
4baff7a54b | ||
|
|
7bcba99e37 | ||
|
|
74c5d8e44c | ||
|
|
bac55c65f8 | ||
|
|
63672ea38b | ||
|
|
4b751e79e1 | ||
|
|
3ea83163b0 | ||
|
|
0e8dd923f8 | ||
|
|
2b1c70a9e1 | ||
|
|
d7df2876dd | ||
|
|
3e6378fbc6 | ||
|
|
bdeddcabad | ||
|
|
b3f9566b8b | ||
|
|
5b92e52e29 | ||
|
|
058517b5b4 | ||
|
|
960e933837 | ||
|
|
37d46d284f | ||
|
|
be41e8ded6 | ||
|
|
3129d89f0f | ||
|
|
abd2026b90 | ||
|
|
8426f4107c | ||
|
|
3eb575d0ec | ||
|
|
f2bb93ffc4 | ||
|
|
5836eab233 | ||
|
|
0775e3f4fc | ||
|
|
1bc2189b72 | ||
|
|
9098675ede | ||
|
|
b11a791566 | ||
|
|
e22da356d1 | ||
|
|
72ca7dbe05 | ||
|
|
596e7d9e79 | ||
|
|
3fe343db57 | ||
|
|
a18a18c1b1 | ||
|
|
00170f3505 | ||
|
|
01963c45c1 | ||
|
|
fa90202eb9 | ||
|
|
df3965e896 | ||
|
|
b9b1c899b3 | ||
|
|
29083b7c49 | ||
|
|
52e315868b | ||
|
|
bbda9e2f55 | ||
|
|
f20feff6c6 | ||
|
|
77c9149348 | ||
|
|
cea6fbcf17 | ||
|
|
00720f5bf0 | ||
|
|
46913913be | ||
|
|
72b89d905e | ||
|
|
206fd4828d | ||
|
|
b1b515a1fb | ||
|
|
83034dd2fc | ||
|
|
3df6a1eafd | ||
|
|
8d4244ba87 | ||
|
|
3072882495 | ||
|
|
a6862fba03 | ||
|
|
8d67e65c7f | ||
|
|
a78e704b0d | ||
|
|
06cdffa169 | ||
|
|
3c1f31874a | ||
|
|
6ff9a7ca7a | ||
|
|
12bfb15d64 | ||
|
|
826f0e3ea3 | ||
|
|
bfdf2a91ef | ||
|
|
0cc941f7e0 | ||
|
|
bd266cdce2 | ||
|
|
0c848948b4 | ||
|
|
dbe0dc4d08 | ||
|
|
ccbfd64989 | ||
|
|
6d65a914a2 | ||
|
|
0310d0be9f | ||
|
|
1c12414972 | ||
|
|
5ee0adc553 | ||
|
|
7cdcca3cb4 | ||
|
|
63bcf0b99d | ||
|
|
b90c96524c | ||
|
|
1226a08176 | ||
|
|
ebaa6645b2 | ||
|
|
4eb23ef281 | ||
|
|
18f3da59b0 | ||
|
|
91b6bfbd09 | ||
|
|
4889a2dd38 | ||
|
|
9b4b3def44 | ||
|
|
f2d53fe386 | ||
|
|
31cb1fc94c | ||
|
|
4b4ca76558 | ||
|
|
62051108ea | ||
|
|
a0164e1575 | ||
|
|
c35353ed2a | ||
|
|
35cb7501c6 | ||
|
|
58f060730b | ||
|
|
cb39c8c88a | ||
|
|
a95405f800 | ||
|
|
1f4888cded | ||
|
|
b8b28bc0c9 | ||
|
|
e338f537f5 | ||
|
|
ccbb03f5f3 | ||
|
|
354cc11b8e | ||
|
|
706455a6f8 | ||
|
|
2fcc542d85 | ||
|
|
f2c564cfb7 | ||
|
|
3ec968d873 | ||
|
|
c7c2bb20d9 | ||
|
|
7f1907beb3 | ||
|
|
bda03dcf29 | ||
|
|
530f1c2016 | ||
|
|
636626506a | ||
|
|
152837959a | ||
|
|
ff2571180c | ||
|
|
1117890327 | ||
|
|
fb6e416e1c | ||
|
|
b8388db18d | ||
|
|
71ab2fb80e | ||
|
|
fae2b31acc | ||
|
|
9c550a8f9a | ||
|
|
5a3b35f5ac | ||
|
|
549f9fe91d | ||
|
|
f3b0afd574 | ||
|
|
ac4959cfbf | ||
|
|
8f4ed621a7 | ||
|
|
fad1a1531b | ||
|
|
e417d80244 | ||
|
|
7e3c86e09a | ||
|
|
0848fa1b59 | ||
|
|
50e1f3c0c4 | ||
|
|
52781fbd9e | ||
|
|
d4d2074466 | ||
|
|
db64bc02c8 | ||
|
|
432a3a653a | ||
|
|
72ed175c52 | ||
|
|
7e765b667c | ||
|
|
73dc4e50eb | ||
|
|
239494e4dc | ||
|
|
ca2772df79 | ||
|
|
308a5eb5d4 | ||
|
|
0307a32e1b | ||
|
|
60c2bef474 | ||
|
|
fe60ebd89a | ||
|
|
fccffa96c6 | ||
|
|
73ad860bb9 | ||
|
|
c79ba01dba | ||
|
|
a4604e3380 | ||
|
|
ccfe32f236 | ||
|
|
d4ef626961 | ||
|
|
4e00a0760e | ||
|
|
71f9e677b8 | ||
|
|
d1c2dcca0b | ||
|
|
8df98908ca | ||
|
|
f735c04194 | ||
|
|
e66744b6e9 | ||
|
|
30ac5dfae9 | ||
|
|
0a8590643f | ||
|
|
3a42dac02b | ||
|
|
863d0c1e4b | ||
|
|
b40751ba9d | ||
|
|
c2409e813e | ||
|
|
83371cf135 | ||
|
|
247640cc27 | ||
|
|
63578aefd0 | ||
|
|
8debbf8ba4 | ||
|
|
6f2c79f985 | ||
|
|
7117cfc273 | ||
|
|
5fec55f5a0 | ||
|
|
92ce2a5a5d | ||
|
|
54d68d9394 | ||
|
|
003acd5f64 | ||
|
|
9097cfcce7 | ||
|
|
484551e5bf | ||
|
|
9beecbda92 | ||
|
|
96b1c22e28 | ||
|
|
b8921ca593 | ||
|
|
17dc05c9b7 | ||
|
|
0ff1d79b5b | ||
|
|
11d15f96d1 | ||
|
|
ecb6ebcc18 | ||
|
|
0fb48fb9bf | ||
|
|
4e8d50367d | ||
|
|
cdef4e7393 | ||
|
|
a101815a47 | ||
|
|
b8ba6c0d2b | ||
|
|
5c62149fc4 | ||
|
|
dc00d38b01 | ||
|
|
8f3b30a04f | ||
|
|
b07b2be5ca | ||
|
|
dfa38a0ddc | ||
|
|
2dbea4f4cd | ||
|
|
4d6037c3d3 | ||
|
|
346a3d7c9d | ||
|
|
f2f2c93aa1 | ||
|
|
4fe89d5571 | ||
|
|
7f89bd7d62 | ||
|
|
3b1c21a72d | ||
|
|
5332eab258 | ||
|
|
c9581205d3 | ||
|
|
fa1dc438fa | ||
|
|
bc34ebdff9 | ||
|
|
e41a934f74 | ||
|
|
7e16dded0b | ||
|
|
6b31076a43 | ||
|
|
3f62bb6fb4 | ||
|
|
64ffe22545 | ||
|
|
0b1fce8a6d | ||
|
|
bb0266f5c4 | ||
|
|
eddf47e4a3 | ||
|
|
3f0d20ed8c | ||
|
|
80c762074f | ||
|
|
9d0d09de80 | ||
|
|
73df63db1f | ||
|
|
fca0cf3027 | ||
|
|
76704feee4 | ||
|
|
c5bf6e77a7 | ||
|
|
9c6048a759 | ||
|
|
ba9428558a | ||
|
|
ddc0e76ffc | ||
|
|
326d23a509 | ||
|
|
81899e04fd | ||
|
|
b60e6dc311 | ||
|
|
531028ef4f | ||
|
|
1dfbffb422 | ||
|
|
b6896c7c0a | ||
|
|
e7d3f3e961 | ||
|
|
4b1a3b8792 | ||
|
|
8d59c424d7 | ||
|
|
0f2e3d7c99 | ||
|
|
48cb177ef0 | ||
|
|
ac550bac24 | ||
|
|
5570ab02ee | ||
|
|
1ab413e9bc | ||
|
|
a802e10725 | ||
|
|
546a17f5d3 | ||
|
|
7394a22c2d | ||
|
|
379a26600c | ||
|
|
683d93a894 | ||
|
|
02144b472a | ||
|
|
763d987309 | ||
|
|
c857e1a99f | ||
|
|
b631ec44bb | ||
|
|
2bf6d609cb | ||
|
|
5a60d64f04 | ||
|
|
9447494bd5 | ||
|
|
44a5600038 | ||
|
|
99b97afc7d | ||
|
|
a3e4dac5fb | ||
|
|
affe196ff6 | ||
|
|
98bb40bd80 | ||
|
|
10dfb0d477 | ||
|
|
6b1b8c5102 | ||
|
|
f0ae51792f | ||
|
|
9813011db2 | ||
|
|
0850c16b00 | ||
|
|
90e13c07f7 | ||
|
|
119f579a44 | ||
|
|
aadff0d54e | ||
|
|
e87ab4a895 | ||
|
|
04b1103778 | ||
|
|
65a8271925 | ||
|
|
67c98f6a76 | ||
|
|
f946e6a28d | ||
|
|
71b46cc768 | ||
|
|
d18021950d | ||
|
|
71517b255d | ||
|
|
6ec37fdacc | ||
|
|
931e88b9f0 | ||
|
|
948b842351 | ||
|
|
145968af0f | ||
|
|
6f4a0480f3 | ||
|
|
522b4df989 | ||
|
|
eb1599fa07 | ||
|
|
0fb997285b | ||
|
|
d6c8d6d3a6 | ||
|
|
088a7e4e70 | ||
|
|
2cebf5cc03 | ||
|
|
61ea86033a | ||
|
|
896cd8c41e | ||
|
|
4b9973826e | ||
|
|
bc18e3174a | ||
|
|
c756a9029a | ||
|
|
43efe40cd8 | ||
|
|
3f7cae09bb | ||
|
|
52ebc2b404 | ||
|
|
f44fc4b85b | ||
|
|
d1f97f2658 | ||
|
|
3d44c51613 | ||
|
|
d10ce8772d | ||
|
|
652bb46f60 | ||
|
|
994123e92e | ||
|
|
8010c51521 | ||
|
|
55454a300e | ||
|
|
daad786072 | ||
|
|
b620ebbc29 | ||
|
|
d410731faa | ||
|
|
a5128f06ad | ||
|
|
bf9223225c | ||
|
|
d4316d9878 | ||
|
|
045075c396 | ||
|
|
3102391234 | ||
|
|
e9ad278286 | ||
|
|
b836d618c9 | ||
|
|
a23187b4af | ||
|
|
66de18f9b6 | ||
|
|
8d6def7e41 | ||
|
|
c196f7548c | ||
|
|
15fed2e819 | ||
|
|
374516a00a | ||
|
|
c4f1d251c3 | ||
|
|
619a588683 | ||
|
|
7beca7a1a3 | ||
|
|
35785be5dc | ||
|
|
69f527b7c7 | ||
|
|
60f4a82873 | ||
|
|
ddd735feba | ||
|
|
a88468eb79 | ||
|
|
d506c9241f | ||
|
|
94b1896e28 | ||
|
|
01ad427d75 | ||
|
|
cf99b78489 | ||
|
|
20871e2171 | ||
|
|
f1de614027 | ||
|
|
eee1eda6bc | ||
|
|
3008a13efb | ||
|
|
ea6df41f05 | ||
|
|
27a0295218 | ||
|
|
6e6388d673 | ||
|
|
84a8538597 | ||
|
|
54dc887254 | ||
|
|
ca595163bb | ||
|
|
5585884d26 | ||
|
|
c4d15e40a8 | ||
|
|
36b5b9f4dd | ||
|
|
19422819da | ||
|
|
f7d5f11cf8 | ||
|
|
5c5e91cb3d | ||
|
|
c226e9c1e4 | ||
|
|
09b6a33ae4 | ||
|
|
ee0c641b08 | ||
|
|
cc5dea716b | ||
|
|
dbbb07c68e | ||
|
|
ad1666bb2c | ||
|
|
e620d2dcd7 | ||
|
|
06a3f932ba | ||
|
|
2298f6b5a7 | ||
|
|
78d7a4f560 | ||
|
|
5d079d8c26 | ||
|
|
7fc571643d | ||
|
|
088d9ee59a | ||
|
|
90e2ab6fcf | ||
|
|
aa16dd671b | ||
|
|
6dbcdf537f | ||
|
|
94989b39dc | ||
|
|
b3b60757aa | ||
|
|
eed759e111 | ||
|
|
bfeb096f31 | ||
|
|
8b2d9b26f5 | ||
|
|
7de61eb113 | ||
|
|
b18e9cc222 | ||
|
|
6e8b720d17 | ||
|
|
7deb9fac4c | ||
|
|
42357891a3 | ||
|
|
3b53d9532d | ||
|
|
6d8cb762ff | ||
|
|
9ad8fed81e | ||
|
|
cf83c9f709 | ||
|
|
fb15b2a3de | ||
|
|
be23f206ee | ||
|
|
dddd968f82 | ||
|
|
7337c6f762 | ||
|
|
07388f4d38 | ||
|
|
e3cf9b2aa9 | ||
|
|
6c6b7dcff0 | ||
|
|
975011d190 | ||
|
|
d9c16380a4 | ||
|
|
588454ffee | ||
|
|
27dddd62ac | ||
|
|
2e27b073c9 | ||
|
|
b63ca44094 | ||
|
|
40011370a3 | ||
|
|
e03dbe3251 | ||
|
|
4f32f477bd | ||
|
|
a71c5c159d | ||
|
|
17ffb4455e | ||
|
|
2641fc54d6 | ||
|
|
b8ce199edd | ||
|
|
fd11c08b99 | ||
|
|
b676773602 | ||
|
|
9785387867 | ||
|
|
4fe99e6ebb | ||
|
|
d721ec5d9c | ||
|
|
6f6f535d6a | ||
|
|
b4dfa5a4dd | ||
|
|
d25ddc954a | ||
|
|
0afbefc962 | ||
|
|
a28c7c3f93 | ||
|
|
bfc7ea3635 | ||
|
|
0e7c759bde | ||
|
|
2a7594fc3b | ||
|
|
7219cc45a5 | ||
|
|
0eae069666 | ||
|
|
89dbefe46d | ||
|
|
ddd4a02e9c | ||
|
|
282cf1ce03 | ||
|
|
327441fd6b | ||
|
|
9b0aec378e | ||
|
|
16c407e33c | ||
|
|
6f20150e6e | ||
|
|
a39dbeadac | ||
|
|
8d0c8e4033 | ||
|
|
65644bab8b | ||
|
|
82dd2f3c1f | ||
|
|
ffbb628ce2 | ||
|
|
d4c4b64cd5 | ||
|
|
c4aaf43662 | ||
|
|
e073df40b0 | ||
|
|
e90691f168 | ||
|
|
0c23630e87 | ||
|
|
3026a0c7e7 | ||
|
|
51f4d4b888 | ||
|
|
f99e5b0bea | ||
|
|
3ccf02c156 | ||
|
|
c50e61a25b | ||
|
|
4329241949 | ||
|
|
52ee49eed3 | ||
|
|
0c6b4e0dad | ||
|
|
a222ff0042 | ||
|
|
a232260713 | ||
|
|
ee62d07c68 | ||
|
|
d98f11b98e | ||
|
|
ae1d3b0393 | ||
|
|
3d9052d711 | ||
|
|
fe120952ee | ||
|
|
47f0f0c21e | ||
|
|
797c62389d | ||
|
|
8adda52df1 | ||
|
|
e433252934 | ||
|
|
d3bab5de94 | ||
|
|
7e85ac97c9 | ||
|
|
8ad19e6054 | ||
|
|
6467cc6b89 | ||
|
|
c3697d0656 | ||
|
|
7c8d68c0a1 | ||
|
|
f487de77bc | ||
|
|
a22033ac49 | ||
|
|
937c766ded | ||
|
|
1857eecb36 | ||
|
|
22d1fda655 | ||
|
|
a0a50442f7 | ||
|
|
aebcd00f61 | ||
|
|
5a0dde2017 | ||
|
|
871c551134 | ||
|
|
fe52bc5b6d | ||
|
|
821f3c5161 | ||
|
|
1fadae885e | ||
|
|
fdc3e0eb0b | ||
|
|
3e1919b46e | ||
|
|
ac876b9271 | ||
|
|
9b1eed534b | ||
|
|
f46cc32be3 | ||
|
|
4f785cfca0 | ||
|
|
db27fef6f2 | ||
|
|
0437d1623e | ||
|
|
4443bfbd41 | ||
|
|
01141fa10e | ||
|
|
51e3568aac | ||
|
|
011179ca6d | ||
|
|
270c78d8af | ||
|
|
3f1e9e397e | ||
|
|
1c16233da0 | ||
|
|
9651923f8e | ||
|
|
3e875b583c | ||
|
|
1a4480e74c | ||
|
|
bdd1d93708 | ||
|
|
69710e10e0 | ||
|
|
41d945803f | ||
|
|
c903dd6af4 | ||
|
|
26975e055b | ||
|
|
504a3a76f5 | ||
|
|
d51820f48c | ||
|
|
5691a4f162 | ||
|
|
c3c3170451 | ||
|
|
e6b32cabbe | ||
|
|
8eddec88cb | ||
|
|
a7e154fbe4 | ||
|
|
b36f5a4eee | ||
|
|
499d9adbe0 | ||
|
|
5d8422ec52 | ||
|
|
93f473f629 | ||
|
|
2ef4dc4d8e | ||
|
|
5f43536612 | ||
|
|
a1e786fd73 | ||
|
|
07544718fa | ||
|
|
a237ba3735 | ||
|
|
56499f9269 | ||
|
|
f6770e2865 | ||
|
|
0592181f54 | ||
|
|
1d3e5564a2 | ||
|
|
1cfeb853a5 | ||
|
|
4edfbce3ce | ||
|
|
ee8f77c8c6 | ||
|
|
357276b1d9 | ||
|
|
b2d84bc733 | ||
|
|
5d54a10177 | ||
|
|
09c29eab23 | ||
|
|
7172531386 | ||
|
|
e6b3b8ba48 | ||
|
|
4b9c836743 | ||
|
|
2078287872 | ||
|
|
2b98792657 | ||
|
|
1f0fd699ea | ||
|
|
a55818bb1a | ||
|
|
95d5f045db | ||
|
|
adc32379da | ||
|
|
02d66a346d | ||
|
|
0f4276d9b0 | ||
|
|
3b62ed4e4f | ||
|
|
a797dd0b50 | ||
|
|
a7b9e5783d | ||
|
|
35396a5b2a | ||
|
|
86af3a42ff | ||
|
|
09f9043e9a | ||
|
|
aa0f89c2a4 | ||
|
|
1a5cf56532 | ||
|
|
d6231634db | ||
|
|
c41c5881c8 | ||
|
|
adca664460 | ||
|
|
cd4fdfb7b6 | ||
|
|
c609060352 | ||
|
|
348b7f521f | ||
|
|
b21f177e95 | ||
|
|
6c7dfe5921 | ||
|
|
cf56a1cdcd | ||
|
|
ac10b4a3b9 | ||
|
|
53d9522c06 | ||
|
|
eff090170c | ||
|
|
204e7ca4ff | ||
|
|
d393c89ae0 | ||
|
|
31e589abde | ||
|
|
6b73da55f8 | ||
|
|
110cbd1084 | ||
|
|
80920dd872 | ||
|
|
c40a3474f4 | ||
|
|
4cc0e86dc0 | ||
|
|
6ef20d0a1f | ||
|
|
f29c896c4a | ||
|
|
40013ec270 | ||
|
|
18f5ff4eed | ||
|
|
c8767daddf | ||
|
|
523c1ce423 | ||
|
|
452aa9a931 | ||
|
|
ead4cc21ce | ||
|
|
fd5ea0c6a4 | ||
|
|
6a5a5b50d3 | ||
|
|
4281c4d978 | ||
|
|
2d70511474 | ||
|
|
07e4b2cd7a | ||
|
|
bc7e7d4548 | ||
|
|
734351d9a0 | ||
|
|
1b9f29db13 | ||
|
|
201e84cd94 | ||
|
|
ad66831324 | ||
|
|
834fa2e4e0 | ||
|
|
244004136c | ||
|
|
6d73c60a38 | ||
|
|
160f6d64be | ||
|
|
80fb97c9bc | ||
|
|
ed569a2fdb | ||
|
|
a06f748587 | ||
|
|
68a6eb3f2a | ||
|
|
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 |
No files matched your search
@@ -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,68 @@
|
||||
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).
|
||||
All bug reports MUST include `moonraker.log` as an attachment.
|
||||
- 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
|
||||
- OctoApp
|
||||
- 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,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: weibullguy/python-lint-plus@v1.12.0
|
||||
with:
|
||||
python-root-list: "moonraker scripts"
|
||||
virtual-env: "python-lint-plus"
|
||||
python-version: "3.10"
|
||||
use-flake8: true
|
||||
flake8-version: "==6.1.0"
|
||||
use-mypy: true
|
||||
mypy-version: "==1.5.1"
|
||||
extra-flake8-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"
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.devel
|
||||
|
||||
.venv
|
||||
venv
|
||||
start_moonraker
|
||||
*.env
|
||||
*.egg-info
|
||||
.pdm-python
|
||||
build
|
||||
dist
|
||||
share
|
||||
|
||||
.vscode
|
||||
.mypy_cache
|
||||
.pdm-build
|
||||
.pytest_cache
|
||||
|
||||
# Sometimes uv lock generates the version file and places it in
|
||||
# the repo. We don't want to commit this, so ignore it
|
||||
moonraker/__version__.py
|
||||
@@ -0,0 +1,13 @@
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: sync-requirements
|
||||
name: sync python requirements
|
||||
language: system
|
||||
entry: python3 scripts/sync_dependencies.py
|
||||
files: ^pyproject.toml$
|
||||
- id: sync-os-packages
|
||||
name: sync packages
|
||||
language: system
|
||||
entry: python3 scripts/sync_dependencies.py
|
||||
files: ^scripts/system-dependencies.json$
|
||||
@@ -0,0 +1,14 @@
|
||||
version: 2
|
||||
|
||||
build:
|
||||
os: ubuntu-24.04
|
||||
tools:
|
||||
python: "3.12"
|
||||
|
||||
mkdocs:
|
||||
configuration: mkdocs.yml
|
||||
fail_on_warning: false
|
||||
|
||||
python:
|
||||
install:
|
||||
- requirements: docs/doc-requirements.txt
|
||||
@@ -1,24 +1,43 @@
|
||||
|
||||
# Moonraker - API Web Server for Klipper
|
||||
|
||||
Moonraker is a Python 3 based web server that exposes APIs with which
|
||||
client applications may use to interact with Klipper. Communcation between
|
||||
client applications may use to interact with the 3D printing firmware
|
||||
[Klipper](https://github.com/KevinOConnor/klipper). Communication between
|
||||
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
|
||||
is used to provide Moonraker's server functionality.
|
||||
|
||||
Documentation for users and developers can be found on
|
||||
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
|
||||
|
||||
### 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/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
|
||||
- [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
|
||||
|
||||
This section contains changelogs that users and developers may reference
|
||||
to see if any action is necessary on their part. The date of the most
|
||||
recent change is included.
|
||||
|
||||
Users:\
|
||||
[user_changes.md](/docs/user_changes.md) - December 31st 2020
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - January 1st 2021
|
||||
Please refer to the [changelog](https://moonraker.readthedocs.io/en/latest/changelog)
|
||||
for a list of notable changes to Moonraker.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Moonraker provides security updates through new releases. All versions are supported, however users
|
||||
will need to update to the latest release to get the latest fixes.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Users can report security vulnerabilites through GitHub's private vulnerablility reporting.
|
||||
Once a report is received users should expect a typical response time of one to two days, one week at most.
|
||||
If the report is accepted as a legitimate vulnerability a security advisory will be drafted and
|
||||
a work will begin on a fix. The finder will get credit for the report and may be asked to
|
||||
collaborate on a private fork, depending on the depth of the vulnerability and complexity of
|
||||
the fix. Once the fix is complete and tested it will be pushed to the master branch of the
|
||||
repo, a new release will be created, and the security advisory will be published. Ideally this will
|
||||
occur within 1-2 weeks of the report.
|
||||
|
||||
If the report is declined no further action will be taken.
|
||||
+145
-8
@@ -1,4 +1,140 @@
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
##
|
||||
This document keeps a record of notable changes to Moonraker's Web API.
|
||||
|
||||
### July 18th 2023
|
||||
- Moonraker API Version 1.3.0
|
||||
- Added [Spoolman](./external_api/integrations.md#spoolman) APIs.
|
||||
- Added [Rollback](./external_api/update_manager.md#rollback-to-the-previous-version)
|
||||
API to the `update_manager`
|
||||
- The `update_manager` status response has new fields for items of the
|
||||
`git_repo` and `web` types:
|
||||
- `recovery_url`: Url of the repo a "hard" recovery will fetch from
|
||||
- `rollback_version`: Version the extension will revert to when a rollback
|
||||
is requested
|
||||
- `warnings`: An array of strings containing various warnings detected
|
||||
during repo init. Some warnings may explain an invalid state while
|
||||
others may alert users to potential issues, such as a `git_repo` remote
|
||||
url not matching the expected (ie: configured) url.
|
||||
- Additionally, the `need_channel_update` field has been removed as the method
|
||||
changing channels is done exclusively in the configuration.
|
||||
|
||||
### 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 [the documentation](./external_api/devices.md#sensor-endpoints)
|
||||
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 [the documentation](./external_api/jsonrpc_notifications.md#sensor-events)
|
||||
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](./external_api/server.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`). Sub-folders within these
|
||||
these roots are also monitored, however hidden folders are not.
|
||||
The following changes API changes have been made to accommodate
|
||||
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 notifications. 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 particularly 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
|
||||
|
||||
@@ -18,7 +154,8 @@ This document keeps a record of all changes to Moonraker's web APIs.
|
||||
core API:
|
||||
- `POST /machine/services/restart`
|
||||
|
||||
See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
See [the documentation](./external_api/update_manager.md) for details
|
||||
on these new endpoints.
|
||||
|
||||
### November 23rd 2020
|
||||
- Moonraker now serves Klipper's "docs" directory. This can be access
|
||||
@@ -52,7 +189,7 @@ See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
"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
|
||||
containing device info, matching that which would be received
|
||||
from a single item in `/machine/power/devices`.
|
||||
|
||||
### November 12th 2020
|
||||
@@ -72,13 +209,13 @@ See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
- 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
|
||||
connection will only receive 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
|
||||
Currently 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
|
||||
@@ -163,8 +300,8 @@ See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
- `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.
|
||||
- A new notification has been added: `notify_metadata_update`. This
|
||||
notification is sent when Moonraker parses metadata 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:
|
||||
@@ -264,7 +401,7 @@ See [web_api.md](web_api.md) for details on these new endpoints.
|
||||
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
|
||||
- Subscriptions are now pushed as "diffs". Clients will only receive updates
|
||||
for subscribed items when that data changes. This requires that clients
|
||||
initialize their local state with the data returned from the subscription
|
||||
request.
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog].
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Changed
|
||||
- **machine**: Support standard reboot and shutdown commands
|
||||
|
||||
### Added
|
||||
- **metadata**: Auto-detect forks of PrusaSlicer.
|
||||
- **metadata**: Add `printer_vendor`, `printer_model`, `printer_variant`,
|
||||
and `profile_version` parsing for PrusaSlicer derivatives.
|
||||
|
||||
## [0.10.0] - 2026-01-21
|
||||
|
||||
### Changed
|
||||
- **data_store**: Store multi-line gcode commands in a single entry.
|
||||
- **dbus_manager**: Replace unmaintained `dbus-next` requirement with
|
||||
`dbus-fast`.
|
||||
- **pip_utils**: Use the "upgrade" option when installing python packages.
|
||||
This will force upgrades to the latest version available as resolved by
|
||||
the requirement specifier.
|
||||
- **python_deploy**: Use the "eager" dependency update strategy.
|
||||
- **wled**: Use the `async_serial` utility for serial comms.
|
||||
- **paneldue**: Use the `async_serial` utility for serial comms.
|
||||
- **scripts**: Update `fetch-apikey.sh` to query the SQL database
|
||||
- **update_manager**: The following endpoints have been deprecated
|
||||
as of API version 1.5.0:
|
||||
- `/machine/update/full`
|
||||
- `/machine/update/client`
|
||||
- `/machine/update/moonraker`
|
||||
- `/machine/update/klipper`
|
||||
- `/machine/update/system`
|
||||
|
||||
The new `/machine/update/upgrade` endpoint replaces the functionality
|
||||
of all of the above. The deprecated endpoints will NOT be removed,
|
||||
so existing software does not need to be changed. New software
|
||||
should use the new endpoint, however it may be desirable to also
|
||||
support the deprecated `full` and `client` endpoints for compatibility
|
||||
with older API versions.
|
||||
- **simplyprint**: Improve job progress calculation.
|
||||
- **build**: Bump PDM-Backend to 2.4.4.
|
||||
- **build**: Bump Apprise to 1.9.6
|
||||
- **build**: Bump Tornado to 6.5.4
|
||||
- **build**: Bump Streaming-form-data to 1.19.1
|
||||
- **build**: Bump Jinja2 to 3.1.6
|
||||
- **build**: Bump dbus-fast to 3.1.2
|
||||
- **build**: Bump pillow to 12.1.0
|
||||
- **build**: Bump inotify-simple to 2.0.1
|
||||
- **build**: Bump paho-mqtt to 2.1.0
|
||||
- **build**: Bump zeroconf to 0.148.0
|
||||
- **build**: bump importlib_metadata to 8.7.1
|
||||
- **metadata**: Export `filament_name` and `filament_type` values as arrays
|
||||
when more than one value is present.
|
||||
|
||||
### Fixed
|
||||
- **python_deploy**: Fix "dev" channel updates for GitHub sources.
|
||||
- **python_deploy**: Fix release rollbacks.
|
||||
- **python_deploy**: Fix support for PyPI beta updates.
|
||||
- **mqtt**: Publish the result of the Klipper status subscription request.
|
||||
This fixes issues with MQTT clients missing the initial status updates
|
||||
after Klippy restarts.
|
||||
- **eventloop**: Fixed a condition where the garbage collector may
|
||||
prematurely cancel background tasks.
|
||||
- **spoolman**: Use the default websocket ping timeout. Disable pinging for
|
||||
versions of Tornado prior to 6.5.0.
|
||||
- **application**: Disable pinging for versions of Tornado prior to 6.5.0.
|
||||
- **system_deploy**: Handle the "package_severity" bits for Info Enum objects.
|
||||
- **spoolman**: Fix filament tracking for MMU devices.
|
||||
- **ldap**: Fix filter injection vulnerability.
|
||||
|
||||
### Added
|
||||
- **application**: Verify that a filename is present when parsing the
|
||||
multipart/form-data for uploads.
|
||||
- **application**: Log all failed HTTP API requests when verbose logging
|
||||
is enabled.
|
||||
- **install**: Support "requirement specifiers" for system packages.
|
||||
Initially this is limited to restricting packages to a specific
|
||||
distro version.
|
||||
- **async_serial**: Basic asyncio wrapper around pyserial.
|
||||
- **wled**: Add initial support for receiving responses.
|
||||
- **scripts**: Add a `-g` option to `fetch-apikey.sh`. When specified
|
||||
a new API Key will be generated and stored in the database. After
|
||||
running this script it is necessary to restart Moonraker.
|
||||
- **update_manager**: Report `name` and `configured_type` for all status
|
||||
response types. This adds consistency and allows front-end devs to
|
||||
simply iterate over the values of the `version_info` object.
|
||||
- **python_deploy**: Add support for updating python packages with
|
||||
"extras" installed.
|
||||
- **update_manager**: Add support for updating `executable` binaries.
|
||||
- **update_manager**: Added a `report_anomalies` option for git, web, and zip
|
||||
types.
|
||||
- **git_deploy**: Add support for relative `gitdir` file paths.
|
||||
- **analysis**: Initial support for gcode file time analysis using
|
||||
[Klipper Estimator](https://github.com/Annex-Engineering/klipper_estimator).
|
||||
- **power**: Added the ability to discard unwanted responses for MQTT
|
||||
power devices.
|
||||
- **power**: Added `poll_interval` option for HTTP (and all derivatives),
|
||||
TPLink Smartplug, and uhubctl devices. When set Moonraker will poll device
|
||||
status.
|
||||
- **power**: Added `restrict_action_processing` option. When set to `False`,
|
||||
post toggle actions such as restarting Klippy and controlling bound services
|
||||
are run when an external power event is detected.
|
||||
- **simplyprint**: Forward `exclude_object` status data from Klipper.
|
||||
- **td1**: Add support for interfacing with [TD-1](https://ajax-3d.com/) devices.
|
||||
- **metadata**: Add generic support for most PrusaSlicer forks.
|
||||
- **proc_stats**: Add support for x86-64 (Intel and AMD) temperature sensors.
|
||||
- **ldap**: Add support for servers such as OpenDJ that use the `isMemberOf`
|
||||
virtual attribute to report group membership.
|
||||
- **ldap**: Add `check_dn_case` option to disable case-sensitive group DN
|
||||
comparisons if desired.
|
||||
|
||||
## [0.9.3] - 2024-09-05
|
||||
|
||||
### Changed
|
||||
- **server**: Use `asyncio.run` to launch the server as recommended by the
|
||||
official Python documentation.
|
||||
- **announcements**: Look for xml files at `<data_path>/development/announcements`
|
||||
when `dev_mode` is set to True.
|
||||
- **build**: Move scripts from the "data" directory into a folder inside the
|
||||
moonraker package.
|
||||
|
||||
### Fixed
|
||||
- **confighelper**: Don't resolve symbolic links to the main configuration file.
|
||||
- **power**: Allow special characters in the user/pass options for backends that
|
||||
support Basic Authentication.
|
||||
|
||||
## [0.9.2] - 2024-07-30
|
||||
|
||||
### Added
|
||||
- **install**: Add support for installing Moonraker's python package via pip.
|
||||
- **scripts**: Add script to sync python and system dependencies from
|
||||
`pyproject.toml` and `system-dependencies.json` respectively.
|
||||
- **dev**: Add pre-commit hook to call `sync_dependencies.py`.
|
||||
|
||||
### Fixed
|
||||
- **build**: Build from sdist now correctly includes share data.
|
||||
- **build**: Remove stray `.gitignore` from Python Wheel.
|
||||
|
||||
### Changed
|
||||
- **install**: The `MOONRAKER_FORCE_DEFAULTS` environment variable has changed
|
||||
to `MOONRAKER_FORCE_SYSTEM_INSTALL`.
|
||||
|
||||
## [0.9.1] - 2024-07-25
|
||||
|
||||
### Fixed
|
||||
- **source_info**: Fixed `importlib.metadata` compatibility issues with python
|
||||
versions 3.9 or older.
|
||||
|
||||
## [0.9.0] - 2024-07-25
|
||||
|
||||
### Added
|
||||
- **notifier**: The `attach` option now supports Jinja2 templates.
|
||||
- **notifier**: The `attach` option may now contain multiple attachments,
|
||||
each separated by a newline.
|
||||
- **notifier**: Added support for a configurable `body_format`
|
||||
- **power**: Added support for generic `http` type switches.
|
||||
- **metadata**: Added support for OrcaSlicer
|
||||
- **zeroconf**: Added support for a configurable mDNS hostname.
|
||||
- **zeroconf**: Added support for UPnP/SSDP Discovery.
|
||||
- **spoolman**: Added integration to the
|
||||
[Spoolman](https://github.com/Donkie/Spoolman) filament manager.
|
||||
- **update_manager**: Added support for update rollbacks
|
||||
- **update_manager**: Added support for stable `git_repo` updates
|
||||
- **server**: Added a `--unixsocket` command line option
|
||||
- **server**: Command line options may also be specified as env variables
|
||||
- **server**: Added a `route_prefix` option
|
||||
- **webcam**: Webcam APIs can now specify cameras by `uid` or `name`
|
||||
- **deps**: Added support for optional `msgspec` and `uvloop` packages
|
||||
- **extensions**: Agents may now register remote methods with Klipper
|
||||
- **file_manager**: Add `check_klipper_config_path` option
|
||||
- **button**: Added `debounce_period` option
|
||||
- **history**: Added a check for previous jobs not finished (ie: when power is
|
||||
lost during a print). These jobs will report their status as `interrupted`.
|
||||
- **build**: Added support for optional speedup dependencies `uvloop` and `msgspec`
|
||||
- **update_manager**: Added support for "zipped" application updates
|
||||
- **file_manager**: Added `enable_config_write_access` option
|
||||
- **machine**: Add support for system peripheral queries
|
||||
- **mqtt**: Added the `status_interval` option to support rate limiting
|
||||
- **mqtt**: Added the `enable_tls` option to support ssl/tls connections
|
||||
- **mqtt**: Added support for a configurable `client_id`
|
||||
- **history**: Added `user` field to job history data
|
||||
- **history**: Added support for auxiliary history fields
|
||||
- **spoolman**: Report spool ids set during a print in history auxiliary data
|
||||
- **sensor**: Added support for history fields reported in auxiliary data
|
||||
- **power**: Added support for `uhubctl` devices
|
||||
- **update_manager**: Add support for pinned git commits
|
||||
- **update_manager**: Added support for updating pip managed python apps
|
||||
|
||||
### Fixed
|
||||
|
||||
- **simplyprint**: Fixed import error preventing the component from loading.
|
||||
- **update_manager**: Moonraker will now restart the correct "moonraker" and
|
||||
"klipper" services if they are not the default values.
|
||||
- **job_queue**: Fixed transition when auto is disabled
|
||||
- **history**: Added modification time to file existence checks.
|
||||
- **dbus_manager**: Fixed PolKit warning when PolKit features are not used.
|
||||
- **job_queue**: Fixed a bug where the `job_transition_gcode` runs when the
|
||||
queue is started. It will now only run between jobs during automatic
|
||||
transition.
|
||||
- **klippy_connection**: Fixed a race condition that can result in
|
||||
skipped subscription updates.
|
||||
- **configheler**: Fixed inline comment parsing.
|
||||
- **authorization**: Fixed blocking call to `socket.getfqdn()`
|
||||
- **power**: Fixed "on_when_job_queued" behavior when the internal device
|
||||
state is stale.
|
||||
|
||||
### Changed
|
||||
|
||||
- **build**: Bumped apprise to version `1.8.0`.
|
||||
- **build**: Bumped lmdb to version `1.4.1`
|
||||
- **build**: Bumped tornado to version `6.4.0`
|
||||
- **build**: Bumped jinja2 to version `3.1.4`
|
||||
- **build**: Bumped zeroconf to version `0.131.0`
|
||||
- **build**: Bumped libnacl to version `2.1.0`
|
||||
- **build**: Bumped distro to version `1.9.0`
|
||||
- **build**: Bumped pillow to version `10.3.0`
|
||||
- **build**: Bumped streaming-form-data to version `1.15.0`
|
||||
- **machine**: Added `ratos-configurator` to list of default allowed services
|
||||
- **update_manager**: It is now required that an application be "allowed"
|
||||
for Moonraker to restart it after an update.
|
||||
- **update_manager**: Git repo validation no longer requires a match for the
|
||||
remote URL and/or branch.
|
||||
- **update_manager**: Fixed potential security vulnerabilities in `web` type updates.
|
||||
This change adds a validation step to the install, front-end developers may refer to
|
||||
the [configuration documentation](./configuration.md#web-type-front-end-configuration)
|
||||
for details.
|
||||
- **update_manager**: The `env` option for the `git_repo` type has been deprecated, new
|
||||
configurations should use the `virtualenv` option.
|
||||
- **update_manager**: The `install_script` option for the `git_repo` has been
|
||||
deprecated, new configurations should use the `system_dependencies` option.
|
||||
- **update_manager**: APIs that return status report additional fields.
|
||||
See the [API Documentation](./external_api/update_manager.md#get-update-status)
|
||||
for details.
|
||||
- **proc_stats**: Improved performance of Raspberry Pi CPU throttle detection.
|
||||
- **power**: Bound services are now processed during initialization when
|
||||
`initial_state` is configured.
|
||||
- **gpio**: Migrate from libgpiod to python-periphery
|
||||
- **authorization**: The authorization module is now loaded as part of Moonraker's
|
||||
core.
|
||||
- **database**: Migrated the underlying database from LMDB to Sqlite.
|
||||
- **history**: Use dedicated SQL tables to store job history and job totals.
|
||||
- **authorization**: Use a dedicated SQL table to store user data.
|
||||
|
||||
### REMOVED
|
||||
|
||||
- **simplyprint**: Removed defunct "AI" functionality
|
||||
|
||||
## [0.8.0] - 2023-02-23
|
||||
|
||||
!!! Note
|
||||
This is the first tagged release since a changelog was introduced. The list
|
||||
below contains notable changes introduced beginning in February 2023. Prior
|
||||
notable changes were kept in [user_changes.md] and [api_changes.md].
|
||||
|
||||
### 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](./external_api/devices.md#sensor-endpoints)
|
||||
- [Websocket Notification Docs](./external_api/jsonrpc_notifications.md#sensor-events)
|
||||
- **file_manager**: Added new [scan metadata](./external_api/file_manager.md#scan-gcode-metadata) endpoint.
|
||||
- **file_manager**: Added new [thumbnails](./external_api/file_manager.md#get-gcode-thumbnail-details) 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](./external_api/introduction.md#bridge-websocket)
|
||||
connections.
|
||||
- **update_manager**: Added new [refresh](./external_api/update_manager.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.10.0...HEAD
|
||||
[0.10.0]: https://github.com/Arksine/moonraker/compare/v0.9.3...v0.10.0
|
||||
[0.9.3]: https://github.com/Arksine/moonraker/compare/v0.9.2...v0.9.3
|
||||
[0.9.2]: https://github.com/Arksine/moonraker/compare/v0.9.1...v0.9.2
|
||||
[0.9.1]: https://github.com/Arksine/moonraker/compare/v0.9.0...v0.9.1
|
||||
[0.9.0]: https://github.com/Arksine/moonraker/compare/v0.8.0...v0.9.0
|
||||
[0.8.0]: https://github.com/Arksine/moonraker/compare/v0.7.1...v0.8.0
|
||||
[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_request_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 retrieve 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 notification 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="k_connected"`
|
||||
were specified when registering the `server:klippy_connected` event, the
|
||||
websocket would emit a `notify_k_connected` 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-transportshttp-websocket-mqtt-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 synonymous 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 specified
|
||||
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 specified.
|
||||
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)*
|
||||
|
||||
Subscribes 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.
|
||||
|
||||
#### *MQTTClient.unsubscribe(hdl)*
|
||||
|
||||
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
|
||||
exist for the topic then the topic is unsubscribed from the broker.
|
||||
+3603
-119
File diff suppressed because it is too large.
Load diff
+140
-26
@@ -1,31 +1,145 @@
|
||||
# Contributing to Moonraker
|
||||
|
||||
While Moonraker exists as a service independently from Klipper, it relies
|
||||
on Klipper to be useful. Thus, the tentative plan is to eventually merge
|
||||
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:
|
||||
Prior to submitting a pull request prospective contributors must read this
|
||||
entire document. Care should be taken to [format git commits](#git-commit-format)
|
||||
correctly. This eases the review process and provides the reviewer with
|
||||
confidence that the submission will be of sufficient quality.
|
||||
|
||||
- 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
|
||||
Prospective contributors should consider the following:
|
||||
|
||||
More detailed explanation if necessary.
|
||||
- Does the contribution have significant impact? Bug fixes to existing
|
||||
functionality and new features requested by 100+ users qualify as
|
||||
items of significant impact.
|
||||
- Has the submission been well tested? Submissions with substantial code
|
||||
change must include details about the testing procedure and results.
|
||||
- Does the submission include blocking code? Moonraker is an asynchronous
|
||||
application, thus blocking code must be avoided.
|
||||
- If any dependencies are included, are they pure python? Many low-powered SBCs
|
||||
running Armbian do not have prebuilt wheels and are not capable of building wheels
|
||||
themselves, thus breaking updates on these systems.
|
||||
- Does the submission change the API? If so, could the change potentially break
|
||||
frontends using the API?
|
||||
- Does the submission include updates to the documentation?
|
||||
|
||||
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.
|
||||
When performing reviews these are the questions that will be asked during the
|
||||
initial stages.
|
||||
|
||||
#### New Module Contributions
|
||||
|
||||
All source files should begin with a copyright notice in the following format:
|
||||
|
||||
```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](https://developercertificate.org/)
|
||||
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 `mypy` version 1.5.1 for static
|
||||
type checking with the following options:
|
||||
|
||||
- `--ignore-missing-imports`
|
||||
- `--follow-imports=silent`
|
||||
|
||||
No line in the source code should exceed 88 characters. Be sure there is no
|
||||
trailing whitespace. To validate code before submission one may use
|
||||
`flake8` version 6.1.0 with the following options:
|
||||
|
||||
- `--ignore=E226,E301,E302,E303,W503,W504`
|
||||
- `--max-line-length=88`
|
||||
- `--max-doc-length=88`
|
||||
|
||||
Generally speaking, each line in submitted documentation should also be no
|
||||
longer than 88 characters, however there are situations where this isn't
|
||||
possible, such as long hyperlinks or example return values.
|
||||
|
||||
Avoid peeking into the member variables of another class. Use getters or
|
||||
properties to access object state.
|
||||
+13
-13
@@ -70,7 +70,7 @@
|
||||
- Added thumbnail extraction from SuperSlicer and PrusaSlicer gcode files
|
||||
- For status requests, `virtual_sdcard.current_file` has been renamed to
|
||||
`virtual_sdcard.filename`
|
||||
- Clients should not send `M112` via gcode to execute an emegency shutdown.
|
||||
- Clients should not send `M112` via gcode to execute an emergency shutdown.
|
||||
They should instead use the new API which exposes this functionality.
|
||||
- New APIs:
|
||||
- `POST /printer/emergency_stop` - `post_printer_emergency_stop`
|
||||
@@ -108,7 +108,7 @@
|
||||
remote_api.py module that handles server configuration.
|
||||
- webhooks.py has been changed to handle communications with the server
|
||||
- klippy.py has been changed to pass itself to webhooks
|
||||
- file_manager.py has been changed to specifiy the correct status code
|
||||
- file_manager.py has been changed to specify the correct status code
|
||||
when an error is generated attempting to upload or delete a file
|
||||
- The nginx configuration will need the following additional section:
|
||||
```
|
||||
@@ -149,8 +149,8 @@
|
||||
This allows the client limited access to Klippy in the event of a startup
|
||||
error, assuming the config file was successfully parsed and the
|
||||
`remote_api` configuration section is valid. Note that when the server is
|
||||
initally launched not all endpoints will be available. The following
|
||||
endponts are guaranteed when the server is launched:
|
||||
initially launched not all endpoints will be available. The following
|
||||
endpoints are guaranteed when the server is launched:
|
||||
- `/websocket`
|
||||
- `/printer/info`
|
||||
- `/printer/restart`
|
||||
@@ -159,7 +159,7 @@
|
||||
- `/printer/gcode`
|
||||
- `/access/api_key`
|
||||
- `/access/oneshot_token`
|
||||
The following startup sequence is recommened for clients which make use of
|
||||
The following startup sequence is recommended for clients which make use of
|
||||
the websocket:
|
||||
- Attempt to connect to `/websocket` until successful
|
||||
- Once connected, query `/printer/info` for the ready status. If not ready
|
||||
@@ -181,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
|
||||
@@ -199,7 +199,7 @@
|
||||
- Fix bug in CORS where DELETE requests raised an exception
|
||||
- Disable the server when running Klippy in batch mode
|
||||
- The the `/printer/cancel`, `/printer/pause` and `/printer/resume` gcodes
|
||||
are now registed by the pause_resume module. This results in the following
|
||||
are now registered by the pause_resume module. This results in the following
|
||||
changes:
|
||||
- The `cancel_gcode`, `pause_gcode`, and `resume_gcode` options have
|
||||
been removed from the [web_server] section.
|
||||
@@ -275,17 +275,17 @@
|
||||
websocket data from a Blob into a String.
|
||||
- The endpoint for querying endstops has changed from `GET
|
||||
/printer/extras/endstops` to `GET /printer/endstops`
|
||||
- Serveral API changes have been made to accomodate the addition of webhooks:
|
||||
- Several API changes have been made to accommodate 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
|
||||
- `GET /printer/objects` is no longer used to accommodate multiple request
|
||||
types by modifying the "Accept" headers. Each request has been broken
|
||||
down in their their own endpoints:
|
||||
- `GET /printer/objects` returns all available printer objects that may
|
||||
be queried
|
||||
- `GET /printer/status?gcode=gcode_position,speed&toolhead` returns the
|
||||
status of the printer objects and attribtues
|
||||
status of the printer objects and attributes
|
||||
- `GET /printer/subscriptions` returns all printer objects that are current
|
||||
being subscribed to along with their poll times
|
||||
- `POST /printer/subscriptions?gcode&toolhead` requests that the printer
|
||||
@@ -297,7 +297,7 @@
|
||||
- `POST /printer/gcode/<gcode>` is now `POST /printer/gcode?script=<gcode>`
|
||||
- `POST printer/print/start/<filename>` is now
|
||||
`POST /printer/print/start?filename=<filename>`
|
||||
- The websocket API also required changes to accomodate dynamically registered
|
||||
- The websocket API also required changes to accommodate dynamically registered
|
||||
endpoints. Each method name is now generated from its comparable HTTP
|
||||
request. The new method names are listed below:
|
||||
| new method | old method |
|
||||
@@ -317,7 +317,7 @@
|
||||
| post_printer_firmware_restart | firmware_restart |
|
||||
| get_printer_endstops | get_endstops |
|
||||
- As with the http API, a change was necessary to the way arguments are send
|
||||
along with the request. Webocket requests should now send "keyword
|
||||
along with the request. Websocket requests should now send "keyword
|
||||
arguments" rather than "variable arguments". The test client has been
|
||||
updated to reflect these changes, see main.js and json-rpc.js, specifically
|
||||
the new method `call_method_with_kwargs`. For status requests this simply
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
adxl
|
||||
apikey
|
||||
apirequest
|
||||
apiresponse
|
||||
argone
|
||||
argtwo
|
||||
arksine
|
||||
armv
|
||||
asvc
|
||||
asyncio
|
||||
atmega
|
||||
Benchy
|
||||
bigtreetech
|
||||
binutils
|
||||
calicat
|
||||
camerastreamer
|
||||
canbus
|
||||
cansocket
|
||||
cmnd
|
||||
comms
|
||||
compat
|
||||
configfile
|
||||
configheler
|
||||
confighelper
|
||||
configurator
|
||||
Connor
|
||||
crowsnest
|
||||
Cura
|
||||
datapath
|
||||
datasheet
|
||||
dbus
|
||||
devel
|
||||
distro
|
||||
distros
|
||||
Domoticz
|
||||
Donkie
|
||||
eeprom
|
||||
endstop
|
||||
endstops
|
||||
EPCOS
|
||||
eventtime
|
||||
extr
|
||||
feedrate
|
||||
filelist
|
||||
fileobj
|
||||
firemon
|
||||
Fluidd
|
||||
fourcc
|
||||
fromjson
|
||||
frontends
|
||||
ftdi
|
||||
gcode
|
||||
gcodes
|
||||
getboolean
|
||||
getfloat
|
||||
getfqdn
|
||||
getint
|
||||
getitem
|
||||
getsection
|
||||
gpio
|
||||
gpiochip
|
||||
hexeditor
|
||||
highspeed
|
||||
hlsstream
|
||||
homeassistant
|
||||
homeseer
|
||||
httpx
|
||||
inotify
|
||||
ipstream
|
||||
jmuxer
|
||||
journalctl
|
||||
Kasa
|
||||
katapult
|
||||
klipper
|
||||
klippy
|
||||
klippysocket
|
||||
kwargs
|
||||
libcamera
|
||||
libgpiod
|
||||
libnacl
|
||||
lmdb
|
||||
logind
|
||||
Loxone
|
||||
loxonev
|
||||
mediamtx
|
||||
metascan
|
||||
microsteps
|
||||
mjpeg
|
||||
mjpegstreamer
|
||||
MJPG
|
||||
Mobileraker
|
||||
moko
|
||||
moonagent
|
||||
moontest
|
||||
msgspec
|
||||
Muxer
|
||||
mypassword
|
||||
mypy
|
||||
neopixel
|
||||
neopixels
|
||||
Obico
|
||||
octoeverywhere
|
||||
octoprint
|
||||
oneshot
|
||||
packagekit
|
||||
packagename
|
||||
paneldue
|
||||
piezo
|
||||
PKGLIST
|
||||
poweroff
|
||||
Prusa
|
||||
pstats
|
||||
pullup
|
||||
pyapp
|
||||
Pycurl
|
||||
pyproject
|
||||
pyserial
|
||||
raspberrypi
|
||||
ratos
|
||||
rawparams
|
||||
readwrite
|
||||
sdcard
|
||||
sdcardinfo
|
||||
sdist
|
||||
Semitec
|
||||
setitem
|
||||
sgbrg
|
||||
simplyprint
|
||||
smartplug
|
||||
smartthings
|
||||
spoolman
|
||||
SSDP
|
||||
stallguard
|
||||
subdir
|
||||
supervisord
|
||||
sysfs
|
||||
sysinfo
|
||||
tasmota
|
||||
telegam
|
||||
testcam
|
||||
testdir
|
||||
testuser
|
||||
TESTZ
|
||||
tojson
|
||||
tplink
|
||||
trapq
|
||||
uart
|
||||
ububctl
|
||||
uhubctl
|
||||
unicam
|
||||
unixsocket
|
||||
userpass
|
||||
uvcvideo
|
||||
uvloop
|
||||
vcgencmd
|
||||
venv
|
||||
virt
|
||||
virtualenv
|
||||
volted
|
||||
webcamd
|
||||
webrtc
|
||||
websockets
|
||||
wlan
|
||||
WLED
|
||||
worktrees
|
||||
yuyv
|
||||
zeroconf
|
||||
Zigbee
|
||||
@@ -0,0 +1,4 @@
|
||||
mkdocs-material==9.7.5
|
||||
pymdown-extensions~=10.21.0
|
||||
compact_tables@git+https://github.com/Arksine/markdown-compact-tables@v1.1.0
|
||||
./docs/pymdown-extras
|
||||
@@ -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") }}
|
||||
@@ -1,5 +1,5 @@
|
||||
# Example Home Assistant configuration file for a Voron V0.
|
||||
# Credit to GitHub user @Kruppes
|
||||
# Credit to GitHub users @Kruppes and @pedrolamas
|
||||
#
|
||||
sensor:
|
||||
- platform: rest
|
||||
@@ -13,40 +13,99 @@ sensor:
|
||||
- toolhead
|
||||
- display_status
|
||||
- virtual_sdcard
|
||||
value_template: 'OK'
|
||||
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'
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
|
||||
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:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
|
||||
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:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
|
||||
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:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
|
||||
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:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["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"]}}'
|
||||
value_template: >-
|
||||
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['filename'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
|
||||
|
||||
vzero_current_progress:
|
||||
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
|
||||
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:
|
||||
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
|
||||
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:
|
||||
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)}}'
|
||||
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:
|
||||
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)}}'
|
||||
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:
|
||||
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}}'
|
||||
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:
|
||||
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}}'
|
||||
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,692 @@
|
||||
# Announcements
|
||||
|
||||
The following endpoints are available to manage announcements.
|
||||
Moonraker announcements are effectively push notifications that
|
||||
can be used to notify users of important information related the
|
||||
development and status of software in the Klipper ecosystem.
|
||||
See [the appendix](#appendix) for details on how announcements
|
||||
work and recommendations for your implementation.
|
||||
|
||||
## List announcements
|
||||
|
||||
Retrieves a list of current announcements.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/announcements/list?include_dismissed=false
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.list",
|
||||
"params": {
|
||||
"include_dismissed": false
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------------------- | :--: | ------- | ----------------------------------- |
|
||||
| `include_dismissed` | bool | true | When set to false dismissed entries |
|
||||
| | | | will be excluded from the returned |^
|
||||
| | | | list of current announcements. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"entries": [
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/3",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/3",
|
||||
"title": "Test announcement 3",
|
||||
"description": "Test Description [with a link](https://moonraker.readthedocs.io).",
|
||||
"priority": "normal",
|
||||
"date": 1647459219,
|
||||
"dismissed": false,
|
||||
"date_dismissed": null,
|
||||
"dismiss_wake": null,
|
||||
"source": "moonlight",
|
||||
"feed": "moonlight"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/2",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/2",
|
||||
"title": "Announcement Test Two",
|
||||
"description": "This is a high priority announcement. This line is included in the description.",
|
||||
"priority": "high",
|
||||
"date": 1646855579,
|
||||
"dismissed": false,
|
||||
"date_dismissed": null,
|
||||
"dismiss_wake": null,
|
||||
"source": "moonlight",
|
||||
"feed": "moonlight"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/1",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/1",
|
||||
"title": "Announcement Test One",
|
||||
"description": "This is the description. Anything here should appear in the announcement, up to 512 characters.",
|
||||
"priority": "normal",
|
||||
"date": 1646854678,
|
||||
"dismissed": false,
|
||||
"date_dismissed": null,
|
||||
"dismiss_wake": null,
|
||||
"source": "moonlight",
|
||||
"feed": "moonlight"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonraker/issue/349",
|
||||
"url": "https://github.com/Arksine/moonraker/issues/349",
|
||||
"title": "PolicyKit warnings; unable to manage services, restart system, or update packages",
|
||||
"description": "This announcement is an effort to get ahead of a coming change that will certainly result in issues. PR #346 has been merged, and with it are some changes to Moonraker's default behavior.",
|
||||
"priority": "normal",
|
||||
"date": 1643392406,
|
||||
"dismissed": false,
|
||||
"dismiss_wake": null,
|
||||
"source": "moonlight",
|
||||
"feed": "Moonraker"
|
||||
}
|
||||
],
|
||||
"feeds": [
|
||||
"moonraker",
|
||||
"klipper",
|
||||
"moonlight"
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :------: | ---------------------------------------------------------- |
|
||||
| `entries` | [object] | An array of [announcement entry](#announcement-entry-spec) |
|
||||
| | | objects. The array is sorted by date in descending order |^
|
||||
| | | (newest to oldest). |^
|
||||
| `feeds` | [string] | An array of RSS announcement feeds Moonraker is |
|
||||
| | | currently subscribed to. |^
|
||||
{ #list-announcements-spec }
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------------- | :-----------: | ------------------------------------------------------------ |
|
||||
| `entry_id` | string | A unique identifier for the announcement entry. |
|
||||
| `url` | string | A url associated with the announcement. This will link to |
|
||||
| | | a GitHub issue for announcements sourced from `moonlight`. |^
|
||||
| `title` | string | The title of the announcement. |
|
||||
| `description` | string | A brief description of the announcement. For announcement's |
|
||||
| | | sourced from `moonlight` this will be the first paragraph |^
|
||||
| | | of the associated GitHub issue. Moonlight will truncate |^
|
||||
| | | truncate descriptions over 512 characters. |^
|
||||
| `priority` | string | The [priority](#announcement-priority-desc) of the |
|
||||
| | | announcement. |^
|
||||
| `date` | int \| float | The announcement creation date in unix time. |
|
||||
| `dismissed` | bool | Set to `true` if the announcement has been dismissed. |
|
||||
| `date_dismissed` | float \| null | The date, in unix time, the announcement was last dismissed. |
|
||||
| | | Will be `null` if the announcement has not been dismissed. |^
|
||||
| `dismiss_wake` | float \| null | The amount of time remaining, in seconds, before the entry's |
|
||||
| | | `dismissed` flag reverts to `true`. Will be `null` if the |^
|
||||
| | | announcement has not been dismissed or if the announcement |^
|
||||
| | | was dismissed indefinitely. |^
|
||||
| `source` | string | The [source](#announcement-source-desc) of the announcement. |
|
||||
| `feed` | string | The registered RSS feed the announcement belongs to. For |
|
||||
| | | announcements sourced internally this will typically be |^
|
||||
| | | the name of the component that generated the announcement. |^
|
||||
{ #announcement-entry-spec } Announcement Entry
|
||||
|
||||
| Priority | Description |
|
||||
| -------- | ----------------------------------------------------------------- |
|
||||
| `normal` | Standard priority. Front-end devs should use their own discretion |
|
||||
| | on how to present announcements with normal priority to users. |^
|
||||
| `high` | High priority. It is recommended that front-ends alert the user |
|
||||
| | when a high priority announcement is received. |^
|
||||
{ #announcement-priority-desc } Announcement Priority
|
||||
|
||||
| Source | Description |
|
||||
| ----------- | -------------------------------------------------------------------- |
|
||||
| `moonlight` | The announcement was received from the |
|
||||
| | [moonlight](https://github.com/Arksine/moonlight) GitHub repo. |^
|
||||
| | Announcements received from local XML files when the `announcements` |^
|
||||
| | module is configured in `dev_mode` will also report the source as |^
|
||||
| | `moonlight`. |^
|
||||
| `internal` | The announcement was generated by Moonraker itself. This could |
|
||||
| | be a component, such as `simplyprint`. |^
|
||||
{ #announcement-source-desc } Announcement Source
|
||||
|
||||
///
|
||||
|
||||
## Update announcements
|
||||
Requests that Moonraker check for announcement updates. This is generally
|
||||
not required in production, as Moonraker will automatically check for
|
||||
updates every 30 minutes. However, during development this endpoint is
|
||||
useful to force an update when it is necessary to perform integration
|
||||
tests.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/announcements/update
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.update",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
Returns:
|
||||
|
||||
The current list of announcements, in descending order (newest to oldest)
|
||||
sorted by `date`, and a `modified` field that contains a boolean value
|
||||
indicating if the update resulted in a change:
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"entries": [
|
||||
{
|
||||
"entry_id": "arksine/moonraker/issue/349",
|
||||
"url": "https://github.com/Arksine/moonraker/issues/349",
|
||||
"title": "PolicyKit warnings; unable to manage services, restart system, or update packages",
|
||||
"description": "This announcement is an effort to get ahead of a coming change that will certainly result in issues. PR #346 has been merged, and with it are some changes to Moonraker's default behavior.",
|
||||
"priority": "normal",
|
||||
"date": 1643392406,
|
||||
"dismissed": false,
|
||||
"source": "moonlight",
|
||||
"feed": "Moonraker"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/1",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/1",
|
||||
"title": "Announcement Test One",
|
||||
"description": "This is the description. Anything here should appear in the announcement, up to 512 characters.",
|
||||
"priority": "normal",
|
||||
"date": 1646854678,
|
||||
"dismissed": true,
|
||||
"source": "moonlight",
|
||||
"feed": "Moonlight"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/2",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/2",
|
||||
"title": "Announcement Test Two",
|
||||
"description": "This is a high priority announcement. This line is included in the description.",
|
||||
"priority": "high",
|
||||
"date": 1646855579,
|
||||
"dismissed": false,
|
||||
"source": "moonlight",
|
||||
"feed": "Moonlight"
|
||||
},
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/3",
|
||||
"url": "https://github.com/Arksine/moonlight/issues/3",
|
||||
"title": "Test announcement 3",
|
||||
"description": "Test Description [with a link](https://moonraker.readthedocs.io).",
|
||||
"priority": "normal",
|
||||
"date": 1647459219,
|
||||
"dismissed": false,
|
||||
"source": "moonlight",
|
||||
"feed": "Moonlight"
|
||||
}
|
||||
],
|
||||
"modified": false
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :------: | ---------------------------------------------------------- |
|
||||
| `entries` | [object] | An array of [Announcement Entry](#announcement-entry-spec) |
|
||||
| | | objects. |^
|
||||
| `modified` | bool | A value of `true` indicates that announcement entries |
|
||||
| | | were changed after the update operation. |^
|
||||
|
||||
///
|
||||
|
||||
## Dismiss an announcement
|
||||
Sets the dismiss flag of an announcement to `true`.
|
||||
|
||||
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/announcements/dismiss
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/1",
|
||||
"wake_time": 600
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.dismiss",
|
||||
"params": {
|
||||
"entry_id": "arksine/moonlight/issue/1",
|
||||
"wake_time": 600
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :-----------: | ------------ | -------------------------------------------- |
|
||||
| `entry_id` | string | **REQUIRED** | The entry ID of the announcement to dismiss. |
|
||||
| `wake_time` | float \| null | null | A time, in seconds, after which the entry's |
|
||||
| | | | `dismiss` flag will revert to `true`. When |^
|
||||
| | | | set to `null` the flag will remain `false` |^
|
||||
| | | | indefinitely. |^
|
||||
|
||||
//// tip
|
||||
The `entry_id` typically contains forward slashes. Remember to escape this value
|
||||
if including it in the query string of an HTTP request.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"entry_id": "arksine/moonlight/issue/1"
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ------------------------------------------------- |
|
||||
| `entry_id` | string | The entry ID of the dismissed announcement entry. |
|
||||
|
||||
///
|
||||
|
||||
## List announcement feeds
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/announcements/feeds
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.feeds",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"feeds": [
|
||||
"moonraker",
|
||||
"klipper"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------- | :------: | ----------------------------------------------------- |
|
||||
| `feeds` | [string] | An array of announcement feeds Moonraker is currently |
|
||||
| | | subscribed to. |^
|
||||
|
||||
///
|
||||
|
||||
## Subscribe to an announcement feed
|
||||
|
||||
Subscribes Moonraker to the announcement feed specified in the request.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/announcements/feed
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "my_feed"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.post_feed",
|
||||
"params": {
|
||||
"name": "my_feed"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------------ | -------------------------------------------------- |
|
||||
| `name` | string | **REQUIRED** | The name of the announcement feed to subscribe to. |
|
||||
|
||||
///
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"feed": "my_feed",
|
||||
"action": "added"
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :----: | -------------------------------------------------------- |
|
||||
| `feed` | string | The name of the announcement feed subscribed to. |
|
||||
| `action` | string | The [subscription action](#feed-subscribed-action-desc ) |
|
||||
| | | taken by Moonraker after the request has been processed. |^
|
||||
|
||||
| Action | Description |
|
||||
| --------- | ------------------------------------------------------- |
|
||||
| `added` | The requested announcement feed has been subscribed to. |
|
||||
| `skipped` | Moonraker was already subscribed to the requested feed. |
|
||||
{ #feed-subscribed-action-desc } Subscription Action
|
||||
|
||||
///
|
||||
|
||||
## Remove an announcement feed
|
||||
|
||||
Removes a subscribed feed. Only feeds previously subscribed to using
|
||||
the [subscribe feed](#subscribe-to-an-announcement-feed) endpoint may be
|
||||
removed. Feeds configured in `moonraker.conf` may not be removed.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/announcements/feed?name=my_feed
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.announcements.delete_feed",
|
||||
"params": {
|
||||
"name": "my_feed"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------------ | -------------------------------------------- |
|
||||
| `name` | string | **REQUIRED** | The name of the announcement feed to remove. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
Parameters:
|
||||
|
||||
- `name`: The name of the new feed to remove. This parameter is required.
|
||||
|
||||
Returns:
|
||||
|
||||
The name of the new feed and the action taken. The `action` will be
|
||||
`removed` if the operation was successful.
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"feed": "my_feed",
|
||||
"action": "removed"
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :----: | ------------------------------------------------------ |
|
||||
| `feed` | string | The name of the announcement feed removed. |
|
||||
| `action` | string | The action taken after the request. Will be `removed` |
|
||||
| | | upon successful removal. |^
|
||||
|
||||
//// tip
|
||||
Unlike the [feed subscription request](#subscribe-to-an-announcement-feed) an
|
||||
error will be returned if either the feed does not exist or the feed is
|
||||
configured in `moonraker.conf`.
|
||||
////
|
||||
///
|
||||
|
||||
## Appendix
|
||||
|
||||
This section will provide an overview of how the announcement system
|
||||
in Moonraker works, how to set up a dev environment, and provide
|
||||
recommendations on front-end implementation.
|
||||
|
||||
### How announcements work
|
||||
|
||||
Moonraker announcements are GitHub issues tagged with the `announcement`
|
||||
label. GitHub repos may registered with
|
||||
[moonlight](https://github.com/arksine/moonlight), which is responsible
|
||||
for generating RSS feeds from GitHub issues using GitHub's REST API. These
|
||||
RSS feeds are hosted on GitHub Pages, for example Moonraker's feed may be found
|
||||
[here](https://arksine.github.io/moonlight/assets/moonraker.xml). By
|
||||
centralizing GitHub API queries in `moonlight` we are able to poll multiple
|
||||
repos without running into API rate limit issues. Moonlight has has a workflow
|
||||
that checks all registered repos for new announcements every 30 minutes. In
|
||||
theory it would be able to check for announcements in up to 500 repos before
|
||||
exceeding GitHub's API rate limit.
|
||||
|
||||
Moonraker's `[announcements]` component will always check the `klipper` and
|
||||
`moonraker` RSS feeds. It is possible to configure additional RSS feeds by
|
||||
adding them to the `subscriptions` option. The component will poll configured
|
||||
feeds every 30 minutes, resulting in maximum of 1 hour for new announcements
|
||||
to reach all users.
|
||||
|
||||
When new issues are tagged with `announcement` these entries will be parsed
|
||||
and added to the RSS feeds. When the issue is closed they will be removed from
|
||||
the corresponding feed. Moonlight will fetch up to 20 announcements for each
|
||||
feed, if a repo goes over this limit older announcements will be removed.
|
||||
|
||||
/// Note
|
||||
It is also possible for Moonraker to generate announcements itself. For
|
||||
example, if a Moonraker component needs user feedback it may generate an
|
||||
announcement and notify all connected clients. From a front-end's
|
||||
perspective there is no need to treat these announcements differently than
|
||||
any other announcement.
|
||||
///
|
||||
|
||||
### Setting up the dev environment
|
||||
|
||||
Moonraker provides configuration to parse announcements from a local folder
|
||||
so that it is possible to manually add and remove entries, allowing front-end
|
||||
developers to perform integration tests:
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[announcements]
|
||||
dev_mode: True
|
||||
```
|
||||
|
||||
With `dev_mode` enabled, Moonraker will look for`moonraker.xml` and
|
||||
`klipper.xml` in the following folder:
|
||||
```shell
|
||||
~/moonraker/.devel/announcement_xml
|
||||
```
|
||||
|
||||
If moonraker is not installed in the home folder then substitute `~`
|
||||
for the parent folder location. This folder is in a hardcoded location
|
||||
to so as not to expose users to vulnerabilities associated with parsing XML.
|
||||
|
||||
It is possible to configure Moonraker to search for your own feeds:
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[announcements]
|
||||
subscription:
|
||||
my_project
|
||||
dev_mode: True
|
||||
```
|
||||
|
||||
The above configuration would look for `my_project.xml` in addition to
|
||||
`klipper.xml` and `moonraker.xml`. The developer may manually create
|
||||
the xml feeds or they may clone `moonlight` and leverage its script
|
||||
to generate a feed from issues created on their test repo. When local
|
||||
feeds have been modified one may call the [update announcements API](#update-announcements)
|
||||
to have Moonraker fetch the updates and add/remove entries.
|
||||
|
||||
### RSS file structure
|
||||
|
||||
Moonlight generates RSS feeds in XML format. Below is an example generated
|
||||
from moonlight's own issue tracker:
|
||||
|
||||
```xml
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<rss version="2.0" xmlns:moonlight="https://arksine.github.io/moonlight">
|
||||
<channel>
|
||||
<title>arksine/moonlight</title>
|
||||
<link>https://github.com/Arksine/moonlight</link>
|
||||
<description>RSS Announcements for Moonraker</description>
|
||||
<pubDate>Tue, 22 Mar 2022 23:19:04 GMT</pubDate>
|
||||
<moonlight:configHash>f2912192bf0d09cf18d8b8af22b2d3501627043e5afa3ebff0e45e4794937901</moonlight:configHash>
|
||||
<item>
|
||||
<title>Test announcement 3</title>
|
||||
<link>https://github.com/Arksine/moonlight/issues/3</link>
|
||||
<description>Test Description [with a link](https://moonraker.readthedocs.io).</description>
|
||||
<pubDate>Wed, 16 Mar 2022 19:33:39 GMT</pubDate>
|
||||
<category>normal</category>
|
||||
<guid>arksine/moonlight/issue/3</guid>
|
||||
</item>
|
||||
<item>
|
||||
<title>Announcement Test Two</title>
|
||||
<link>https://github.com/Arksine/moonlight/issues/2</link>
|
||||
<description>This is a high priority announcement. This line is included in the description.</description>
|
||||
<pubDate>Wed, 09 Mar 2022 19:52:59 GMT</pubDate>
|
||||
<category>high</category>
|
||||
<guid>arksine/moonlight/issue/2</guid>
|
||||
</item>
|
||||
<item>
|
||||
<title>Announcement Test One</title>
|
||||
<link>https://github.com/Arksine/moonlight/issues/1</link>
|
||||
<description>This is the description. Anything here should appear in the announcement, up to 512 characters.</description>
|
||||
<pubDate>Wed, 09 Mar 2022 19:37:58 GMT</pubDate>
|
||||
<category>normal</category>
|
||||
<guid>arksine/moonlight/issue/1</guid>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
```
|
||||
|
||||
Each xml file may contain only one `<rss>` element, and each `<rss>` element
|
||||
may contain only one channel. All items must be present aside from
|
||||
`moonlight:configHash`, which is used by the workflow to detect changes to
|
||||
moonlight's configuration. Most elements are self explanatory, developers will
|
||||
be most interested in adding and removing `<item>` elements, as these are
|
||||
the basis for entries in Moonraker's announcement database.
|
||||
|
||||
### Generating announcements from your own repo
|
||||
|
||||
As mentioned previously, its possible to clone moonlight and use its rss
|
||||
script to generate announcements from issues in your repo:
|
||||
|
||||
```shell
|
||||
cd ~
|
||||
git clone https://github.com/arksine/moonlight
|
||||
cd moonlight
|
||||
virtualenv -p /usr/bin/python3 .venv
|
||||
source .venv/bin/activate
|
||||
pip install httpx[http2]
|
||||
deactivate
|
||||
```
|
||||
|
||||
To add your repo edit `~/moonlight/src/config.json`:
|
||||
```json
|
||||
{
|
||||
"moonraker": {
|
||||
"repo_owner": "Arksine",
|
||||
"repo_name": "moonraker",
|
||||
"description": "API Host For Klipper",
|
||||
"authorized_creators": ["Arksine"]
|
||||
},
|
||||
"klipper": {
|
||||
"repo_owner": "Klipper3d",
|
||||
"repo_name": "klipper",
|
||||
"description": "A 3D Printer Firmware",
|
||||
"authorized_creators": ["KevinOConnor"]
|
||||
},
|
||||
// Add your test repo info here. It should contain
|
||||
// fields matching those in "moonraker" and "klipper"
|
||||
// shown above.
|
||||
}
|
||||
```
|
||||
|
||||
Once your repo is added, create one or more issues on your GitHub
|
||||
repo tagged with the `announcement` label. Add the `critical` label to
|
||||
one if you wish to test high priority announcements. You may need to
|
||||
create these labels in your repo before they can be added.
|
||||
|
||||
Now we can use moonlight to generate the xml files:
|
||||
```shell
|
||||
cd ~/moonlight
|
||||
source .venv/bin/activate
|
||||
src/update_rss.py
|
||||
deactivate
|
||||
```
|
||||
|
||||
After the script has run it will generate the configured RSS feeds
|
||||
and store them in `~/moonlight/assets`. If using this method it may
|
||||
be useful to create a symbolic link to it in Moonraker's devel folder:
|
||||
|
||||
```shell
|
||||
cd ~/moonraker
|
||||
mkdir .devel
|
||||
cd .devel
|
||||
ln -s ~/moonlight/assets announcement_xml
|
||||
```
|
||||
|
||||
If you haven't done so, configure Moonraker to subscribe to your feed
|
||||
and restart the Moonraker service. Otherwise you may call the
|
||||
[announcement update](#update-announcements) API to have Moonraker
|
||||
parse the announcements from your test feed.
|
||||
|
||||
|
||||
### Implementation details and recommendations
|
||||
|
||||
When a front-end first connects to Moonraker it is recommended that the
|
||||
[list announcements](#list-announcements) API is called to retrieve
|
||||
the current list of [announcement entries](#announcement-entry-spec).
|
||||
If the front-end is connected via websocket it may watch for the
|
||||
[announcement update](./jsonrpc_notifications.md#announcement-update-event) and
|
||||
[announcement dismissed](./jsonrpc_notifications.md#announcement-dismissed-event)
|
||||
JSON-RPC notifications and update its UI accordingly.
|
||||
|
||||
Front-end devs should decide how they want to present announcements to users.
|
||||
They could be treated as any other notification, for example a front-end
|
||||
may have a notification icon that shows the current number of unread
|
||||
announcements. Front-ends can mark an announcement as `read` by calling
|
||||
the [dismiss announcement](#dismiss-an-announcement) endpoint. Any
|
||||
announcement entry with `dismissed == true` should be considered read.
|
||||
|
||||
When a `high priority` announcement is detected it is recommended that
|
||||
clients present the announcement in a format that is immediately visible
|
||||
to the user. That said, it may be wise to allow users to opt out of
|
||||
this behavior via configuration.
|
||||
|
||||
/// note
|
||||
If an announcement is dismissed, closed on GitHub, then reopened,
|
||||
the `dismissed` flag will reset to false. This is expected behavior
|
||||
as announcements are pruned from the database when they are no
|
||||
longer present in feeds. It isn't valid for repo maintainers
|
||||
to re-open a closed announcement. That said, its fine to close
|
||||
and re-open issues during development and testing using repos
|
||||
that are not yet registered with moonlight.
|
||||
///
|
||||
@@ -0,0 +1,635 @@
|
||||
|
||||
# Authorization and Authentication
|
||||
|
||||
The Authorization endpoints provide access to the various methods
|
||||
used to authorize connections to Moonraker. This includes user
|
||||
authentication, API Key authentication, Temporary access via
|
||||
"oneshot tokens", and IP and/or domain based authentication
|
||||
("ie: trusted clients).
|
||||
|
||||
Untrusted clients must use either a JSON Web Token or an API key to access
|
||||
Moonraker's HTTP APIs. JWTs should be included in the `Authorization`
|
||||
header as a `Bearer` type for each HTTP request. If using an API Key it
|
||||
should be included in the `X-Api-Key` header for each HTTP Request.
|
||||
|
||||
Websocket authentication can be achieved via the request itself or
|
||||
post connection. Unlike HTTP requests it is not necessary to pass a
|
||||
token and/or API Key to each request. The
|
||||
[identify connection](./server.md#identify-connection) endpoint takes optional
|
||||
`access_token` and `api_key` parameters that may be used to authenticate
|
||||
a user already logged in, otherwise the `login` API may be used for
|
||||
authentication. Websocket connections will stay authenticated until
|
||||
the connection is closed or the user logs out.
|
||||
|
||||
User authentication can be performed using a choice sources. Moonraker
|
||||
currently supports the following authentication sources:
|
||||
|
||||
| Source Name | Description |
|
||||
| ----------- | -------------------------------------------------------------- |
|
||||
| `moonraker` | Authentication is performed using credentials stored in |
|
||||
| | Moonraker's database. |^
|
||||
| `ldap` | Authentication is performed through a connected LDAP provider. |
|
||||
| | Requires a valid `[LDAP]` configuration. |^
|
||||
{ #auth-source-desc } Authentication Source
|
||||
|
||||
/// note
|
||||
ECMAScript imposes limitations on certain requests that prohibit the
|
||||
developer from modifying the HTTP headers (ie: Requests to open a
|
||||
websocket, "download" requests that open a user dialog). In these cases
|
||||
it is recommended for the developer to request a `oneshot_token`, then
|
||||
send the result via the `token` query string argument in the desired
|
||||
request.
|
||||
///
|
||||
|
||||
/// warning
|
||||
It is strongly recommended that arguments for the below APIs are
|
||||
passed in the request's body.
|
||||
///
|
||||
|
||||
## Login User
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "my_user",
|
||||
"password": "my_password",
|
||||
"source": "moonraker"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.login",
|
||||
"params": {
|
||||
"username": "my_user",
|
||||
"password": "my_password",
|
||||
"source": "moonraker"
|
||||
},
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | -------------------- | --------------------------------------------------- |
|
||||
| `username` | string | **REQUIRED** | The user login name. |
|
||||
| `password` | string | **REQUIRED** | The user password. |
|
||||
| `source` | string | Set by configuration | A valid [authentication source](#auth-source-desc). |
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNjU1LCAiZXhwIjogMTYxODg4MDQwMC40ODE2NTUsICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.QdieeEskrU0FrH7rXKuPDSZxscM54kV_vH60uJqdU9g",
|
||||
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY4MDAuNDgxNzUxNCwgImV4cCI6IDE2MjY2NTI4MDAuNDgxNzUxNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.btJF0LJfymInhGJQ2xvPwkp2dFUqwgcw4OA_wE-EcCM",
|
||||
"action": "user_logged_in",
|
||||
"source": "moonraker"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------- | :----: | -------------------------------------------------------------------- |
|
||||
| `username` | string | The name of the logged in user. |
|
||||
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
|
||||
| | | referred to as an `access token`. HTTP requests should include this |^
|
||||
| | | token in the `Authorization` header as a `Bearer` type. This token |^
|
||||
| | | expires after 1 hour. |^
|
||||
| `refresh_token` | string | A JWT that should be used to generate new access tokens after they |
|
||||
| | | expire. See the [refresh token section](#refresh-json-web-token) |^
|
||||
| | | for details. |^
|
||||
| `action` | string | The action taken by the auth manager. Will always be |
|
||||
| | | "user_logged_in". |^
|
||||
| `source` | string | The [authentication source](#auth-source-desc) used. |
|
||||
|
||||
///
|
||||
|
||||
/// note
|
||||
This endpoint may be accessed without prior authentication. A 401 will
|
||||
only be returned if the authentication fails.
|
||||
///
|
||||
|
||||
## Logout Current User
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/logout
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.logout",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"action": "user_logged_out"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ----------------------------------------------------- |
|
||||
| `username` | string | The name of the logged out user. |
|
||||
| `action` | string | The action taken by the auth manager. Will always be |
|
||||
| | | "user_logged_out". |^
|
||||
|
||||
///
|
||||
|
||||
## Get Current User
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /access/user
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.get_user",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
Returns: An object containing the currently logged in user name, the source and
|
||||
the date on which the user was created (in unix time).
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"source": "moonraker",
|
||||
"created_on": 1618876783.8896716
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | :----: | ---------------------------------------------------- |
|
||||
| `username` | string | The name of the logged in user. |
|
||||
| `source` | string | The [source](#auth-source-desc) used to authenticate |
|
||||
| | | the user. |^
|
||||
| `created_on` | float | The date, in unix time, the user entry was created. |
|
||||
|
||||
///
|
||||
|
||||
## Create User
|
||||
|
||||
Creates a new local user and logs them in.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/user
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "my_user",
|
||||
"password": "my_password"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.post_user",
|
||||
"params": {
|
||||
"username": "my_user",
|
||||
"password": "my_password"
|
||||
},
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | ------------ | -------------------- |
|
||||
| `username` | string | **REQUIRED** | The user login name. |
|
||||
| `password` | string | **REQUIRED** | The user password. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNjE5LCAiZXhwIjogMTYxODg4MDM4My44OTE2MTksICJ1c2VybmFtZSI6ICJteV91c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.oH0IShTL7mdlVs4kcx3BIs_-1j0Oe-qXezJKjo-9Xgo",
|
||||
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzY3ODMuODkxNzAyNCwgImV4cCI6IDE2MjY2NTI3ODMuODkxNzAyNCwgInVzZXJuYW1lIjogIm15X3VzZXIiLCAidG9rZW5fdHlwZSI6ICJyZWZyZXNoIn0.a6ZeRjk8RQQJDDH0JV-qGY_d_HIgfI3XpsqUlUaFT7c",
|
||||
"source": "moonraker",
|
||||
"action": "user_created"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------- | :----: | --------------------------------------------------------------------- |
|
||||
| `username` | string | The name of the created user. |
|
||||
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
|
||||
| | | referred to as an `access token`. HTTP requests should include this |^
|
||||
| | | token in the `Authorization` header as a `Bearer` type. This token |^
|
||||
| | | expires after 1 hour. |^
|
||||
| `refresh_token` | string | A JWT that should be used to generate new access tokens after they |
|
||||
| | | expire. See the [refresh token section](#refresh-json-web-token) |^
|
||||
| | | for details. |^
|
||||
| `action` | string | The action taken by the auth manager. Will always be "user_created". |
|
||||
| `source` | string | The [authentication source](#auth-source-desc) used. |
|
||||
|
||||
///
|
||||
|
||||
/// note
|
||||
Unlike `/access/login`, `/access/user` is a protected endpoint. To
|
||||
create a new user a client must either be trusted, use the API Key,
|
||||
or be logged in as another user.
|
||||
///
|
||||
|
||||
## Delete User
|
||||
|
||||
/// note
|
||||
A request to delete a user MUST come from an authorized login
|
||||
other than the account to be deleted. This can be a "trusted user",
|
||||
the "api key user", or any other user account.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /access/user
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"username": "my_username"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.delete_user",
|
||||
"params": {
|
||||
"username": "my_username"
|
||||
},
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :--: | ------------ | ------------------------------------ |
|
||||
| `username` | str | **REQUIRED** | The username of the entry to delete. |
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"action": "user_deleted"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ------------------------------------------------- |
|
||||
| `username` | string | The username of the deleted entry. |
|
||||
| `action` | string | The action taken by the auth manager. Will always |
|
||||
| | | be "user_deleted". |^
|
||||
|
||||
///
|
||||
|
||||
## List Available Users
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /access/users/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.users.list",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"users": [
|
||||
{
|
||||
"username": "testuser",
|
||||
"source": "moonraker",
|
||||
"created_on": 1618771331.1685035
|
||||
},
|
||||
{
|
||||
"username": "testuser2",
|
||||
"source": "ldap",
|
||||
"created_on": 1620943153.0191233
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------- | :------: | -------------------------------- |
|
||||
| `users` | [object] | An array of `User Info` objects. |
|
||||
| | | #user-info-spec |+
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | :----: | ---------------------------------------------------- |
|
||||
| `username` | string | The username of the entry. |
|
||||
| `source` | string | The [source](#auth-source-desc) that must be used to |
|
||||
| | | authenticate the user. |^
|
||||
| `created_on` | float | The date, in unix time, the user entry was created. |
|
||||
{ #user-info-spec } User Info
|
||||
|
||||
///
|
||||
|
||||
## Reset User Password
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/user/password
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"password": "my_current_password",
|
||||
"new_password": "my_new_pass"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.user.password",
|
||||
"params": {
|
||||
"password": "my_current_password",
|
||||
"new_password": "my_new_pass"
|
||||
},
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| -------------- | :----: | ------------ | ---------------------------- |
|
||||
| `password` | string | **REQUIRED** | The user's current password. |
|
||||
| `new_password` | string | **REQUIRED** | The user's new password. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"action": "user_password_reset"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | --------------------------------------------------- |
|
||||
| `username` | string | The username of the entry whose password was reset. |
|
||||
| `action` | string | Action taken by the Auth manager. Will always be |
|
||||
| | | "user_password_reset". |^
|
||||
|
||||
///
|
||||
|
||||
## Refresh JSON Web Token
|
||||
This endpoint can be used to refresh an expired access token. If this
|
||||
request returns an error then the refresh token is no longer valid and
|
||||
the user must login with their credentials.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/refresh_jwt
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4Nzc0ODUuNzcyMjg5OCwgImV4cCI6IDE2MjY2NTM0ODUuNzcyMjg5OCwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAicmVmcmVzaCJ9.Y5YxGuYSzwJN2WlunxlR7XNa2Y3GWK-2kt-MzHvLbP8"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.refresh_jwt",
|
||||
"params": {
|
||||
"refresh_token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4Nzc0ODUuNzcyMjg5OCwgImV4cCI6IDE2MjY2NTM0ODUuNzcyMjg5OCwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAicmVmcmVzaCJ9.Y5YxGuYSzwJN2WlunxlR7XNa2Y3GWK-2kt-MzHvLbP8"
|
||||
},
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| --------------- | :----: | ------------ | ------------------------------------- |
|
||||
| `refresh_token` | string | **REQUIRED** | A valid `refresh_token` for the user. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"username": "my_user",
|
||||
"token": "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiTW9vbnJha2VyIiwgImlhdCI6IDE2MTg4NzgyNDMuNTE2Nzc5MiwgImV4cCI6IDE2MTg4ODE4NDMuNTE2Nzc5MiwgInVzZXJuYW1lIjogInRlc3R1c2VyIiwgInRva2VuX3R5cGUiOiAiYXV0aCJ9.Ia_X_pf20RR4RAEXcxalZIOzOBOs2OwearWHfRnTSGU",
|
||||
"source": "moonraker",
|
||||
"action": "user_jwt_refresh"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | -------------------------------------------------------------------- |
|
||||
| `username` | string | The username of the entry whose access token ws refreshed. |
|
||||
| `token` | string | A JSON Web Token (JWT) used to authenticate requests, also commonly |
|
||||
| | | referred to as an `access token`. HTTP requests should include this |^
|
||||
| | | token in the `Authorization` header as a `Bearer` type. This token |^
|
||||
| | | expires after 1 hour. |^
|
||||
| `source` | string | The [authentication source](#auth-source-desc) of the user entry. |
|
||||
| `action` | string | The action taken by the Auth Manager. Will always be |
|
||||
| | | "user_jwt_refresh". |^
|
||||
|
||||
///
|
||||
|
||||
/// note
|
||||
This endpoint may be accessed by unauthorized clients. A 401 will
|
||||
only be returned if the refresh token is invalid.
|
||||
///
|
||||
|
||||
## Generate a Oneshot Token
|
||||
|
||||
Javascript is not capable of modifying the headers for some HTTP requests
|
||||
(for example, the `websocket`), which is a requirement to apply JWT or API Key
|
||||
authorization. To work around this clients may request a Oneshot Token and
|
||||
pass it via the query string for these requests. Tokens expire in 5 seconds
|
||||
and may only be used once, making them relatively safe for inclusion in the
|
||||
query string.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /access/oneshot_token
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.oneshot_token",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
"APDBEGHUTBUD6SOAYBPF3KE5BRMO7YSL"
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
The response is a string value containing the oneshot token. It may
|
||||
added to a request's query string for access to any API endpoint. The query
|
||||
string should be added in the form of:
|
||||
|
||||
```
|
||||
?token={base32_random_token}
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
## Get authorization module info
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /access/info
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.info",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"default_source": "moonraker",
|
||||
"available_sources": [
|
||||
"moonraker",
|
||||
"ldap"
|
||||
],
|
||||
"login_required": false,
|
||||
"trusted": true
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------- | :------: | ---------------------------------------------------- |
|
||||
| `default_source` | string | The configured default |
|
||||
| | | [authentication source](#auth-source-desc). |^
|
||||
| `available_sources` | [string] | An array of available authentication sources. |
|
||||
| `login_required` | bool | Set to `true` when `force_logins` is enabled via the |
|
||||
| | | configuration at least one user has been created. |^
|
||||
| `trusted` | bool | Set to `true` when the connection making the info |
|
||||
| | | request is a trusted connection. |^
|
||||
|
||||
///
|
||||
|
||||
/// note
|
||||
This endpoint may be accessed by unauthorized clients.
|
||||
///
|
||||
|
||||
## Get the Current API Key
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /access/api_key
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.get_api_key",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
e514851f37b94c779d955212b6906f95
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
The response string value containing the current API key.
|
||||
|
||||
///
|
||||
|
||||
## Generate a New API Key
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /access/api_key
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "access.post_api_key",
|
||||
"id": 1323
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
e514851f37b94c779d955212b6906f95
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
The response string value containing the new API key.
|
||||
|
||||
///
|
||||
|
||||
/// note
|
||||
After this request executes the API key change is applied immediately.
|
||||
All subsequent HTTP requests from untrusted clients must use the new key.
|
||||
Changing the API Key will not affect open websockets authenticated using
|
||||
the previous API Key.
|
||||
///
|
||||
@@ -0,0 +1,773 @@
|
||||
# Database Management
|
||||
|
||||
The following endpoints provide access to Moonraker's internal sqlite database.
|
||||
The primary table exposed to clients is divided into `namespaces`. Each client
|
||||
may define its own namespace to store information. From the client's point of
|
||||
view, a namespace is an `object`. Items in the database are accessed by providing
|
||||
a namespace and a key. A key may be specified as string, where a "." is a
|
||||
delimiter to access nested fields. Alternatively the key may be specified
|
||||
as an array of strings, where each string references a nested field.
|
||||
This is useful for scenarios where a namespace contains fields that include
|
||||
a "." character, such as a file name.
|
||||
|
||||
/// note
|
||||
Moonraker reserves several namespaces for internal use. Clients may read from
|
||||
these namespaces but they may not modify them.
|
||||
///
|
||||
|
||||
For example, assume the following object is stored in the "superclient"
|
||||
namespace:
|
||||
|
||||
```json
|
||||
{
|
||||
"settings": {
|
||||
"console": {
|
||||
"enable_autocomplete": true
|
||||
}
|
||||
},
|
||||
"theme": {
|
||||
"background_color": "black"
|
||||
}
|
||||
}
|
||||
```
|
||||
One may access the `enable_autocomplete` field by supplying `superclient` as
|
||||
the `namespace` argument and `settings.console.enable_autocomplete` or
|
||||
`["settings", "console", "enable_autocomplete"]` as the `key` argument for
|
||||
the request. The entire settings object could be accessed by providing
|
||||
`settings` or `["settings"]` as the `key` argument. The entire namespace
|
||||
may be read by omitting the `key` argument, however as explained below it
|
||||
is not possible to modify a namespace without specifying a key.
|
||||
|
||||
## List Database Info
|
||||
|
||||
Lists all namespaces with read and/or write access. Also lists database
|
||||
backup files.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/database/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.list",
|
||||
"id": 8694
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"namespaces": [
|
||||
"gcode_metadata",
|
||||
"webcams",
|
||||
"update_manager",
|
||||
"announcements",
|
||||
"database",
|
||||
"moonraker"
|
||||
],
|
||||
"backups": [
|
||||
"sqldb-backup-20240513-134542.db",
|
||||
"testbackup.db",
|
||||
"testbackup2.db"
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | :------: | ---------------------------------------------------- |
|
||||
| `namespaces` | [string] | An array of namespaces registered with the database |
|
||||
| | | that may be read by clients. |^
|
||||
| `backups` | [string] | An array of database backup filenames that have been |
|
||||
| | | created. |^
|
||||
|
||||
///
|
||||
|
||||
## Get Database Item
|
||||
|
||||
Retrieves an item from a specified namespace. The `key` argument may be
|
||||
omitted, in which case an object representing the entire namespace will
|
||||
be returned in the `value` field. If the `key` is provided and does not
|
||||
exist in the database an error will be returned.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/database/item?namespace={namespace}&key={key}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.get_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}"
|
||||
},
|
||||
"id": 5644
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :----------------: | ------------ | ------------------------------------------ |
|
||||
| `namespace` | string | **REQUIRED** | The namespace of the item to retrieve. |
|
||||
| `key` | string \| [string] | null | The key indicating the field or fields |
|
||||
| | \| null | | within the namespace to retrieve. May |^
|
||||
| | | | be a string, where nested fields are |^
|
||||
| | | | separated by a ".", or a list of strings. |^
|
||||
| | | | If the key is omitted the entire namespace |^
|
||||
| | | | will be returned. |^
|
||||
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"namespace": "moonraker",
|
||||
"key": "file_manager.metadata_version",
|
||||
"value": 2
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------- | :----------------: | ------------------------------------------------- |
|
||||
| `namespace` | string | The namespace of the returned item. |
|
||||
| `key` | string \| [string] | The key indicating the requested field(s). |
|
||||
| | \| null | |^
|
||||
| `value` | any | The value of the requested item. This can be any |
|
||||
| | | valid JSON type. |^
|
||||
|
||||
///
|
||||
|
||||
## Add Database Item
|
||||
Inserts an item into the database. If the `namespace` does not exist
|
||||
it will be created. If the `key` specifies a nested field, all parents
|
||||
will be created if they do not exist. If the key exists it will be
|
||||
overwritten with the provided `value`. The `key` parameter must be provided,
|
||||
as it is not possible to assign a value directly to a namespace.
|
||||
|
||||
/// note
|
||||
If the request parameters are placed in the query string and the `value`
|
||||
is not a string type, then `value` argument must provide a
|
||||
[type hint](./introduction.md#query-string-type-hints). It is strongly
|
||||
recommended to put parameters in the body of the request wrapped in a
|
||||
JSON object.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/database/item
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"namespace": "my_client",
|
||||
"key": "settings.some_count",
|
||||
"value": 100
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :----------------: | ------------ | ----------------------------------------- |
|
||||
| `namespace` | string | **REQUIRED** | The namespace where the value |
|
||||
| | | | should be inserted. |^
|
||||
| `key` | string \| [string] | **REQUIRED** | The key indicating the field or fields |
|
||||
| | | | where the value should be inserted. |^
|
||||
| `value` | any | **REQUIRED** | The value to insert in the database. May |
|
||||
| | | | be any valid JSON type. |^
|
||||
|
||||
///
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.post_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}",
|
||||
"value": 100
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"namespace": "test",
|
||||
"key": "settings.some_count",
|
||||
"value": 9001
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------- | :----------------: | ------------------------------------------- |
|
||||
| `namespace` | string | The namespace where the value was inserted. |
|
||||
| `key` | string \| [string] | The key indicating the field or fields |
|
||||
| | | where the value was inserted. |^
|
||||
| `value` | any | The value inserted into the database. May |
|
||||
| | | be any valid JSON type. |^
|
||||
|
||||
///
|
||||
|
||||
## Delete Database Item
|
||||
|
||||
Deletes an item from a `namespace` at the specified `key`. If the key does not
|
||||
exist in the namespace an error will be returned. If the deleted item results
|
||||
in an empty namespace, the namespace will be removed from the database.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/database/item?namespace={namespace}&key={key}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.delete_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :----------------: | ------------ | -------------------------------------- |
|
||||
| `namespace` | string | **REQUIRED** | The namespace where the item should be |
|
||||
| | | | should be removed. |^
|
||||
| `key` | string \| [string] | **REQUIRED** | The key indicating the field or fields |
|
||||
| | | | where the item should be removed. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"namespace": "test",
|
||||
"key": "settings.some_count",
|
||||
"value": 9001
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------- | :----------------: | ------------------------------------------ |
|
||||
| `namespace` | string | The namespace containing the item removed. |
|
||||
| `key` | string \| [string] | The key indicating the field or fields |
|
||||
| | | where the item was removed. |^
|
||||
| `value` | any | The of the item at the removed field. May |
|
||||
| | | be any valid JSON type. |^
|
||||
|
||||
///
|
||||
|
||||
## Compact Database
|
||||
|
||||
Compacts and defragments the the sqlite database using the `VACUUM` command.
|
||||
This endpoint cannot be requested when Klipper is printing.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/database/compact
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.compact",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"previous_size": 139264,
|
||||
"new_size": 122880
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------- | :--: | -------------------------------------------------- |
|
||||
| `previous_size` | int | Size in bytes of the database prior to compaction. |
|
||||
| `new_size` | int | Size in bytes of the database after compaction. |
|
||||
|
||||
///
|
||||
|
||||
## Backup Database
|
||||
|
||||
Creates a backup of the current database. The backup will be
|
||||
created in the `<data_path>/backup/database/<filename>`.
|
||||
|
||||
This API cannot be requested when Klipper is printing.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/database/backup
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "sql-db-backup.db"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.post_backup",
|
||||
"params": {
|
||||
"filename": "sql-db-backup.db"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | -------------------------- | -------------------------- |
|
||||
| `filename` | string | sqldb-backup-{timespec}.db | The file name of the saved |
|
||||
| | | | backup file. |^
|
||||
|
||||
//// note
|
||||
The `{timespec}` of the default `filename` is in the following format:
|
||||
|
||||
`<year><month><day>-<hour><minute><second>`
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"backup_path": "/home/test/printer_data/backup/database/sql-db-backup.db"
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | :----: | ------------------------------------------------------ |
|
||||
| `backup_path` | string | The complete absolute path where the backup was saved. |
|
||||
|
||||
///
|
||||
|
||||
## Delete a backup
|
||||
|
||||
Deletes a previously backed up database.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/database/backup?filename=sql-db-backup.db
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.delete_backup",
|
||||
"params": {
|
||||
"filename": "sql-db-backup.db"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | ------------ | ---------------------------------------------- |
|
||||
| `filename` | string | **REQUIRED** | The name of the backup file to delete. Must be |
|
||||
| | | | a valid filename reported by the |^
|
||||
| | | | [database list endpoint](#list-database-info). |^
|
||||
|
||||
///
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"backup_path": "/home/test/printer_data/backup/database/sql-db-backup.db"
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | :----: | -------------------------------------------------------- |
|
||||
| `backup_path` | string | The complete absolute path where the backup was removed. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
## Restore Database
|
||||
|
||||
Restores a previously backed up sqlite database file. The backup
|
||||
must be located at `<data_path>/backup/database/<filename>`. The
|
||||
`<filename>` must be a valid filename reported in by the
|
||||
[database list](#list-database-info) API.
|
||||
|
||||
This API cannot be requested when Klipper is printing.
|
||||
|
||||
/// Note
|
||||
Moonraker will restart immediately after this request is processed.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/database/restore
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filename": "sql-db-backup.db"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.database.restore",
|
||||
"params": {
|
||||
"filename": "sql-db-backup.db"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | ------------ | ----------------------------------------------- |
|
||||
| `filename` | string | **REQUIRED** | The name of the backup file to restore. Must be |
|
||||
| | | | a valid filename reported by the |^
|
||||
| | | | [database list endpoint](#list-database-info). |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"restored_tables": [
|
||||
"table_registry",
|
||||
"namespace_store",
|
||||
"authorized_users",
|
||||
"job_history",
|
||||
"job_totals"
|
||||
],
|
||||
"restored_namespaces": [
|
||||
"database",
|
||||
"fluidd",
|
||||
"gcode_metadata",
|
||||
"mainsail",
|
||||
"moonraker",
|
||||
"update_manager",
|
||||
"webcams"
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | :------: | ------------------------------------------- |
|
||||
| `restored_tables` | [string] | An array of table names that were recovered |
|
||||
| | | after the restore operation. |^
|
||||
| `restored_namespaces` | [string] | An array of namespaces that were recovered |
|
||||
| | | after the restore operation. |^
|
||||
|
||||
///
|
||||
|
||||
## Debug endpoints
|
||||
|
||||
Below are a number of debug endpoints available when Moonraker has been
|
||||
launched with [debug features enabled](../installation.md#command-line-usage).
|
||||
Front ends should not rely on these endpoints in production releases, however
|
||||
they may be useful during development. Developers writing extensions and/or
|
||||
additions to Moonraker may also find these endpoints useful.
|
||||
|
||||
/// Warning
|
||||
Debug endpoints may expose security vulnerabilities. They should only be
|
||||
enabled by developers on secured machines.
|
||||
///
|
||||
|
||||
### List Database Info (debug)
|
||||
|
||||
Debug version of the [List Database Info](#list-database-info) endpoint.
|
||||
Returns all namespaces, including those exclusively reserved for Moonraker.
|
||||
In addition all registered SQL tables are reported.
|
||||
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /debug/database/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "debug.database.list",
|
||||
"id": 8694
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"namespaces": [
|
||||
"gcode_metadata",
|
||||
"webcams",
|
||||
"update_manager",
|
||||
"announcements",
|
||||
"database",
|
||||
"moonraker"
|
||||
],
|
||||
"backups": [
|
||||
"sqldb-backup-20240513-134542.db",
|
||||
"testbackup.db",
|
||||
"testbackup2.db"
|
||||
],
|
||||
"tables": [
|
||||
"job_history",
|
||||
"job_totals",
|
||||
"namespace_store",
|
||||
"table_registry",
|
||||
"authorized_users"
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | :------: | -------------------------------------------------------- |
|
||||
| `namespaces` | [string] | An array of all namespaces registered with the database. |
|
||||
| `backups` | [string] | An array of database backup filenames that have been |
|
||||
| | | created. |^
|
||||
| `tables` | [string] | An array of tables created within the database. |
|
||||
|
||||
///
|
||||
|
||||
### Get Database Item (debug)
|
||||
|
||||
Debug version of the [Get Database Item](#get-database-item) endpoint.
|
||||
Keys within protected and forbidden namespaces may be read.
|
||||
|
||||
```http title="HTTP Request"
|
||||
GET /debug/database/item?namespace={namespace}&key={key}
|
||||
```
|
||||
```json title="JSON-RPC Request"
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "debug.database.get_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}"
|
||||
},
|
||||
"id": 5644
|
||||
}
|
||||
```
|
||||
|
||||
See the [Get Database Item](#get-database-item) endpoint for the
|
||||
`Parameter Specification`, `Example Response`, and `Response Specification`.
|
||||
|
||||
### Add Database Item (debug)
|
||||
|
||||
Debug version of the [Add Database Item](#add-database-item) endpoint.
|
||||
Keys within protected and forbidden namespaces may be inserted.
|
||||
|
||||
/// Warning
|
||||
Modifying protected namespaces outside of Moonraker can result in
|
||||
broken functionality and is not supported for production environments.
|
||||
Issues opened with reports/queries related to this endpoint will be
|
||||
redirected to this documentation and closed.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /debug/database/item
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"namespace": "my_client",
|
||||
"key": "settings.some_count",
|
||||
"value": 100
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "debug.database.post_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}",
|
||||
"value": 100
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
See the [Add Database Item](#add-database-item) endpoint for the
|
||||
`Parameter Specification`, `Example Response`, and `Response Specification`.
|
||||
|
||||
### Delete Database Item (debug)
|
||||
|
||||
Debug version of [Delete Database Item](#delete-database-item). Keys within
|
||||
protected and forbidden namespaces may be removed.
|
||||
|
||||
/// Warning
|
||||
Modifying protected namespaces outside of Moonraker can result in
|
||||
broken functionality and is not supported for production environments.
|
||||
Issues opened with reports/queries related to this endpoint will be
|
||||
redirected to this documentation and closed.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /debug/database/item?namespace={namespace}&key={key}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "debug.database.delete_item",
|
||||
"params": {
|
||||
"namespace": "{namespace}",
|
||||
"key": "{key}"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
See the [Delete Database Item](#delete-database-item) endpoint for the
|
||||
`Parameter Specification`, `Example Response`, and `Response Specification`.
|
||||
|
||||
|
||||
### Get Database Table
|
||||
|
||||
Requests all the contents of a specified table.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /debug/database/table?table=job_history
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "debug.database.table",
|
||||
"params": {
|
||||
"table": "job_history"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------- | :----: | ------------ | --------------------------------- |
|
||||
| `table` | string | **REQUIRED** | The name of the table to request. |
|
||||
|
||||
///
|
||||
|
||||
|
||||
|
||||
Returns:
|
||||
|
||||
An object with the table's name and a list of all rows contained
|
||||
within the table. The `rowid` will always be included for each
|
||||
row, however it may be represented by an alias. In the example
|
||||
below the alias for `rowid` is `job_id`.
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"table_name": "job_history",
|
||||
"rows": [
|
||||
{
|
||||
"job_id": 1,
|
||||
"user": "No User",
|
||||
"filename": "active_test.gcode",
|
||||
"status": "completed",
|
||||
"start_time": 1690749153.2661753,
|
||||
"end_time": 1690749173.076986,
|
||||
"print_duration": 0.0,
|
||||
"total_duration": 19.975574419135228,
|
||||
"filament_used": 0.0,
|
||||
"metadata": {
|
||||
"size": 211,
|
||||
"modified": 1635771217.0,
|
||||
"uuid": "627371e0-faa5-4ced-8bb4-7017d29226fa",
|
||||
"slicer": "Unknown",
|
||||
"gcode_start_byte": 8,
|
||||
"gcode_end_byte": 211
|
||||
},
|
||||
"auxiliary_data": [],
|
||||
"instance_id": "default"
|
||||
},
|
||||
{
|
||||
"job_id": 2,
|
||||
"user": "No User",
|
||||
"filename": "active_test.gcode",
|
||||
"status": "completed",
|
||||
"start_time": 1701262034.9242446,
|
||||
"end_time": 1701262054.7332363,
|
||||
"print_duration": 0.0,
|
||||
"total_duration": 19.990913168992847,
|
||||
"filament_used": 0.0,
|
||||
"metadata": {
|
||||
"size": 211,
|
||||
"modified": 1635771217.0,
|
||||
"uuid": "627371e0-faa5-4ced-8bb4-7017d29226fa",
|
||||
"slicer": "Unknown",
|
||||
"gcode_start_byte": 8,
|
||||
"gcode_end_byte": 211
|
||||
},
|
||||
"auxiliary_data": {
|
||||
"spool_ids": [
|
||||
2
|
||||
]
|
||||
},
|
||||
"instance_id": "default"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | :------: | -------------------------------------------------- |
|
||||
| `table_name` | string | The name of the table requested. |
|
||||
| `rows` | [object] | An array of row objects. The fields for each |
|
||||
| | | object are columns defined by the table schema. |^
|
||||
| | | The `rowid` will always be included for each row, |^
|
||||
| | | however it may be represented by an alias. In the |^
|
||||
| | | example above, `job_id` is an alias for `rowid`. |^
|
||||
|
||||
///
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,277 @@
|
||||
# Extensions
|
||||
|
||||
Moonraker has limited support for 3rd party extensions through the
|
||||
use of its API. Extensions must establish a Websocket or Unix Socket
|
||||
connection and [identify](./server.md#identify-connection) themselves
|
||||
as an `agent`.
|
||||
|
||||
The endpoints in this section can be broken down into two categories:
|
||||
|
||||
- Endpoints used by Front Ends and other clients to manage and manipulate
|
||||
extensions.
|
||||
- Endpoints specific to agents that provide functional enhancements not
|
||||
available to other client types.
|
||||
|
||||
## Extension Management
|
||||
|
||||
### List Extensions
|
||||
|
||||
Returns a list of all available extensions. Currently Moonraker can only
|
||||
be officially extended through connected `agents`.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/extensions/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.extensions.list",
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"name": "moonagent",
|
||||
"version": "0.0.1",
|
||||
"type": "agent",
|
||||
"url": "https://github.com/arksine/moontest"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :------: | --------------------------------------------------- |
|
||||
| `agents` | [object] | An array of [Agent Info](#agent-info-spec) objects. |
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :----: | -------------------------------------------------- |
|
||||
| `name` | string | The name provided by the registered agent. |
|
||||
| `version` | string | The version of the software reported by the agent. |
|
||||
| `type` | string | The client type. Will always be `agent`. |
|
||||
| `url` | string | A url to the agent software's webpage. |
|
||||
{ #agent-info-spec } Agent Info
|
||||
|
||||
///
|
||||
|
||||
### Call an extension method
|
||||
|
||||
This endpoint may be used to call a method on a connected agent.
|
||||
The request effectively relays a JSON-RPC request from a front end
|
||||
or other client to the agent. Agents should document their
|
||||
available methods so Moonraker client developers can interact
|
||||
with them.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/extensions/request
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"agent": "moonagent",
|
||||
"method": "moontest.hello_world",
|
||||
"arguments": {"argone": true, "argtwo": 9000}
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.extensions.request",
|
||||
"params":{
|
||||
"agent": "moonagent",
|
||||
"method": "moontest.hello_world",
|
||||
"arguments": {"argone": true, "argtwo": 9000}
|
||||
},
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
Parameters:
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :-------------: | ------------ | -------------------------------- |
|
||||
| `agent` | string | **REQUIRED** | The name of the registered agent |
|
||||
| | | | hosting the requested method. |^
|
||||
| `method` | string | **REQUIRED** | The name of the method to call. |
|
||||
| `arguments` | array \| object | null | The arguments to send with the |
|
||||
| | | | method. This may be an array |^
|
||||
| | | | containing positional arguments |^
|
||||
| | | | or an object containing keyword |^
|
||||
| | | | arguments. A value of `null` |^
|
||||
| | | | will omit arguments from the |^
|
||||
| | | | request. |^
|
||||
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
The result received from the agent will be returned directly. See
|
||||
the agent's documentation for response specifications
|
||||
|
||||
///
|
||||
|
||||
## Agent specific endpoints
|
||||
|
||||
/// Note
|
||||
These endpoints are only available to connections that have
|
||||
identified themselves as an `agent` type.
|
||||
///
|
||||
|
||||
### Send an agent event
|
||||
|
||||
Sends a [JSON-RPC notification](./jsonrpc_notifications.md#agent-events)
|
||||
containing the supplied event info to all of Moonraker's persistent
|
||||
connections.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
Not Available
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "connection.send_event",
|
||||
"params":{
|
||||
"event": "my_event",
|
||||
"data": {"my_arg": "optional data"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------- | :----: | ------------ | -------------------------------------------- |
|
||||
| `event` | string | **REQUIRED** | The name of the event. This may be any |
|
||||
| | | | name other than those reserved by Moonraker. |^
|
||||
| `data` | any | undefined | The data to send with the event. This can be |
|
||||
| | | | any valid JSON decodable value. If omitted |^
|
||||
| | | | no data is sent with the event. |^
|
||||
|
||||
//// Note
|
||||
The `connected` and `disconnected` events are reserved for use
|
||||
by Moonraker and may not be sent from agents.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
```{.apiresponse title="Response when JSON-RPC 'id' present"}
|
||||
ok
|
||||
```
|
||||
|
||||
/// note
|
||||
An agent may send an event without specifying the JSON-RPC `id` field.
|
||||
In this case Moonraker will not return a response.
|
||||
///
|
||||
|
||||
|
||||
### Register a method with Klipper
|
||||
|
||||
Registers a "remote method" with Klipper that can be called
|
||||
from GCode Macros.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
Not Available
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "connection.register_remote_method",
|
||||
"params": {
|
||||
"method_name": "firemon_alert_heated"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------------- | :----: | ------------ | --------------------------------------------- |
|
||||
| `method_name` | string | **REQUIRED** | The name of the remote method to register |
|
||||
| | | | with Klipper. It is recommended for agents |^
|
||||
| | | | to use a unique identifier, such as a prefix, |^
|
||||
| | | | to prevent collisions with other remote |^
|
||||
| | | | methods registered with Klipper. |^
|
||||
|
||||
///
|
||||
|
||||
```{.apiresponse title= Response"}
|
||||
ok
|
||||
```
|
||||
|
||||
/// Note
|
||||
Methods registered by agents will persist until the agent disconnects.
|
||||
Upon connection it is only necessary that they register their desired
|
||||
methods once.
|
||||
///
|
||||
|
||||
#### Remote Method Example
|
||||
|
||||
Presume an application named `firemon` has connected to Moonraker's websocket
|
||||
and identified itself as an `agent`. After identification it registers a
|
||||
remote method named `firemon_alert_heated` using the JSON-RPC request
|
||||
example above.
|
||||
|
||||
In addition, the user has following `gcode_macro` configured in `printer.cfg`:
|
||||
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro ALERT_HEATED]
|
||||
gcode:
|
||||
{% if not params %}
|
||||
{action_call_remote_method("firemon_alert_heated")}
|
||||
{% else %}
|
||||
{% set htr = params.HEATER|default("unknown") %}
|
||||
{% set tmp = params.TEMP|default(0)|float %}
|
||||
{action_call_remote_method(
|
||||
"firemon_alert_heated", heater=htr, temp=tmp)}
|
||||
{% endif %}
|
||||
|
||||
|
||||
```
|
||||
|
||||
When the `ALERT_HEATED HEATER=extruder TEMP=200` gcode is executed by Klipper,
|
||||
the agent will receive the following JSON-RPC request from Moonraker:
|
||||
|
||||
```{.json .apiresponse title="Remote Method Call"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "firemon_alert_heated",
|
||||
"params": {
|
||||
"heater": "extruder",
|
||||
"temp": 200
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When the `ALERT_HEATED` gcode is executed with no parameters, the agent will
|
||||
receive the following JSON-RPC request from Moonraker:
|
||||
|
||||
```{.json .apiresponse title="Remote Method Call"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "monitor_alert_heated"
|
||||
}
|
||||
```
|
||||
|
||||
/// Note
|
||||
Remote methods called from Klipper never contain the JSON-RPC "id" field,
|
||||
as Klipper does not accept return values to remote methods.
|
||||
///
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,452 @@
|
||||
# Job History
|
||||
|
||||
Moonraker's `history` component tracks print job completion data.
|
||||
The following endpoints are available to manage Moonraker's job
|
||||
history data.
|
||||
|
||||
## Get job list
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/history/list?limit=50&start=50&since=1&before=5&order=asc
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.history.list",
|
||||
"params":{
|
||||
"limit": 50,
|
||||
"start": 10,
|
||||
"since": 464.54,
|
||||
"before": 1322.54,
|
||||
"order": "asc"
|
||||
},
|
||||
"id": 5656
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| -------- | :----: | --------- | ----------------------------------------------- |
|
||||
| `limit` | int | 50 | Maximum number of job entries to return. |
|
||||
| `start` | int | 0 | The record number indicating the first entry |
|
||||
| | | | of the returned list. |^
|
||||
| `before` | float | undefined | A timestamp in unix time. When specified, the |
|
||||
| | | | returned list will only contain entries created |^
|
||||
| | | | before this date. |^
|
||||
| `since` | float | undefined | A timestamp in unix time. When specified, the |
|
||||
| | | | returned list will only contain entries created |^
|
||||
| | | | after this date. |^
|
||||
| `order` | string | "desc" | The order of the list returned. May be `asc` |
|
||||
| | | | (ascending) or `desc` (descending). |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"count": 1,
|
||||
"jobs": [
|
||||
{
|
||||
"job_id": "000001",
|
||||
"exists": true,
|
||||
"end_time": 1615764265.6493807,
|
||||
"filament_used": 7.83,
|
||||
"filename": "test/history_test.gcode",
|
||||
"metadata": {
|
||||
// Object containing metadata at time of job
|
||||
},
|
||||
"print_duration": 18.37201827496756,
|
||||
"status": "completed",
|
||||
"start_time": 1615764496.622146,
|
||||
"total_duration": 18.37201827496756,
|
||||
"user": "testuser",
|
||||
"auxiliary_data": [
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "power_consumption",
|
||||
"value": 4.119977,
|
||||
"description": "Printer Power Consumption",
|
||||
"units": "kWh"
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "max_current",
|
||||
"value": 2.768851,
|
||||
"description": "Maximum current draw",
|
||||
"units": "A"
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "min_current",
|
||||
"value": 0.426725,
|
||||
"description": "Minimum current draw",
|
||||
"units": "A"
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "avg_current",
|
||||
"value": 1.706872,
|
||||
"description": "Average current draw",
|
||||
"units": "A"
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "status",
|
||||
"value": 2,
|
||||
"description": "Power Switch Status",
|
||||
"units": null
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"name": "filament",
|
||||
"value": 19.08058495194607,
|
||||
"description": "filament usage tracker",
|
||||
"units": "mm"
|
||||
},
|
||||
{
|
||||
"provider": "spoolman",
|
||||
"name": "spool_ids",
|
||||
"value": [
|
||||
1
|
||||
],
|
||||
"description": "Spool IDs used",
|
||||
"units": null
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------- | :------: | -------------------------------------------------- |
|
||||
| `count` | int | The number of entries returned by the query. |
|
||||
| `jobs` | [object] | An array of [Job History](#job-history-entry-spec) |
|
||||
| | | objects. |^
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------------- | :------------: | ----------------------------------------------------------- |
|
||||
| `job_id` | string | A unique ID for the entry. |
|
||||
| `user` | string \| null | The user that started the job. Will be `null` |
|
||||
| | | if Moonraker cannot identify a user (ie: job) |^
|
||||
| | | was started via Klipper's display. |^
|
||||
| `filename` | string | The path, relative to `gcodes` root, of the file |
|
||||
| | | associated with the job. |^
|
||||
| `exists` | bool | A value of `true` indicates that the file |
|
||||
| | | associated with the job exists on disk and has |^
|
||||
| | | not been modified. |^
|
||||
| `status` | string | The [job status](#job-history-status-desc) |
|
||||
| | | at the time of query. |^
|
||||
| `start_time` | float | A timestamp, in unix time, indicating when |
|
||||
| | | the job started. |^
|
||||
| `end_time` | float \| null | A timestamp, in unix time, indicating when |
|
||||
| | | the job finished. Will be `null` if the |^
|
||||
| | | job is in progress or if Moonraker is |^
|
||||
| | | interrupted prior to the job completion. |^
|
||||
| `print_duration` | float | The amount of time, in seconds, the job |
|
||||
| | | spent printing (ie: printer not idle). |^
|
||||
| `total_duration` | float | The total amount of time, in seconds, the |
|
||||
| | | job took to print. This includes time paused. |^
|
||||
| `filament_used` | float | The amount of filament (in mm) used during the job. |
|
||||
| `metadata` | object | The [gcode metadata](./file_manager.md#gcode-metadata-spec) |
|
||||
| | | object associated with the job. The `job_id` and |^
|
||||
| | | `print_start_time` fields are removed from the metadata as |^
|
||||
| | | they are redundant. |^
|
||||
| `auxiliary_data` | [object] | An array of [auxiliary field](#job-history-aux-field-spec) |
|
||||
| | | objects containing supplemental history data related to |^
|
||||
| | | the job. |^
|
||||
{ #job-history-entry-spec } Job History
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | :------------: | ------------------------------------------------- |
|
||||
| `provider` | string | The component or extension that generated the |
|
||||
| | | auxiliary field. |^
|
||||
| `name` | string | A name identifying the field. |
|
||||
| `description` | string | A brief description of the data in this entry. |
|
||||
| `value` | any | The value associated with the field. Can be any |
|
||||
| | | valid JSON type. |^
|
||||
| `units` | string \| null | The unit type associated with the value. For |
|
||||
| | | example this would be `mm` for millimeters. Can |^
|
||||
| | | be `null` if no unit abbreviation is appropriate. |^
|
||||
{ #job-history-aux-field-spec } Auxiliary Field
|
||||
|
||||
| Status | Description |
|
||||
| ------------------- | ----------------------------------------------------- |
|
||||
| `in_progress` | The job is currently active. |
|
||||
| `completed` | The job successfully completed. |
|
||||
| `cancelled` | The job was cancelled by the user. |
|
||||
| `error` | The job was aborted due to an error during execution. |
|
||||
| `klippy_shutdown` | The job was aborted due to Klippy Shutdown. |
|
||||
| `klippy_disconnect` | Moonraker's connection to Klippy was lost while the |
|
||||
| | job was in progress. |^
|
||||
| `interrupted` | Moonraker was abruptly terminated while the job was |
|
||||
| | in progress. |^
|
||||
{ #job-history-status-desc } Job Status
|
||||
|
||||
///
|
||||
## Get job totals
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/history/totals
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.history.totals",
|
||||
"id": 5656
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"job_totals": {
|
||||
"total_jobs": 3,
|
||||
"total_time": 11748.077333278954,
|
||||
"total_print_time": 11348.794790096988,
|
||||
"total_filament_used": 11615.718840001999,
|
||||
"longest_job": 11665.191012736992,
|
||||
"longest_print": 11348.794790096988
|
||||
},
|
||||
"auxiliary_totals": [
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "power_consumption",
|
||||
"maximum": 4.119977,
|
||||
"total": 4.119977
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "avg_current",
|
||||
"maximum": 1.706872,
|
||||
"total": null
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "filament",
|
||||
"maximum": 19.08058495194607,
|
||||
"total": 19.08058495194607
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------ | :------: | ----------------------------------------------- |
|
||||
| `job_totals` | object | A [Job Totals](#job-history-totals-spec) object |
|
||||
| | | reporting all current totals. |^
|
||||
| `auxiliary_totals` | [object] | An array of |
|
||||
| | | [Auxiliary Total](#job-auxiliary-totals-spec) |^
|
||||
| | | objects. |^
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | :------: | ------------------------------------------------------ |
|
||||
| `total_jobs` | int | The total number of jobs tracked. |
|
||||
| `total_time` | float | The total amount of job work time (in seconds) |
|
||||
| | | across all jobs, including time paused. |^
|
||||
| `total_print_time` | float | The total amount of time printing (in seconds) |
|
||||
| | | across all jobs. |^
|
||||
| `total_filament_used` | float | The total amount of filament used (in mm) across |
|
||||
| | | all jobs. |^
|
||||
| `longest_job` | float | The maximum time spent working on a single job, |
|
||||
| | | including time paused. |^
|
||||
| `longest_print` | float | The maximum time spent printing a single job. |
|
||||
| `auxiliary_totals` | [object] | An array of |
|
||||
| | | [Auxiliary Total](#job-auxiliary-totals-spec) objects. |^
|
||||
{ #job-history-totals-spec } Job Totals
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :-----------: | ----------------------------------------------- |
|
||||
| `provider` | string | The component or extension that generated the |
|
||||
| | | auxiliary totals. |^
|
||||
| `field` | string | The corresponding `name` of the auxiliary field |
|
||||
| | | used to generate totals. |^
|
||||
| `maximum` | float \| null | The maximum value observed across all prints. |
|
||||
| | | Will be `null` if the maximum is not available. |^
|
||||
| `total` | float \| null | The accumulated total value across all prints. |
|
||||
| | | Will be `null` if the total is not available. |^
|
||||
{ #job-auxiliary-totals-spec } Auxiliary Total
|
||||
|
||||
///
|
||||
|
||||
## Reset totals
|
||||
Resets the persistent "job totals" to zero.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/history/reset_totals
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.history.reset_totals",
|
||||
"id": 5534
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"last_totals": {
|
||||
"total_jobs": 3,
|
||||
"total_time": 11748.077333278954,
|
||||
"total_print_time": 11348.794790096988,
|
||||
"total_filament_used": 11615.718840001999,
|
||||
"longest_job": 11665.191012736992,
|
||||
"longest_print": 11348.794790096988
|
||||
},
|
||||
"last_auxiliary_totals": [
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "power_consumption",
|
||||
"maximum": 4.119977,
|
||||
"total": 4.119977
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "avg_current",
|
||||
"maximum": 1.706872,
|
||||
"total": null
|
||||
},
|
||||
{
|
||||
"provider": "sensor hist_test",
|
||||
"field": "filament",
|
||||
"maximum": 19.08058495194607,
|
||||
"total": 19.08058495194607
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------------------- | :------: | ----------------------------------------------- |
|
||||
| `last_totals` | object | A [Job Totals](#job-history-totals-spec) object |
|
||||
| | | reporting all totals prior to the reset. |^
|
||||
| `last_auxiliary_totals` | [object] | An array of |
|
||||
| | | [Auxiliary Total](#job-auxiliary-totals-spec) |^
|
||||
| | | objects reporting totals prior to the reset. |^
|
||||
|
||||
///
|
||||
|
||||
## Get a single job
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/history/job?uid=<id>
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.history.get_job",
|
||||
"params":{"uid": "{uid}"},
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----- | :----: | ------------ | --------------------------------------- |
|
||||
| `uid` | string | **REQUIRED** | The unique identifier for the requested |
|
||||
| | | | job history. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"job": {
|
||||
"job_id": "000001",
|
||||
"exists": true,
|
||||
"end_time": 1615764265.6493807,
|
||||
"filament_used": 7.83,
|
||||
"filename": "test/history_test.gcode",
|
||||
"metadata": {
|
||||
// Object containing metadata at time of job
|
||||
},
|
||||
"print_duration": 18.37201827496756,
|
||||
"status": "completed",
|
||||
"start_time": 1615764496.622146,
|
||||
"total_duration": 18.37201827496756
|
||||
}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----- | :----: | ------------------------------------------------------------- |
|
||||
| `job` | object | The requested [Job History](#job-history-entry-spec ) object. |
|
||||
|
||||
///
|
||||
|
||||
## Delete a job
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/history/job?uid=<id>
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.history.delete_job",
|
||||
"params":{
|
||||
"uid": "{uid}"
|
||||
},
|
||||
"id": 5534
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----- | :----: | --------------- | ------------------------------------------ |
|
||||
| `uid` | string | **REQUIRED** | The unique identifier for the job entry |
|
||||
| | | if `all==false` | to delete. |^
|
||||
| `all` | bool | false | When set to `true` all job history entries |
|
||||
| | | | will be removed. |^
|
||||
|
||||
//// tip
|
||||
If `all = true` is specified the `uid` parameter should be omitted.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"deleted_jobs": [
|
||||
"000000",
|
||||
"000001"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------------- | :------: | ------------------------------------- |
|
||||
| `deleted_jobs` | [string] | An array of unique IDs indicating the |
|
||||
| | | job entries that were deleted. |^
|
||||
|
||||
///
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,510 @@
|
||||
# Introduction
|
||||
|
||||
Moonraker provides APIs over two protocols, HTTP and JSON-RPC. Most
|
||||
endpoints have corresponding APIs over both protocols. When requests
|
||||
are exclusive to a protocol or depend on some other condition it will
|
||||
be noted in the documentation for that specific API.
|
||||
|
||||
At a high level, file transfer requests (upload and download) are exclusive
|
||||
to the HTTP API. The Websocket is required to receive events such as status
|
||||
updates and gcode responses. For information on how to set up the Websocket,
|
||||
please see the [Miscellaneous Tutorials](#websocket-setup).
|
||||
|
||||
## HTTP API Overview
|
||||
|
||||
Moonraker's HTTP API could be described as "REST-ish". Attempts are made to
|
||||
conform to REST standards, however the dynamic nature of Moonraker's endpoint
|
||||
registration along with the need to keep consistency between two API protocols
|
||||
results in an HTTP API that deviates
|
||||
|
||||
Moonraker is capable of parsing request arguments from the both the body
|
||||
(either JSON or form-data depending on the `Content-Type` header) and from
|
||||
the query string. All arguments are grouped together in one data structure,
|
||||
with body arguments taking precedence over query arguments. Thus
|
||||
if the same argument is supplied both in the body and in the
|
||||
query string the body argument would be used. It is left up to the front end
|
||||
developer to decide exactly how they want to provide arguments.
|
||||
|
||||
Nearly all successful HTTP requests will return a json encoded object in
|
||||
the form of:
|
||||
|
||||
```text
|
||||
{
|
||||
"result": <response data>
|
||||
}
|
||||
```
|
||||
|
||||
The response data may be any valid JSON type. In most cases it will be
|
||||
a JSON object itself, but some requests may return a simple string.
|
||||
|
||||
If the response is not wrapped in an object with a `result` field it will
|
||||
be noted in the documentation for that API (or API set). Generally this
|
||||
only applies to endpoints that attempt to emulate other backends.
|
||||
|
||||
Should a request result in an error, a standard error code along with
|
||||
an error specific message is returned, wrapped in a JSON object.
|
||||
|
||||
### Query string type hints
|
||||
|
||||
By default all arguments passed via the query string are represented as
|
||||
strings. Most endpoint handlers know the data type for each of their
|
||||
arguments, thus they can perform conversion from a string type if necessary.
|
||||
However some endpoints accept arguments of a "generic" type, thus the
|
||||
client is responsible for specifying the type if "string" is not desirable.
|
||||
This is not a problem for websocket requests as the JSON parser can extract
|
||||
the appropriate type. HTTP requests must provide "type hints" in these
|
||||
scenarios. Moonraker supplies support for the following query string type hints:
|
||||
- int
|
||||
- bool
|
||||
- float
|
||||
- json
|
||||
The `json` type hint can be specified to pass an array or an object via
|
||||
the query string. Remember to percent encode the json string so that
|
||||
the query string is correctly parsed.
|
||||
|
||||
Type hints may be specified by post-fixing them to a key, with a ":"
|
||||
separating the key and the hint. For example, lets assume that we
|
||||
have a request that takes `seconds` (integer) and `enabled` (boolean)
|
||||
arguments. The query string with type hints might look like:
|
||||
```
|
||||
?seconds:int=120&enabled:bool=true
|
||||
```
|
||||
A query string that takes a `value` argument with which we want to
|
||||
pass an object, `{foo: 21.5, bar: "hello"}` might look like:
|
||||
```
|
||||
?value:json=%7B%22foo%22%3A21.5%2C%22bar%22%3A%22hello%22%7D
|
||||
```
|
||||
As you can see, a percent encoded json string is not human readable,
|
||||
thus using this functionality should be seen as a "last resort." If at
|
||||
all possible clients should attempt to put these arguments in the body
|
||||
of a request.
|
||||
|
||||
## JSON-RPC API Overview
|
||||
|
||||
Websocket, Unix Socket, and MQTT connections exclusively use the API
|
||||
available over [JSON-RPC 2.0](https://jsonrpc.org). In addition, Moonraker
|
||||
provides an [JSON-RPC HTTP endpoint](#json-rpc-over-http-endpoint) giving
|
||||
developers who want to avoid persistent connections a choice to use JSON-RPC.
|
||||
|
||||
The Websocket transmits and receives JSON-RPC objects in text frames. MQTT
|
||||
transmits them in the payload of a topic defined when MQTT is configured. By
|
||||
default, Moonraker receives JSON-RPC requests from the
|
||||
`{instance_name}/moonraker/api/request` topic, and publishes responses to the
|
||||
`{instance_name}/moonraker/api/response` topic. The `{instance_name}` must be
|
||||
a unique identifier for each instance of Moonraker connected to the broker.
|
||||
It defaults to the machine's host name.
|
||||
|
||||
An encoded request should look something like:
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "API method",
|
||||
"params": {"arg_one": 1, "arg_two": true},
|
||||
"id": 354
|
||||
}
|
||||
```
|
||||
|
||||
The `params` field may be left out if the API request takes no arguments.
|
||||
The `id` should be a unique value that has no chance of colliding
|
||||
with other JSON-RPC requests. The `method` is the API method, as defined
|
||||
for each API in this document.
|
||||
|
||||
/// details | Optional MQTT timestamp
|
||||
type: tip
|
||||
MQTT requests may provide an optional `mqtt_timestamp` keyword
|
||||
argument in the `params` field of the JSON-RPC request. To avoid
|
||||
potential collisions from time drift it is recommended to specify
|
||||
the timestamp in microseconds since the Unix Epoch. If provided
|
||||
Moonraker will use the timestamp to discard duplicate requests.
|
||||
It is recommended to either provide a timestamp or publish API
|
||||
requests at a QoS level of 0 or 2.
|
||||
///
|
||||
|
||||
A successful request will return a response like the following:
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"result": {"res_data": "success"},
|
||||
"id": 354
|
||||
}
|
||||
```
|
||||
The `result` will generally contain an object, but as with the HTTP API in some
|
||||
cases it may simply return a string. The `id` field will return an id that
|
||||
matches the one provided by the request.
|
||||
|
||||
Requests that result in an error will receive a properly formatted
|
||||
JSON-RPC response:
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"error": {"code": 36000, "message": "Error Message"},
|
||||
"id": 354
|
||||
}
|
||||
```
|
||||
Some errors may not return a request ID, such as an improperly formatted request.
|
||||
|
||||
The [moontest](https://www.github.com/arksine/moontest) repo includes a basic
|
||||
test interface with example usage for most of the requests below. It also
|
||||
includes a basic JSON-RPC implementation that uses promises to return responses
|
||||
and errors (see json-rpc.js).
|
||||
|
||||
## Websocket Connections
|
||||
|
||||
### Primary websocket
|
||||
|
||||
The primary websocket supports Moonraker's JSON-RPC API. Most applications that
|
||||
desire a websocket connection will make use of the primary websocket.
|
||||
|
||||
The primary websocket is available at:
|
||||
```
|
||||
ws://host_or_ip:port/websocket`
|
||||
```
|
||||
|
||||
The primary websocket will remain connected until the application disconnects
|
||||
or Moonraker is shutdown.
|
||||
|
||||
### Bridge websocket
|
||||
|
||||
The "bridge" websocket provides a near direct passthrough to Klipper's API
|
||||
Server. Klipper uses its own RPC protocol, which is effectively a simplified
|
||||
version of the JSON-RPC specification. Developers should refer to
|
||||
[Klipper's API documentation](https://www.klipper3d.org/API_Server.html)
|
||||
for details on the protocol and available APIs.
|
||||
|
||||
!!! Note
|
||||
The bridge websocket is described as "near direct passthrough" because
|
||||
Moonraker handles the ETX (`0x03`) terminator internally. Applications
|
||||
can expect to receive complete JSON encoded messages in a text frame
|
||||
without the ETX terminator. Likewise applications should send JSON encoded
|
||||
messages without the ETX terminator. Messages may be sent using either
|
||||
text frames or binary frames.
|
||||
|
||||
The bridge websocket provides access to diagnostic APIs that are not generally
|
||||
suitable for Moonraker's primary connection. These requests stream a
|
||||
substantial amount of data; bridge connections allow Moonraker to avoid
|
||||
decoding and re-encoding this data, reducing CPU load on the host. The "dump"
|
||||
requests, such as `motion_report/dump_stepper` and `adxl345/dump_adxl345`, are
|
||||
examples of APIs that should make use of the bridge websocket.
|
||||
|
||||
The bridge websocket is available at:
|
||||
```
|
||||
ws://host_or_ip:port/klippysocket
|
||||
```
|
||||
|
||||
The availability of bridge connections depends on Klippy's availability.
|
||||
If Klippy is not running or its API server is not enabled then a bridge
|
||||
websocket connection cannot be established. Established bridge connections
|
||||
will close when Klippy is shutdown or restarted. Such connections will also
|
||||
be closed if Moonraker is restarted or shutdown.
|
||||
|
||||
!!! Note
|
||||
If JWT or API Key authentication is required the application must use a
|
||||
[oneshot token](./authorization.md#generate-a-oneshot-token) when connecting
|
||||
to a bridge socket. Since Moonraker does not decode bridge requests it is
|
||||
not possible to perform JWT authentication post connection.
|
||||
|
||||
## Unix Socket Connection
|
||||
|
||||
All JSON-RPC APIs available over the Websocket transport are also available
|
||||
over the Unix Domain Socket connection. Moonraker creates the socket file at
|
||||
`<datapath>/comms/moonraker.sock` (ie: `~/printer_data/comms/moonraker.sock`).
|
||||
The Unix Socket expects UTF-8 encoded JSON-RPC byte strings. Each JSON-RPC
|
||||
request must be terminated with an ETX character (`0x03`).
|
||||
|
||||
The Unix Socket is desirable for front ends and extensions running on the
|
||||
local machine as authentication is not necessary. There should be a small
|
||||
performance improvement due to the simplified transport protocol, however
|
||||
the impact of this is likely negligible.
|
||||
|
||||
The `moontest` repo contains a
|
||||
[python script](https://github.com/Arksine/moontest/blob/master/scripts/unix_socket_test.py)
|
||||
to test comms over the unix socket.
|
||||
|
||||
## JSON-RPC over HTTP Endpoint
|
||||
|
||||
Exposes the JSON-RPC interface over HTTP. Most JSON-RPC methods with
|
||||
corresponding HTTP APIs are available. Methods exclusive to other
|
||||
transports, such as [Identify Connection](./server.md#identify-connection), are
|
||||
not available.
|
||||
|
||||
/// note
|
||||
If authentication is required it must be part of the HTTP request,
|
||||
either using the API Key Header (`X-Api-Key`) or JWT Bearer Token.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/jsonrpc
|
||||
Content-Type: application/json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.info",
|
||||
"id": 5153
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5153,
|
||||
"result": {
|
||||
"state": "ready",
|
||||
"state_message": "Printer is ready",
|
||||
"hostname": "my-pi-hostname",
|
||||
"software_version": "v0.9.1-302-g900c7396",
|
||||
"cpu_info": "4 core ARMv7 Processor rev 4 (v7l)",
|
||||
"klipper_path": "/home/pi/klipper",
|
||||
"python_path": "/home/pi/klippy-env/bin/python",
|
||||
"log_file": "/tmp/klippy.log",
|
||||
"config_file": "/home/pi/printer.cfg"
|
||||
}
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// note
|
||||
If an error is encountered while processing a JSON-RPC request
|
||||
over HTTP the request itself will still return success. The
|
||||
error will be returned in the response as a JSON-RPC encoded
|
||||
object.
|
||||
///
|
||||
|
||||
## Jinja2 Template API Calls
|
||||
|
||||
Some template options in Moonraker's configuration, such as those in the
|
||||
[button](../configuration.md#button) component, may call Moonraker APIs through
|
||||
the `call_method(method_name, kwargs)` context function. The `call_method`
|
||||
function takes the API's JSON-RPC method name as its first parameter, followed
|
||||
by a set of keyword arguments as per the method's requirements.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
# Query Printer Objects example
|
||||
[button check_status]
|
||||
pin: gpio26
|
||||
on_press:
|
||||
{% set query = {"toolhead": ["position"], "print_stats": None} %}
|
||||
# JSON-RPC method is "printer.objects.query", which takes a single "objects"
|
||||
# argument
|
||||
{% set status = call_method("printer.objects.query", objects=query) %}
|
||||
# do something with the value returned from the object query, perhaps
|
||||
# send a websocket notification or publish a mqtt topic
|
||||
|
||||
# Publish button event to MQTT Topic
|
||||
[button check_status]
|
||||
pin: gpio26
|
||||
on_release:
|
||||
# JSON-RPC method is "server.mqtt.publish"
|
||||
{% do call_method("server.mqtt.publish",
|
||||
topic="moonraker/my-button",
|
||||
payload="Button Released") %}
|
||||
```
|
||||
|
||||
## Miscellaneous Tutorials
|
||||
|
||||
### Websocket setup
|
||||
|
||||
The websocket is located at `ws://host:port/websocket`, for example:
|
||||
```javascript
|
||||
var s = new WebSocket("ws://" + location.host + "/websocket");
|
||||
```
|
||||
|
||||
/// Note
|
||||
It may be necessary to authenticate the connection first. This
|
||||
tutorial assumes that the client is running on a trusted connection.
|
||||
///
|
||||
|
||||
The following is a basic startup sequence that may be used to establish
|
||||
a full connection to Moonraker and ensure that Klipper is running and
|
||||
available:
|
||||
|
||||
1. Attempt to connect to `/websocket` until successful using a timer-like
|
||||
mechanism.
|
||||
2. Once connected, query the [server info](./server.md#query-server-info)
|
||||
endpoint to check Klippy's state.
|
||||
- If the response returns an error then either the client
|
||||
is not authorized or Moonraker is not running. Direct the user to
|
||||
SSH into the machine and check `<data_folder/logs/moonraker.log`.
|
||||
- If the response returns success, check the result's `klippy_state`
|
||||
field:
|
||||
- `klippy_state == "ready"`: you may proceed to request status of
|
||||
printer objects make subscriptions, get the file list, etc.
|
||||
- `klippy_state == "error"`: Klippy has experienced an error
|
||||
starting up
|
||||
- `klippy_state == "shutdown"`: Klippy is in a shutdown state.
|
||||
- `klippy_state == "startup"`: re-request the `server info` endpoint in 2 seconds.
|
||||
- `klippy_state == "disconnected"`: The Klippy host either isn't running,
|
||||
has experienced a critical error during startup, or does not have its
|
||||
API Server enabled.
|
||||
3. Repeat step 2 until Klipper reports ready.
|
||||
4. Clients should watch for the `notify_klippy_disconnected` event. If
|
||||
received then Klippy has either been stopped or restarted. In this
|
||||
state the client should repeat the steps above to determine when
|
||||
klippy is ready.
|
||||
|
||||
/// note
|
||||
If Klippy reports an `error` or `shutdown` state it is advisable prompt
|
||||
the user. You can get a description from the `state_message`
|
||||
field of a [printer info](./printer.md#get-klippy-host-information) request.
|
||||
///
|
||||
|
||||
### Basic Print Status
|
||||
|
||||
An advanced client will likely use subscriptions and notifications
|
||||
to interact with Moonraker, however simple clients such as home automation
|
||||
software and embedded devices (ie: ESP32) may only wish to monitor the
|
||||
status of a print. Below is a high level walkthrough for receiving print state
|
||||
via polling.
|
||||
|
||||
- Set up a timer to poll at the desired interval. Depending on your use
|
||||
case, 1 to 2 seconds is recommended.
|
||||
- On each cycle, issue the following request:
|
||||
```
|
||||
GET http://host/printer/objects/query?webhooks&virtual_sdcard&print_stats
|
||||
```
|
||||
Or via JSON-RPC 2.0:
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.objects.query",
|
||||
"params": {
|
||||
"objects": {
|
||||
"webhooks": null,
|
||||
"virtual_sdcard": null,
|
||||
"print_stats": null
|
||||
}
|
||||
},
|
||||
"id": 5664
|
||||
}
|
||||
```
|
||||
|
||||
- If the request returns an error or the returned `result.status` is an empty
|
||||
object, then this is an indication that Klippy either experienced an error or
|
||||
it is not properly configured. Each queried object should be available in
|
||||
`result.status`. The client should check to make sure that all objects are
|
||||
received before proceeding.
|
||||
- Inspect `webhooks.state`. If the value is not `ready` the printer
|
||||
is not available. `webhooks.message` contains a message pertaining
|
||||
to the current state.
|
||||
- If the printer is ready, inspect `print_stats.state`. It may be one
|
||||
of the following values:
|
||||
- `standby`: No print in progress
|
||||
- `printing`: The printer is currently printing
|
||||
- `paused`: A print in progress has been paused
|
||||
- `error`: The print exited with an error. `print_stats.message`
|
||||
contains a related error message
|
||||
- `complete`: The last print has completed
|
||||
- If `print_stats.state` is not `standby` then `print_stats.filename`
|
||||
will report the name of the currently loaded file.
|
||||
- `print_stats.filename` can be used to fetch file metadata. It
|
||||
is only necessary to fetch metadata once per print.
|
||||
```
|
||||
GET http://host/server/files/metadata?filename=<filename>
|
||||
```
|
||||
Or via JSON-RPC 2.0:
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.files.metadata",
|
||||
"params": {
|
||||
"filename": "{filename}"
|
||||
},
|
||||
"id": 5643
|
||||
}
|
||||
```
|
||||
If metadata extraction failed then this request will return an error.
|
||||
Some metadata fields are only populated for specific slicers, and
|
||||
unsupported slicers will only return the size and modified date.
|
||||
|
||||
- There are multiple ways to calculate the ETA, this example will use
|
||||
file progress, as it is possible calculate the ETA with or without
|
||||
metadata.
|
||||
- If `metadata.estimated_time` is available, the eta calculation can
|
||||
be done as:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let vsd = result.status.virtual_sdcard;
|
||||
let prog_time = vsd.progress * metadata.estimated_time;
|
||||
let eta = metadata.estimated_time - prog_time
|
||||
```
|
||||
Alternatively, one can simply subtract the print duration from
|
||||
the estimated time:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let pstats = result.status.print_status;
|
||||
let eta = metadata.estimated_time - pstats.print_duration;
|
||||
if (eta < 0) eta = 0;
|
||||
```
|
||||
- If no metadata is available, print duration and progress can be used to
|
||||
calculate the ETA:
|
||||
```javascript
|
||||
// assume "result" is the response from the status query
|
||||
let vsd = result.status.virtual_sdcard;
|
||||
let pstats = result.status.print_stats;
|
||||
let total_time = pstats.print_duration / vsd.progress;
|
||||
let eta = total_time - pstats.print_duration;
|
||||
```
|
||||
|
||||
- It is possible to query additional objects if a client wishes to display
|
||||
more information (ie: temperatures). See Klipper's
|
||||
[Status Reference](https://www.klipper3d.org/Status_Reference.html)
|
||||
documentation for details on objects available for query.
|
||||
|
||||
### Bed Mesh Coordinates
|
||||
|
||||
The [Bed Mesh](../printer_objects.md#bed_mesh) printer object may be used
|
||||
to generate three dimensional coordinates of a probed area (or mesh).
|
||||
Below is an example (in javascript) of how to transform the data received
|
||||
from a bed_mesh object query into an array of 3D coordinates.
|
||||
|
||||
```javascript
|
||||
// assume that we have executed an object query for bed_mesh and have the
|
||||
// result. This example generates 3D coordinates for the probed matrix,
|
||||
// however it would work with the mesh matrix as well
|
||||
function process_mesh(result) {
|
||||
let bed_mesh = result.status.bed_mesh;
|
||||
let matrix = bed_mesh.probed_matrix;
|
||||
if (!(matrix instanceof Array) || matrix.length < 3 ||
|
||||
!(matrix[0] instanceof Array) || matrix[0].length < 3)
|
||||
// make sure that the matrix is valid
|
||||
return;
|
||||
let coordinates = [];
|
||||
// calculate the distance between each sample on both the X an Y
|
||||
// axes
|
||||
let x_distance = (bed_mesh.mesh_max[0] - bed_mesh.mesh_min[0]) /
|
||||
(matrix[0].length - 1);
|
||||
let y_distance = (bed_mesh.mesh_max[1] - bed_mesh.mesh_min[1]) /
|
||||
(matrix.length - 1);
|
||||
let x_idx = 0;
|
||||
let y_idx = 0;
|
||||
// transform the matrix of z values into (x, y, z) coordinates
|
||||
for (const x_axis of matrix) {
|
||||
x_idx = 0;
|
||||
// mesh_min is the (x, y) coordinate of the first z sample
|
||||
let y_coord = bed_mesh.mesh_min[1] + (y_idx * y_distance);
|
||||
for (const z_coord of x_axis) {
|
||||
let x_coord = bed_mesh.mesh_min[0] + (x_idx * x_distance);
|
||||
x_idx++;
|
||||
coordinates.push([x_coord, y_coord, z_coord]);
|
||||
}
|
||||
y_idx++;
|
||||
}
|
||||
}
|
||||
// Use the array of coordinates to visualize the "probed area"
|
||||
// or mesh..
|
||||
```
|
||||
|
||||
### Converting to Unix Time
|
||||
|
||||
Some of Moonraker's APIs return a date represented in Unix time.
|
||||
Most languages have functionality built in to convert Unix
|
||||
time to a workable object or string. For example, in JavaScript
|
||||
one might do something like the following:
|
||||
|
||||
```javascript
|
||||
for (let resp of result.gcode_store) {
|
||||
let date = new Date(resp.time * 1000);
|
||||
// Do something with date and resp.message ...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,440 @@
|
||||
# Job Queue Management
|
||||
|
||||
The following endpoints may be used to manage Moonraker's job queue.
|
||||
Note that Moonraker's Job Queue is implemented as a FIFO queue and it may
|
||||
contain multiple references to the same job.
|
||||
|
||||
The queue maintains an internal state attribute, which will always be one
|
||||
of the following:
|
||||
|
||||
| State | Description |
|
||||
| ---------- | ---------------------------------------------------------------- |
|
||||
| `ready` | The queue is active and will load the next queued job upon |
|
||||
| | completion of the current job. |^
|
||||
| `loading` | The queue is currently loading the next job. If the |
|
||||
| | `job_queue` configuration specifies a `job_transition_delay` |^
|
||||
| | and/or a `job_transition_gcode` the queue will remain in the |^
|
||||
| | `loading` state until both are completed. |^
|
||||
| `starting` | The state reported while the Job Queue is requesting Klipper |
|
||||
| | to start the print. |^
|
||||
| `paused` | When the queue is `paused` it will not load the next queued |
|
||||
| | job after a working job has completed. The queue will enter |^
|
||||
| | this state if a pause is requested through the "pause" endpoint, |^
|
||||
| | an error is encountered during the startup or loading phases, or |^
|
||||
| | after completion of a job when the `job_queue` configuration |^
|
||||
| | specifies that `automatic_transition` is set to false. |^
|
||||
{ #queue-state-desc } Queue State
|
||||
|
||||
/// note
|
||||
All filenames provided to and returned by these endpoints are relative to
|
||||
the `gcodes` root.
|
||||
///
|
||||
|
||||
## Get job queue status
|
||||
|
||||
Retrieves the current state of the job queue.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/job_queue/status
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.status",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 21.89680004119873
|
||||
},
|
||||
{
|
||||
"filename": "job2.gcode",
|
||||
"job_id": "0000000066D991F0",
|
||||
"time_added": 1636151050.7766452,
|
||||
"time_in_queue": 21.88680004119873
|
||||
},
|
||||
{
|
||||
"filename": "subdir/job3.gcode",
|
||||
"job_id": "0000000066D99D80",
|
||||
"time_added": 1636151050.7866452,
|
||||
"time_in_queue": 21.90680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "ready"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | :------: | -------------------------------------------------------- |
|
||||
| `queued_jobs` | [object] | An array of `Queued Job` objects. |
|
||||
| | | #queued-job-spec |+
|
||||
| `queue_state` | string | The current [state](#queue-state-desc) of the job queue. |
|
||||
{ #job-queue-status-response-spec }
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------- | :----: | ------------------------------------------------------- |
|
||||
| `filename` | string | The name of the gcode file queued. |
|
||||
| `job_id` | string | A unique ID assigned to the queued job. |
|
||||
| `time_added` | float | The time (in Unix Time) the job was added to the queue. |
|
||||
| `time_in_queue` | float | The cumulative amount of time, in seconds, the job has |
|
||||
| | | been pending in the queue. |^
|
||||
{ #queued-job-spec } Queued Job
|
||||
|
||||
///
|
||||
|
||||
## Enqueue a job
|
||||
|
||||
Adds a job, or an array of jobs, to the end of the job queue. The same
|
||||
filename may be specified multiple times to queue a job that repeats.
|
||||
When multiple jobs are specified they will be enqueued in the order they
|
||||
are received.
|
||||
|
||||
/// note
|
||||
The request will be aborted and return an error if any of the supplied
|
||||
files do not exist.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/job_queue/job
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"filenames": [
|
||||
"job1.gcode",
|
||||
"job2.gcode",
|
||||
"subdir/job3.gcode"
|
||||
],
|
||||
"reset": false
|
||||
}
|
||||
|
||||
```
|
||||
/// tip
|
||||
If it isn't possible for your client to pass parameters in the body
|
||||
of the request as a json object, they can be added to the query string
|
||||
as shown below:
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/job_queue/job?filenames=job1.gcode,job2.gcode,subdir/job3.gcode
|
||||
```
|
||||
|
||||
Multiple jobs should be comma separated as shown above.
|
||||
///
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.post_job",
|
||||
"params": {
|
||||
"filenames": [
|
||||
"job1.gcode",
|
||||
"job2.gcode",
|
||||
"subdir/job3.gcode"
|
||||
],
|
||||
"reset": false
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------- | :------: | ------------ | ------------------------------------------------------- |
|
||||
| `filenames` | [string] | **REQUIRED** | An array of filenames of jobs to add to the queue. |
|
||||
| | | | The file names should be paths relative to the `gcodes` |^
|
||||
| | | | root. All of the specified files must exist, otherwise |^
|
||||
| | | | the request will return with an error. |^
|
||||
| `reset` | bool | false | When set to `true` the job queue will be |
|
||||
| | | | cleared prior to adding the requested jobs. |^
|
||||
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 0.01680004119873
|
||||
},
|
||||
{
|
||||
"filename": "job2.gcode",
|
||||
"job_id": "0000000066D991F0",
|
||||
"time_added": 1636151050.7766452,
|
||||
"time_in_queue": 0.01480004119873
|
||||
},
|
||||
{
|
||||
"filename": "subdir/job3.gcode",
|
||||
"job_id": "0000000066D99D80",
|
||||
"time_added": 1636151050.7866452,
|
||||
"time_in_queue": 0.010680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "ready"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
See the [Job Queue Status](#job-queue-status-response-spec)
|
||||
Response Specification.
|
||||
|
||||
///
|
||||
|
||||
## Remove a Job
|
||||
|
||||
Removes one or more jobs from the queue.
|
||||
|
||||
/// Note
|
||||
Unlike the POST version of this method, it is not necessary that
|
||||
all job ids exist. If any supplied job id does not exist in the
|
||||
queue it will be silently ignored. Clients can verify the contents
|
||||
of the queue via the return value.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/job_queue/job?job_ids=0000000066D991F0,0000000066D99D80
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.delete_job",
|
||||
"params": {
|
||||
"job_ids": [
|
||||
"0000000066D991F0",
|
||||
"0000000066D99D80"
|
||||
]
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| --------- | :------: | --------------- | ------------------------------------------------ |
|
||||
| `job_ids` | [string] | **REQUIRED** | An array of `job_ids` to remove from the queue. |
|
||||
| | | if `all==false` | Any job ids that do not exist will be ignored. |^
|
||||
| `all` | bool | false | When set to `true` all jobs will be removed |
|
||||
| | | | from the queue. In this case it is not necessary |^
|
||||
| | | | to set the `job_ids` parameter. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 21.89680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "ready"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
See the [Job Queue Status](#job-queue-status-response-spec)
|
||||
Response Specification.
|
||||
|
||||
///
|
||||
|
||||
## Pause the job queue
|
||||
|
||||
Sets the job queue state to "pause", which prevents the next job
|
||||
in the queue from loading after an job in progress is complete.
|
||||
If the queue is paused while the queue is in the `loading` state
|
||||
the load will be aborted.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/job_queue/pause
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.pause",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 21.89680004119873
|
||||
},
|
||||
{
|
||||
"filename": "job2.gcode",
|
||||
"job_id": "0000000066D991F0",
|
||||
"time_added": 1636151050.7766452,
|
||||
"time_in_queue": 21.88680004119873
|
||||
},
|
||||
{
|
||||
"filename": "subdir/job3.gcode",
|
||||
"job_id": "0000000066D99D80",
|
||||
"time_added": 1636151050.7866452,
|
||||
"time_in_queue": 21.90680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "paused"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
See the [Job Queue Status](#job-queue-status-response-spec)
|
||||
Response Specification.
|
||||
|
||||
///
|
||||
|
||||
## Start the job queue
|
||||
|
||||
Starts the job queue. If Klipper is ready to start a print the next
|
||||
job in the queue will be loaded. Otherwise the queue will be put
|
||||
into the "ready" state, where the job will be loaded after the current
|
||||
job completes.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/job_queue/start
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.start",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 21.89680004119873
|
||||
},
|
||||
{
|
||||
"filename": "job2.gcode",
|
||||
"job_id": "0000000066D991F0",
|
||||
"time_added": 1636151050.7766452,
|
||||
"time_in_queue": 21.88680004119873
|
||||
},
|
||||
{
|
||||
"filename": "subdir/job3.gcode",
|
||||
"job_id": "0000000066D99D80",
|
||||
"time_added": 1636151050.7866452,
|
||||
"time_in_queue": 21.90680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "loading"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
See the [Job Queue Status](#job-queue-status-response-spec)
|
||||
Response Specification.
|
||||
|
||||
///
|
||||
|
||||
## Perform a Queue Jump
|
||||
|
||||
Jumps a job to the front of the queue.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/job_queue/jump?job_id=0000000066D991F0
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.job_queue.jump",
|
||||
"params": {
|
||||
"job_id": "0000000066D991F0"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| -------- | :----: | ------------ | --------------------------------------- |
|
||||
| `job_id` | string | **REQUIRED** | The `job_id` of the job to jump to the. |
|
||||
| | | | front of the queue. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"queued_jobs": [
|
||||
{
|
||||
"filename": "job2.gcode",
|
||||
"job_id": "0000000066D991F0",
|
||||
"time_added": 1636151050.7766452,
|
||||
"time_in_queue": 21.88680004119873
|
||||
},
|
||||
{
|
||||
"filename": "job1.gcode",
|
||||
"job_id": "0000000066D99C90",
|
||||
"time_added": 1636151050.7666452,
|
||||
"time_in_queue": 21.89680004119873
|
||||
},
|
||||
{
|
||||
"filename": "subdir/job3.gcode",
|
||||
"job_id": "0000000066D99D80",
|
||||
"time_added": 1636151050.7866452,
|
||||
"time_in_queue": 21.90680004119873
|
||||
}
|
||||
],
|
||||
"queue_state": "loading"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
See the [Job Queue Status](#job-queue-status-response-spec)
|
||||
Response Specification.
|
||||
|
||||
///
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,667 @@
|
||||
# Printer Administration
|
||||
|
||||
These endpoints provide access to printer state and printer control.
|
||||
Klippy must be connected to Moonraker to receive a successful response,
|
||||
and in many cases Klippy must be in the `ready` state.
|
||||
|
||||
Most of these endpoints are registered with Moonraker by Klipper.
|
||||
Requests pass from the frontend through Moonraker directly to Klipper.
|
||||
Moonraker does not intervene.
|
||||
|
||||
## Get Klippy host information
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /printer/info
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.info",
|
||||
"id": 5445
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"state": "ready",
|
||||
"state_message": "Printer is ready",
|
||||
"hostname": "pi-debugger",
|
||||
"klipper_path": "/home/pi/klipper",
|
||||
"python_path": "/home/pi/klipper/venv/bin/python",
|
||||
"process_id": 275124,
|
||||
"user_id": 1000,
|
||||
"group_id": 1000,
|
||||
"log_file": "/home/pi/printer_data/logs/klippy.log",
|
||||
"config_file": "/home/pi/printer_data/config/printer.cfg",
|
||||
"software_version": "v0.12.0-85-gd785b396",
|
||||
"cpu_info": "4 core ?"
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ------------------ | :----: | ----------------------------------------------------- |
|
||||
| `state` | string | Klippy's current [state](#klippy-state-desc). |
|
||||
| `state_message` | string | A message describing Klippy's current state. |
|
||||
| `hostname` | string | Hostname of the machine running Klippy. |
|
||||
| `klipper_path` | string | Path on disk to the Klipper application. |
|
||||
| `python_path` | string | Path on disk to the Python executable running Klippy. |
|
||||
| `process_id` | int | The PID of the current Klippy process. |
|
||||
| `user_id` | int | The UID of the user the Klippy process belongs to. |
|
||||
| `group_id` | int | The GID of the group the Klippy process belongs to. |
|
||||
| `log_file` | string | Path on disk to Klipper's log file. |
|
||||
| `configfile` | string | Path on disk to Klipper's configuration file. |
|
||||
| `software_version` | string | Version of the currently running instance of Klipper. |
|
||||
| `cpu_info` | string | A brief description of the host machine's CPU. |
|
||||
|
||||
| State | Description |
|
||||
| ---------- | ------------------------------------------------------- |
|
||||
| `ready` | Klippy has initialized and is ready for commands. |
|
||||
| `startup` | Klippy is currently in its startup phase. |
|
||||
| `error` | Klippy encountered an error during startup. |
|
||||
| `shutdown` | Klippy is in the shutdown state. This can be initiated |
|
||||
| | by the user via an emergency stop, or by the software |^
|
||||
| | if it encounters a critical error during operation. |^
|
||||
{ #klippy-state-desc } Klippy State
|
||||
///
|
||||
|
||||
## Emergency Stop
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/emergency_stop
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.emergency_stop",
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
/// Note
|
||||
This endpoint will immediately halt the printer and put it in a "shutdown"
|
||||
state. It should be used to implement an "emergency stop" button and
|
||||
also used if a user enters `M112`(emergency stop) via a console.
|
||||
///
|
||||
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Host Restart
|
||||
|
||||
Requests a Klipper "soft" restart. This will reload the Klippy application
|
||||
and configuration. Connected MCUs will not be reset.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/restart
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.restart",
|
||||
"id": 4894
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Firmware Restart
|
||||
|
||||
Requests a complete Klipper restart. Both the Klippy Application and connected
|
||||
MCUs will be reset.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/firmware_restart
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.firmware_restart",
|
||||
"id": 8463
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Printer Status Requests
|
||||
|
||||
### List loaded printer objects
|
||||
|
||||
Returns a list of Klipper `printer objects` that are currently loaded.
|
||||
This can be used to determine if a specific object is available for query
|
||||
and/or subscription.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /printer/objects/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.objects.list",
|
||||
"id": 1454
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"objects": [
|
||||
"gcode",
|
||||
"webhooks",
|
||||
"configfile",
|
||||
"mcu",
|
||||
"mcu linux",
|
||||
"heaters",
|
||||
"bme280 chamber",
|
||||
"temperature_sensor chamber",
|
||||
"filament_switch_sensor extruder_sensor",
|
||||
"output_pin sensor_toggle",
|
||||
"gcode_move",
|
||||
"bed_mesh",
|
||||
"exclude_object",
|
||||
"temperature_host RPi",
|
||||
"temperature_sensor RPi",
|
||||
"gcode_macro TURN_OFF_MOTORS",
|
||||
"gcode_macro SET_HOMING_CURRENT",
|
||||
"temperature_sensor ambient",
|
||||
"gcode_macro query_bme280",
|
||||
"pause_resume",
|
||||
"print_stats",
|
||||
"virtual_sdcard",
|
||||
"probe",
|
||||
"stepper_enable",
|
||||
"tmc2130 stepper_x",
|
||||
"tmc2130 stepper_y",
|
||||
"tmc2130 stepper_z",
|
||||
"tmc2130 extruder",
|
||||
"heater_bed",
|
||||
"heater_fan nozzle_cooling_fan",
|
||||
"fan",
|
||||
"menu",
|
||||
"display_status",
|
||||
"output_pin BEEPER_pin",
|
||||
"idle_timeout",
|
||||
"motion_report",
|
||||
"query_endstops",
|
||||
"system_stats",
|
||||
"manual_probe",
|
||||
"toolhead",
|
||||
"extruder"
|
||||
]
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| --------- | :------: | ------------------------------------------------ |
|
||||
| `objects` | [string] | A list Klipper printer objects currently loaded. |
|
||||
///
|
||||
|
||||
### Query printer object status
|
||||
|
||||
Requests the status of a provided set of printer objects.
|
||||
|
||||
/// Tip
|
||||
See the [Printer Objects](../printer_objects.md) document
|
||||
for details on the objects available for query.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/objects/query
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"objects": {
|
||||
"gcode_move": null,
|
||||
"toolhead": ["position", "status"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
/// details | Using the Query String
|
||||
The HTTP Request may also be performed using the query string. It is
|
||||
recommended to send the request in the body unless otherwise not possible.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /printer/objects/query?gcode_move&toolhead&extruder=target,temperature
|
||||
```
|
||||
|
||||
The above will request a status update for all `gcode_move` and `toolhead`
|
||||
attributes. Only the `temperature` and `target` attributes are requested
|
||||
for the `extruder`.
|
||||
///
|
||||
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.objects.query",
|
||||
"params": {
|
||||
"objects": {
|
||||
"gcode_move": null,
|
||||
"toolhead": ["position", "status"]
|
||||
}
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| --------- | :----: | ------------ | ------------------------------------------------------ |
|
||||
| `objects` | object | **REQUIRED** | An object whose key, value pairs represent one or |
|
||||
| | | | more [Printer Object Requests](#printer-obj-req-desc). |^
|
||||
|
||||
| Key Description | Value Description |
|
||||
| ------------------------------- | ----------------------------------------------------------- |
|
||||
| The `key`should be an available | The `value` specifies the attributes of the object that |
|
||||
| Klipper printer object. | should be returned. If the value is `null` all attributes |^
|
||||
| { width=40% } | will be returned. Alternatively a list of strings |^
|
||||
| | specifying the desired attributes can be provided. |^
|
||||
{ #printer-obj-req-desc } Printer Object Request
|
||||
|
||||
//// Note
|
||||
If a requested printer object or attribute does not exist then the result
|
||||
will be omitted from the response. No error is returned.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"eventtime": 578243.57824499,
|
||||
"status": {
|
||||
"gcode_move": {
|
||||
"absolute_coordinates": true,
|
||||
"absolute_extrude": true,
|
||||
"extrude_factor": 1,
|
||||
"gcode_position": [0, 0, 0, 0],
|
||||
"homing_origin": [0, 0, 0, 0],
|
||||
"position": [0, 0, 0, 0],
|
||||
"speed": 1500,
|
||||
"speed_factor": 1
|
||||
},
|
||||
"toolhead": {
|
||||
"position": [0, 0, 0, 0],
|
||||
"status": "Ready"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ----------- | :----: | -------------------------------------------------------------- |
|
||||
| `eventtime` | float | The time at which the status was received, according Klipper's |
|
||||
| | | monotonic clock. |^
|
||||
| `status` | object | An object containing the current state of the requested |
|
||||
| | | printer objects. |^
|
||||
{ #object-query-response-spec }
|
||||
///
|
||||
|
||||
### Subscribe to printer object status updates
|
||||
|
||||
Requests status updates for a set of printer objects. A persistent
|
||||
connection (Websocket or Unix Socket) is required to fulfill this
|
||||
request.
|
||||
|
||||
Status updates for subscribed objects are sent asynchronously over the
|
||||
connection. See the
|
||||
[notify_status_update](./jsonrpc_notifications.md#subscription-updates)
|
||||
notification for details.
|
||||
|
||||
/// Tip
|
||||
See the [Printer Objects](../printer_objects.md) document
|
||||
for details on the objects available for subscription.
|
||||
///
|
||||
|
||||
```{.text .apirequest title="HTTP Request"}
|
||||
Not available
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request (Websocket and Unix Socket Only)"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.objects.subscribe",
|
||||
"params": {
|
||||
"objects": {
|
||||
"gcode_move": null,
|
||||
"toolhead": ["position", "status"]
|
||||
}
|
||||
},
|
||||
"id": 5434
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
Parameters are identical to the [query](#query-printer-object-status)
|
||||
status parameters. A new request will override a previous request.
|
||||
If `objects` is set to an empty object then the subscription will be
|
||||
cancelled.
|
||||
///
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"eventtime": 578243.57824499,
|
||||
"status": {
|
||||
"gcode_move": {
|
||||
"absolute_coordinates": true,
|
||||
"absolute_extrude": true,
|
||||
"extrude_factor": 1,
|
||||
"gcode_position": [0, 0, 0, 0],
|
||||
"homing_origin": [0, 0, 0, 0],
|
||||
"position": [0, 0, 0, 0],
|
||||
"speed": 1500,
|
||||
"speed_factor": 1,
|
||||
},
|
||||
"toolhead": {
|
||||
"position": [0, 0, 0, 0],
|
||||
"status": "Ready"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
The response spec is identical to the [query response specification](#object-query-response-spec)
|
||||
The response may be used to initialize local state without performing a
|
||||
separate query.
|
||||
///
|
||||
|
||||
### Query Endstops
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /printer/query_endstops/status
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.query_endstops.status",
|
||||
"id": 3456
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"x": "TRIGGERED",
|
||||
"y": "open",
|
||||
"z": "open"
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ----------------------------------------------------------- |
|
||||
| *variable* | string | The field is the name of the registered endstop. The value |
|
||||
| | | will be `open` or `TRIGGERED`. |^
|
||||
///
|
||||
|
||||
## GCode APIs
|
||||
|
||||
### Run a gcode command
|
||||
|
||||
Executes a gcode command. Multiple commands may be executed by separating
|
||||
them with a newline (`\n`). The request returns when the command or series
|
||||
of commands have completed, or when the command results in an error.
|
||||
|
||||
/// warning
|
||||
When `M112`(emergency stop) is requested via this endpoint it will not
|
||||
immediately stop the printer. `M112` will be placed on the gcode queue and
|
||||
executed after all previous gcodes are complete. If a frontend detects
|
||||
`M112` via user input (such as a console) it should request the
|
||||
`/printer/emergency_stop` endpoint to immediately halt the printer. This
|
||||
may be done in addition to sending the `M112` gcode if desired.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/gcode/script
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"script": "G28"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.gcode.script",
|
||||
"params": {
|
||||
"script": "G28"
|
||||
},
|
||||
"id": 7466}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| -------- | :----: | ------------ | ------------------------------------------------- |
|
||||
| `script` | string | **REQUIRED** | A GCode Command to run. Multiple commands may be |
|
||||
| | | | specified, separated by a newline (`\n`). |^
|
||||
///
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
### Get GCode Help
|
||||
|
||||
Retrieves a list of registered GCode Command Descriptions. Not all registered
|
||||
GCode commands have a description, so this list should not be treated as an
|
||||
exhaustive list of all supported commands.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /printer/gcode/help
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.gcode.help",
|
||||
"id": 4645
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"RESTART": "Reload config file and restart host software",
|
||||
"FIRMWARE_RESTART": "Restart firmware, host, and reload config",
|
||||
"STATUS": "Report the printer status",
|
||||
"HELP": "Report the list of available extended G-Code commands",
|
||||
"SAVE_CONFIG": "Overwrite config file and restart",
|
||||
"SHUTDOWN_MACHINE": "G-Code macro",
|
||||
"SET_GCODE_VARIABLE": "Set the value of a G-Code macro variable",
|
||||
"REBOOT_MACHINE": "G-Code macro",
|
||||
"UPDATE_DELAYED_GCODE": "Update the duration of a delayed_gcode",
|
||||
"TURN_OFF_HEATERS": "Turn off all heaters",
|
||||
"TEMPERATURE_WAIT": "Wait for a temperature on a sensor",
|
||||
"QUERY_ADC": "Report the last value of an analog pin",
|
||||
"QUERY_FILAMENT_SENSOR": "Query the status of the Filament Sensor",
|
||||
"SET_FILAMENT_SENSOR": "Sets the filament sensor on/off",
|
||||
"SET_PIN": "Set the value of an output pin",
|
||||
"BED_MESH_CALIBRATE": "Perform Mesh Bed Leveling",
|
||||
"BED_MESH_PROFILE": "Bed Mesh Persistent Storage management",
|
||||
"BED_MESH_OUTPUT": "Retrieve interpolated grid of probed z-points",
|
||||
"BED_MESH_MAP": "Serialize mesh and output to terminal",
|
||||
"BED_MESH_CLEAR": "Clear the Mesh so no z-adjustment is made",
|
||||
"BED_MESH_OFFSET": "Add X/Y offsets to the mesh lookup",
|
||||
"SET_GCODE_OFFSET": "Set a virtual offset to g-code positions",
|
||||
"SAVE_GCODE_STATE": "Save G-Code coordinate state",
|
||||
"RESTORE_GCODE_STATE": "Restore a previously saved G-Code state",
|
||||
"GET_POSITION": "Return information on the current location of the toolhead",
|
||||
"EXCLUDE_OBJECT_START": "Marks the beginning the current object as labeled",
|
||||
"EXCLUDE_OBJECT_END": "Marks the end the current object",
|
||||
"EXCLUDE_OBJECT": "Cancel moves inside a specified objects",
|
||||
"EXCLUDE_OBJECT_DEFINE": "Provides a summary of an object",
|
||||
"TURN_OFF_MOTORS": "G-Code macro",
|
||||
"CLEAR_PAUSE": "Clears the current paused state without resuming the print",
|
||||
"SET_PRINT_STATS_INFO": "Pass slicer info like layer act and total to klipper",
|
||||
"SDCARD_RESET_FILE": "Clears a loaded SD File. Stops the print if necessary",
|
||||
"SDCARD_PRINT_FILE": "Loads a SD file and starts the print. May include files in subdirectories.",
|
||||
"RESPOND": "Echo the message prepended with a prefix",
|
||||
"PROBE": "Probe Z-height at current XY position",
|
||||
"QUERY_PROBE": "Return the status of the z-probe",
|
||||
"PROBE_CALIBRATE": "Calibrate the probe's z_offset",
|
||||
"PROBE_ACCURACY": "Probe Z-height accuracy at current XY position",
|
||||
"Z_OFFSET_APPLY_PROBE": "Adjust the probe's z_offset",
|
||||
"GET_CURRENT_SKEW": "Report current printer skew",
|
||||
"CALC_MEASURED_SKEW": "Calculate skew from measured print",
|
||||
"SET_SKEW": "Set skew based on lengths of measured object",
|
||||
"SKEW_PROFILE": "Profile management for skew_correction",
|
||||
"SET_STEPPER_ENABLE": "Enable/disable individual stepper by name",
|
||||
"SET_TMC_FIELD": "Set a register field of a TMC driver",
|
||||
"INIT_TMC": "Initialize TMC stepper driver registers",
|
||||
"SET_TMC_CURRENT": "Set the current of a TMC driver",
|
||||
"DUMP_TMC": "Read and display TMC stepper driver registers",
|
||||
"PID_CALIBRATE": "Run PID calibration test",
|
||||
"SET_HEATER_TEMPERATURE": "Sets a heater temperature",
|
||||
"SET_DISPLAY_TEXT": "Set or clear the display message",
|
||||
"SET_DISPLAY_GROUP": "Set the active display group",
|
||||
"STEPPER_BUZZ": "Oscillate a given stepper to help id it",
|
||||
"FORCE_MOVE": "Manually move a stepper; invalidates kinematics",
|
||||
"SET_KINEMATIC_POSITION": "Force a low-level kinematic position",
|
||||
"SET_IDLE_TIMEOUT": "Set the idle timeout in seconds",
|
||||
"QUERY_ENDSTOPS": "Report on the status of each endstop",
|
||||
"SET_VELOCITY_LIMIT": "Set printer velocity limits",
|
||||
"MANUAL_PROBE": "Start manual probe helper script",
|
||||
"TUNING_TOWER": "Tool to adjust a parameter at each Z height",
|
||||
"SET_PRESSURE_ADVANCE": "Set pressure advance parameters",
|
||||
"SET_EXTRUDER_ROTATION_DISTANCE": "Set extruder rotation distance",
|
||||
"SYNC_EXTRUDER_MOTION": "Set extruder stepper motion queue",
|
||||
"SET_EXTRUDER_STEP_DISTANCE": "Set extruder step distance",
|
||||
"SYNC_STEPPER_TO_EXTRUDER": "Set extruder stepper",
|
||||
"ACTIVATE_EXTRUDER": "Change the active extruder",
|
||||
"BASE_PAUSE": "Renamed builtin of 'PAUSE'",
|
||||
"BASE_RESUME": "Renamed builtin of 'RESUME'",
|
||||
"BASE_CANCEL_PRINT": "Renamed builtin of 'CANCEL_PRINT'",
|
||||
"ACCEPT": "Accept the current Z position",
|
||||
"ABORT": "Abort manual Z probing tool",
|
||||
"TESTZ": "Move to new Z height"
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ----------------------------------------------------------------- |
|
||||
| *variable* | string | The field is the name of the registered gcode command. The value |
|
||||
| | | is a string containing the associated help descriptions. |^
|
||||
|
||||
//// Note
|
||||
As mentioned previously, this list is not exhaustive. Help strings are not
|
||||
available for default gcode handlers such as G1, G28, etc, nor are they
|
||||
available for extended handlers that failed to register a description in
|
||||
Klipper's python source.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
## Print Job Management
|
||||
|
||||
### Start a print job
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/print/start?filename=test_print.gcode
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.print.start",
|
||||
"params": {
|
||||
"filename": "test_print.gcode"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: true
|
||||
| Name | Type | Default | Description |
|
||||
| ---------- | :----: | ------------ | --------------------------------------------------- |
|
||||
| `filename` | string | **REQUIRED** | The name of the gcode file to print. May be a path |
|
||||
| | | | relative to the gcode folder. |^
|
||||
///
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
### Pause a print job
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/print/pause
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.print.pause",
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
### Resume a print job
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/print/resume
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.print.resume",
|
||||
"id": 1465
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
### Cancel a print job
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /printer/print/cancel
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "printer.print.cancel",
|
||||
"id": 2578
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
@@ -0,0 +1,648 @@
|
||||
# Server Administration
|
||||
|
||||
These endpoints provide access to server status, data tracking, and
|
||||
administrative requests.
|
||||
|
||||
## Query Server Info
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/info
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.info",
|
||||
"id": 9546
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"klippy_connected": true,
|
||||
"klippy_state": "ready",
|
||||
"components": [
|
||||
"database",
|
||||
"file_manager",
|
||||
"klippy_apis",
|
||||
"machine",
|
||||
"data_store",
|
||||
"shell_command",
|
||||
"proc_stats",
|
||||
"history",
|
||||
"octoprint_compat",
|
||||
"update_manager",
|
||||
"power"
|
||||
],
|
||||
"failed_components": [],
|
||||
"registered_directories": ["config", "gcodes", "config_examples", "docs"],
|
||||
"warnings": [
|
||||
"Invalid config option 'api_key_path' detected in section [authorization]. Remove the option to resolve this issue. In the future this will result in a startup error.",
|
||||
"Unparsed config section [fake_section] detected. This may be the result of a component that failed to load. In the future this will result in a startup error."
|
||||
],
|
||||
"websocket_count": 2,
|
||||
"moonraker_version": "v0.7.1-105-ge4f103c",
|
||||
"api_version": [1, 4, 0],
|
||||
"api_version_string": "1.4.0"
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ------------------------ | :------: | -------------------------------------------------------- |
|
||||
| `klippy_connected` | bool | Moonraker's connection status to the Klippy Host. |
|
||||
| `klippy_state` | string | Klippy's current state. Expand for available values. |
|
||||
| #klippy-state-desc | | |+
|
||||
| `components` | [string] | A list of Moonraker components that are currently |
|
||||
| | | loaded. |^
|
||||
| `failed_components` | [string] | A list of Moonraker components that failed to load. |
|
||||
| `registered_directories` | [string] | A list "roots" registered with Moonraker's file manager. |
|
||||
| `warnings` | [string] | A list of warning messages describing errors encountered |
|
||||
| | | during initialization or regular operation. |^
|
||||
| `websocket_count` | int | The number of currently active websocket connections. |
|
||||
| `moonraker_version` | string | The version of the Moonraker Application. |
|
||||
| `api_version` | [int] | The version of the API in tuple format. |
|
||||
| `api_version_string` | string | The version of the API in string format. |
|
||||
|
||||
| State | Description |
|
||||
| -------------- | ------------------------------------------------------------------ |
|
||||
| `disconnected` | Moonraker is currently disconnect from Klippy. |
|
||||
| `startup` | Klippy is currently initializing. |
|
||||
| `ready` | Klippy is active and ready to receive commands. |
|
||||
| `error` | Klippy experienced an error during startup. |
|
||||
| `shutdown` | Klippy has been emergency stopped. This can occur at user request |
|
||||
| | or if a critical error is encountered while running. |^
|
||||
{ #klippy-state-desc }
|
||||
///
|
||||
|
||||
## Get Server Configuration
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/config
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.config",
|
||||
"id": 5616
|
||||
}
|
||||
```
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"config": {
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
"port": 7125,
|
||||
"ssl_port": 7130,
|
||||
"enable_debug_logging": true,
|
||||
"enable_asyncio_debug": false,
|
||||
"klippy_uds_address": "/tmp/klippy_uds",
|
||||
"max_upload_size": 210,
|
||||
"ssl_certificate_path": null,
|
||||
"ssl_key_path": null
|
||||
},
|
||||
"dbus_manager": {},
|
||||
"database": {
|
||||
"database_path": "~/.moonraker_database",
|
||||
"enable_database_debug": false
|
||||
},
|
||||
"file_manager": {
|
||||
"enable_object_processing": true,
|
||||
"queue_gcode_uploads": true,
|
||||
"config_path": "~/printer_config",
|
||||
"log_path": "~/logs"
|
||||
},
|
||||
"klippy_apis": {},
|
||||
"machine": {
|
||||
"provider": "systemd_dbus"
|
||||
},
|
||||
"shell_command": {},
|
||||
"data_store": {
|
||||
"temperature_store_size": 1200,
|
||||
"gcode_store_size": 1000
|
||||
},
|
||||
"proc_stats": {},
|
||||
"job_state": {},
|
||||
"job_queue": {
|
||||
"load_on_startup": true,
|
||||
"automatic_transition": false,
|
||||
"job_transition_delay": 2,
|
||||
"job_transition_gcode": "\nM118 Transitioning to next job..."
|
||||
},
|
||||
"http_client": {},
|
||||
"announcements": {
|
||||
"dev_mode": false,
|
||||
"subscriptions": []
|
||||
},
|
||||
"authorization": {
|
||||
"login_timeout": 90,
|
||||
"force_logins": false,
|
||||
"cors_domains": [
|
||||
"*.home",
|
||||
"http://my.mainsail.xyz",
|
||||
"http://app.fluidd.xyz",
|
||||
"*://localhost:*"
|
||||
],
|
||||
"trusted_clients": [
|
||||
"192.168.1.0/24"
|
||||
]
|
||||
},
|
||||
"zeroconf": {},
|
||||
"octoprint_compat": {
|
||||
"enable_ufp": true,
|
||||
"flip_h": false,
|
||||
"flip_v": false,
|
||||
"rotate_90": false,
|
||||
"stream_url": "/webcam/?action=stream",
|
||||
"webcam_enabled": true
|
||||
},
|
||||
"history": {},
|
||||
"secrets": {
|
||||
"secrets_path": "~/moonraker_secrets.ini"
|
||||
},
|
||||
"mqtt": {
|
||||
"address": "eric-work.home",
|
||||
"port": 1883,
|
||||
"username": "{secrets.mqtt_credentials.username}",
|
||||
"password_file": null,
|
||||
"password": "{secrets.mqtt_credentials.password}",
|
||||
"mqtt_protocol": "v3.1.1",
|
||||
"instance_name": "pi-debugger",
|
||||
"default_qos": 0,
|
||||
"status_objects": {
|
||||
"webhooks": null,
|
||||
"toolhead": "position,print_time",
|
||||
"idle_timeout": "state",
|
||||
"gcode_macro M118": null
|
||||
},
|
||||
"api_qos": 0,
|
||||
"enable_moonraker_api": true
|
||||
},
|
||||
"template": {}
|
||||
},
|
||||
"orig": {
|
||||
"DEFAULT": {},
|
||||
"server": {
|
||||
"enable_debug_logging": "True",
|
||||
"max_upload_size": "210"
|
||||
},
|
||||
"file_manager": {
|
||||
"config_path": "~/printer_config",
|
||||
"log_path": "~/logs",
|
||||
"queue_gcode_uploads": "True",
|
||||
"enable_object_processing": "True"
|
||||
},
|
||||
"machine": {
|
||||
"provider": "systemd_dbus"
|
||||
},
|
||||
"announcements": {},
|
||||
"job_queue": {
|
||||
"job_transition_delay": "2.",
|
||||
"job_transition_gcode": "\nM118 Transitioning to next job...",
|
||||
"load_on_startup": "True"
|
||||
},
|
||||
"authorization": {
|
||||
"trusted_clients": "\n192.168.1.0/24",
|
||||
"cors_domains": "\n*.home\nhttp://my.mainsail.xyz\nhttp://app.fluidd.xyz\n*://localhost:*"
|
||||
},
|
||||
"zeroconf": {},
|
||||
"octoprint_compat": {},
|
||||
"history": {},
|
||||
"secrets": {
|
||||
"secrets_path": "~/moonraker_secrets.ini"
|
||||
},
|
||||
"mqtt": {
|
||||
"address": "eric-work.home",
|
||||
"port": "1883",
|
||||
"username": "{secrets.mqtt_credentials.username}",
|
||||
"password": "{secrets.mqtt_credentials.password}",
|
||||
"enable_moonraker_api": "True",
|
||||
"status_objects": "\nwebhooks\ntoolhead=position,print_time\nidle_timeout=state\ngcode_macro M118"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"filename": "moonraker.conf",
|
||||
"sections": [
|
||||
"server",
|
||||
"file_manager",
|
||||
"machine",
|
||||
"announcements",
|
||||
"job_queue",
|
||||
"authorization",
|
||||
"zeroconf",
|
||||
"octoprint_compat",
|
||||
"history",
|
||||
"secrets"
|
||||
]
|
||||
},
|
||||
{
|
||||
"filename": "include/extras.conf",
|
||||
"sections": [
|
||||
"mqtt"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| -------- | :------: | ---------------------------------------------------------------------- |
|
||||
| `config` | object | An object containing the full Moonraker configuration. Each field of |
|
||||
| | | this object is a section name. The value for each section is an |^
|
||||
| | | object mapping option names to values. Values are cast to their |^
|
||||
| | | internal type. Default values not specified in the configuration |^
|
||||
| | | files are included. |^
|
||||
| `orig` | object | An object containing the original configuration as read from the |
|
||||
| | | configuration file(s). Like `config`, each field is a section name |^
|
||||
| | | and each value is a mapping of options to values. Only values present |^
|
||||
| | | in the configuration files are reported, and all values are strings. |^
|
||||
| `files` | [object] | An array of [File Objects](#file-object-spec) describing the config |
|
||||
| | | files parsed. |^
|
||||
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------- | :------: | ----------------------------------------------------------------- |
|
||||
| `filename` | string | The name of the configuration file. This name is a path relative |
|
||||
| | | to the main configuration file's parent folder. |^
|
||||
| `sections` | [string] | The config sections parsed from this file. |
|
||||
{ #file-object-spec } File Object
|
||||
|
||||
///
|
||||
|
||||
## Request Cached Temperature Data
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/temperature_store?include_monitors=false
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.temperature_store",
|
||||
"params": {
|
||||
"include_monitors": false
|
||||
},
|
||||
"id": 2313
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| ------------------ | :--: | ------- | -------------------------------------------- |
|
||||
| `include_monitors` | bool | `false` | When set to `true` the response will include |
|
||||
| | | | sensors reported as `temperature monitors.` |^
|
||||
| | | | A temperature monitor is a specific type of |^
|
||||
| | | | sensor that may include `null` values in |^
|
||||
| | | | the `temperatures` field of the response. |^
|
||||
///
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"extruder": {
|
||||
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1],
|
||||
"targets": [0, 0, 0, 0, 0],
|
||||
"powers": [0, 0, 0, 0, 0]
|
||||
},
|
||||
"temperature_fan my_fan": {
|
||||
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1],
|
||||
"targets": [0, 0, 0, 0, 0],
|
||||
"speeds": [0, 0, 0, 0, 0]
|
||||
},
|
||||
"temperature_sensor my_sensor": {
|
||||
"temperatures": [21.05, 21.12, 21.1, 21.1, 21.1]
|
||||
}
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ---------- | :----: | ----------------------------------------------------------------------------- |
|
||||
| *variable* | object | A primary object including zero or more [Sensor Objects](#sensor-obj-spec). |
|
||||
| | | The `fields` in this object will be sensor names as reported by Klippy. |^
|
||||
| | | If Klippy has not been initialized or reports no sensors this object will |^
|
||||
| | | be empty. |^
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------------- | :------: | ------------------------------------------------------------------ |
|
||||
| `temperatures` | [float?] | Contains the history of temperature measurements of this sensor. |
|
||||
| | | If the sensor is a `temperature monitor` values may be `null`. A |^
|
||||
| | | `null` value indicates that the sensor recorded no measurement at |^
|
||||
| | | that time. |^
|
||||
| `targets` | [float] | Contains the history of temperature targets for heaters. |
|
||||
| `speeds` | [float] | Contains a history of `speeds` for fans. This value should be |
|
||||
| | | between 0 and 1 indicating the pwm duty cycle. |^
|
||||
| `powers` | [float] | Contains a history fof `powers` for heaters. This value should be |
|
||||
| | | between 0 and 1 indicating the pwm duty cycle. |^
|
||||
{ #sensor-obj-spec } Sensor Object
|
||||
|
||||
//// Note
|
||||
Fields not reported by a sensor will be omitted in the `Sensor Object`.
|
||||
|
||||
Each array in the `Sensor Object` is a FIFO queue, where the measurement at index 0
|
||||
is the oldest value. The time period between each measurement is 1 second. The
|
||||
maximum length of the array is set in Moonraker's configuration, where the default is
|
||||
1200 values.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
## Request Cached GCode Responses
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/gcode_store?count=100
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.gcode_store",
|
||||
"params": {
|
||||
"count": 100
|
||||
},
|
||||
"id": 7643
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| ------- | :--: | ------------ | --------------------------------------------------- |
|
||||
| `count` | int | *Store Size* | The number of cached gcode responses to return. The |
|
||||
| | | | default is to return all cached items. |^
|
||||
///
|
||||
|
||||
//// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"gcode_store": [
|
||||
{
|
||||
"message": "FIRMWARE_RESTART",
|
||||
"time": 1615832299.1167388,
|
||||
"type": "command"
|
||||
},
|
||||
{
|
||||
"message": "// Klipper state: Ready",
|
||||
"time": 1615832309.9977088,
|
||||
"type": "response"
|
||||
},
|
||||
{
|
||||
"message": "M117 This is a test",
|
||||
"time": 1615834094.8662775,
|
||||
"type": "command"
|
||||
},
|
||||
{
|
||||
"message": "G4 P1000",
|
||||
"time": 1615834098.761729,
|
||||
"type": "command"
|
||||
},
|
||||
{
|
||||
"message": "STATUS",
|
||||
"time": 1615834104.2860553,
|
||||
"type": "command"
|
||||
},
|
||||
{
|
||||
"message": "// Klipper state: Ready",
|
||||
"time": 1615834104.3299904,
|
||||
"type": "response"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
////
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | :------: | ---------------------------------------------------------------- |
|
||||
| `gcode_store` | [object] | An array of [GCode Tracking Objects](#gc-tracking-obj-spec). |
|
||||
| | | The array is a FIFO queue with the oldest item being at index 0. |^
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :----: | ------------------------------------------------------------------ |
|
||||
| `message` | string | The GCode Message associated with ths object. |
|
||||
| `time` | float | The time at which the message was received reported in Unix Time. |
|
||||
| `type` | string | The message type. Can be `command` or `response`. Commands are |
|
||||
| | | only tracked when received through Moonraker's gcode API endpoint. |^
|
||||
{ #gc-tracking-obj-spec } GCode Tracking Object
|
||||
|
||||
///
|
||||
|
||||
## Rollover Logs
|
||||
|
||||
Requests a manual rollover for log files registered with Moonraker's
|
||||
log management facility. Currently these are limited to `moonraker.log`
|
||||
and `klippy.log`.
|
||||
|
||||
/// Warning
|
||||
Moonraker must be able to manage Klipper's systemd service to
|
||||
perform a manual rollover. The rollover will fail under the following
|
||||
conditions:
|
||||
|
||||
- Moonraker cannot detect Klipper's systemd unit
|
||||
- Moonraker cannot detect the location of Klipper's files
|
||||
- A print is in progress
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/logs/rollover
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"application": "moonraker"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.logs.rollover",
|
||||
"params": {
|
||||
"application": "moonraker"
|
||||
},
|
||||
"id": 4656
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| ------------- | :----: | ------- | ------------------------------------------------------- |
|
||||
| `application` | string | *all* | The name of the application for which the log should be |
|
||||
| | | | rolled over. Can be `moonraker` or `klipper`. When no |^
|
||||
| | | | value is specified all logs are rolled over. |^
|
||||
///
|
||||
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"rolled_over": [
|
||||
"moonraker",
|
||||
"klipper"
|
||||
],
|
||||
"failed": {}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| ------------- | :------: | -------------------------------------------------------- |
|
||||
| `rolled_over` | [string] | A list of application names successfully rolled over. |
|
||||
| `failed` | object | An object where the fields consist of applications names |
|
||||
| | | that failed the rollover procedure. The value assigned |^
|
||||
| | | to each field is an error message. |^
|
||||
///
|
||||
|
||||
|
||||
## Restart Server
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/restart
|
||||
```
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.restart",
|
||||
"id": 4656
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Identify Connection
|
||||
This method provides a way for applications with persistent connections
|
||||
to identify themselves to Moonraker. This information may be used by
|
||||
Moonraker perform an action or present information based on if a specific
|
||||
type of frontend is connected. Currently this method is only available
|
||||
to websocket and unix socket connections. Once this endpoint returns
|
||||
success it cannot be called again, repeated calls will result in an error.
|
||||
|
||||
```{.text .apirequest title="HTTP request"}
|
||||
Not Available
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC request (Websocket/Unix Socket Only)"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.connection.identify",
|
||||
"params": {
|
||||
"client_name": "moontest",
|
||||
"version": "0.0.1",
|
||||
"type": "web",
|
||||
"url": "http://github.com/arksine/moontest",
|
||||
"access_token": "<base64 encoded token>",
|
||||
"api_key": "<system API key>"
|
||||
},
|
||||
"id": 4656
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
| Name | Type | Default | Description |
|
||||
| -------------- | :----: | ------------ | -------------------------------------------------- |
|
||||
| `client_name` | string | **REQUIRED** | The name of the application identifying itself, |
|
||||
| | | | ie: `Mainsail`, `Fluidd`, `KlipperScreen`, etc. |^
|
||||
| `version` | string | **REQUIRED** | The version of the application identifying itself. |
|
||||
| `type` | string | **REQUIRED** | The type of the application. Expand for available |
|
||||
| | | | values. |^
|
||||
| | | | #valid-id-type-desc |+
|
||||
| `url` | string | **REQUIRED** | The project URL or homepage for the application. |
|
||||
| `access_token` | string | `null` | An optional JSON Web Token used to authenticate |
|
||||
| | | | the websocket connection. Only needed when the |^
|
||||
| | | | app uses JWT authentication and did not |^
|
||||
| | | | authenticate through the original Websocket |^
|
||||
| | | | Request. |^
|
||||
| `api_key` | string | `null` | An optional API Key used to authenticate the |
|
||||
| | | | connection. Only needed when the APP uses API |^
|
||||
| | | | Key authentication and did not authenticate |^
|
||||
| | | | through the original Websocket Request. |^
|
||||
|
||||
| Name | Description |
|
||||
| --------- | --------------------------------------------------------------- |
|
||||
| `web` | A web application like `Mainsail` and `Fluidd`. |
|
||||
| `mobile` | A mobile application like `Mobileraker`. |
|
||||
| `desktop` | A desktop application like `OrcaSlicer`. |
|
||||
| `display` | An application intended to drive displays like `KlipperScreen`. |
|
||||
| `bot` | An interactive bot like `MoonCord`. |
|
||||
| `agent` | An external extension like `Obico`. |
|
||||
| `other` | Anything that doesn't fit in to the above categories. |
|
||||
{: #valid-id-type-desc }
|
||||
|
||||
//// Note
|
||||
When identifying as an `agent`, only one instance should be connected
|
||||
to Moonraker at a time. If multiple agents of the same `client_name`
|
||||
attempt to identify themselves this endpoint will return an error.
|
||||
See the [extensions](./extensions.md) document for more information about
|
||||
`agents`.
|
||||
////
|
||||
|
||||
//// Tip
|
||||
See the authorization API documentation for details on JWT and API Key authentication.
|
||||
////
|
||||
///
|
||||
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"connection_id": 1730367696
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
| Field | Type | Description |
|
||||
| --------------- | :--: | ---------------------------------------- |
|
||||
| `connection_id` | int | A unique identifier for this connection. |
|
||||
///
|
||||
|
||||
## Get Websocket ID
|
||||
|
||||
!!! Warning
|
||||
This method is deprecated. Please use the
|
||||
[identify endpoint](#identify-connection) to retrieve the
|
||||
Websocket's UID
|
||||
|
||||
```{.text .apirequest title="HTTP request"}
|
||||
Not Available
|
||||
```
|
||||
|
||||
```{json .apirequest title="JSON-RPC request (Websocket/Unix Socket Only)"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.websocket.id",
|
||||
"id": 4656
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"websocket_id": 1730367696
|
||||
}
|
||||
```
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------------- | :--: | ---------------------------------------- |
|
||||
| `websocket_id` | int | A unique identifier for this connection. |
|
||||
///
|
||||
@@ -0,0 +1,770 @@
|
||||
# Update Management
|
||||
|
||||
The endpoints in the section are available when the `[update_manager]`
|
||||
component has been configured in `moonraker.conf`. They may be used
|
||||
to manage updates for Moonraker, Klipper, OS Packages, and additional
|
||||
software added through the configuration.
|
||||
|
||||
## Get update status
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /machine/update/status
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.status",
|
||||
"id": 4644
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| --------- | :--: | ------- | ----------------------------------------------- |
|
||||
| `refresh` | bool | false | *DEPRECATED*. When `true` an attempt will |
|
||||
| | | | be made to refresh all updaters. The refresh |^
|
||||
| | | | will abort under the following conditions:<BR/> |^
|
||||
| | | | - an update is in progress<BR/> |^
|
||||
| | | | - a print is in progress<BR/> |^
|
||||
| | | | - the update manager hasn't completed |^
|
||||
| | | | initialization<BR/> |^
|
||||
| | | | - a refresh has been performed within the last |^
|
||||
| | | | 60 seconds<BR/> |^
|
||||
|
||||
//// Note
|
||||
The `refresh` parameter is deprecated. Front end developers should use the
|
||||
[refresh endpoint](#refresh-update-status) to request a refresh.
|
||||
////
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json #status-example-response .apiresponse title="Example Response"}
|
||||
{
|
||||
"busy": false,
|
||||
"github_rate_limit": 60,
|
||||
"github_requests_remaining": 57,
|
||||
"github_limit_reset_time": 1615836932,
|
||||
"version_info": {
|
||||
"system": {
|
||||
"name": "system",
|
||||
"configured_type": "system",
|
||||
"package_count": 4,
|
||||
"package_list": [
|
||||
"libtiff5",
|
||||
"raspberrypi-sys-mods",
|
||||
"rpi-eeprom-images",
|
||||
"rpi-eeprom"
|
||||
]
|
||||
},
|
||||
"moonraker": {
|
||||
"channel": "dev",
|
||||
"debug_enabled": true,
|
||||
"is_valid": true,
|
||||
"configured_type": "git_repo",
|
||||
"corrupt": false,
|
||||
"info_tags": [],
|
||||
"detected_type": "git_repo",
|
||||
"name": "moonraker",
|
||||
"remote_alias": "arksine",
|
||||
"branch": "master",
|
||||
"owner": "arksine",
|
||||
"repo_name": "moonraker",
|
||||
"version": "v0.7.1-364",
|
||||
"remote_version": "v0.7.1-364",
|
||||
"rollback_version": "v0.7.1-360",
|
||||
"current_hash": "ecfad5cff15fff1d82cb9bdc64d6b548ed53dfaf",
|
||||
"remote_hash": "ecfad5cff15fff1d82cb9bdc64d6b548ed53dfaf",
|
||||
"is_dirty": false,
|
||||
"detached": true,
|
||||
"commits_behind": [],
|
||||
"git_messages": [],
|
||||
"full_version_string": "v0.7.1-364-gecfad5c",
|
||||
"pristine": true,
|
||||
"recovery_url": "https://github.com/Arksine/moonraker.git",
|
||||
"remote_url": "https://github.com/Arksine/moonraker.git",
|
||||
"warnings": [],
|
||||
"anomalies": [
|
||||
"Unofficial remote url: https://github.com/Arksine/moonraker-fork.git",
|
||||
"Repo not on official remote/branch, expected: origin/master, detected: altremote/altbranch",
|
||||
"Detached HEAD detected"
|
||||
]
|
||||
},
|
||||
"mainsail": {
|
||||
"name": "mainsail",
|
||||
"owner": "mainsail-crew",
|
||||
"version": "v2.1.1",
|
||||
"remote_version": "v2.1.1",
|
||||
"rollback_version": "v2.0.0",
|
||||
"configured_type": "web",
|
||||
"channel": "stable",
|
||||
"info_tags": [
|
||||
"desc=Mainsail Web Client",
|
||||
"action=some_action"
|
||||
],
|
||||
"warnings": [],
|
||||
"anomalies": [],
|
||||
"is_valid": true
|
||||
},
|
||||
"fluidd": {
|
||||
"name": "fluidd",
|
||||
"owner": "fluidd-core",
|
||||
"version": "v1.16.2",
|
||||
"remote_version": "v1.16.2",
|
||||
"rollback_version": "v1.15.0",
|
||||
"configured_type": "web",
|
||||
"channel": "beta",
|
||||
"info_tags": [],
|
||||
"warnings": [],
|
||||
"anomalies": [],
|
||||
"is_valid": true
|
||||
},
|
||||
"klipper": {
|
||||
"channel": "dev",
|
||||
"debug_enabled": true,
|
||||
"is_valid": true,
|
||||
"configured_type": "git_repo",
|
||||
"corrupt": false,
|
||||
"info_tags": [],
|
||||
"detected_type": "git_repo",
|
||||
"name": "klipper",
|
||||
"remote_alias": "origin",
|
||||
"branch": "master",
|
||||
"owner": "Klipper3d",
|
||||
"repo_name": "klipper",
|
||||
"version": "v0.10.0-1",
|
||||
"remote_version": "v0.10.0-41",
|
||||
"rollback_version": "v0.9.1-340",
|
||||
"current_hash": "4c8d24ae03eadf3fc5a28efb1209ce810251d02d",
|
||||
"remote_hash": "e3cbe7ea3663a8cd10207a9aecc4e5458aeb1f1f",
|
||||
"is_dirty": false,
|
||||
"detached": false,
|
||||
"commits_behind": [
|
||||
{
|
||||
"sha": "e3cbe7ea3663a8cd10207a9aecc4e5458aeb1f1f",
|
||||
"author": "Kevin O'Connor",
|
||||
"date": "1644534721",
|
||||
"subject": "stm32: Clear SPE flag on a change to SPI CR1 register",
|
||||
"message": "The stm32 specs indicate that the SPE bit must be cleared before\nchanging the CPHA or CPOL bits.\n\nReported by @cbc02009 and @bigtreetech.\n\nSigned-off-by: Kevin O'Connor <kevin@koconnor.net>",
|
||||
"tag": null
|
||||
},
|
||||
{
|
||||
"sha": "99d55185a21703611b862f6ce4b80bba70a9c4b5",
|
||||
"author": "Kevin O'Connor",
|
||||
"date": "1644532075",
|
||||
"subject": "stm32: Wait for transmission to complete before returning from spi_transfer()",
|
||||
"message": "It's possible for the SCLK pin to still be updating even after the\nlast byte of data has been read from the receive pin. (In particular\nin spi mode 0 and 1.) Exiting early from spi_transfer() in this case\ncould result in the CS pin being raised before the final updates to\nSCLK pin.\n\nAdd an additional wait at the end of spi_transfer() to avoid this\nissue.\n\nSigned-off-by: Kevin O'Connor <kevin@koconnor.net>",
|
||||
"tag": null
|
||||
}
|
||||
],
|
||||
"git_messages": [],
|
||||
"full_version_string": "v0.10.0-1-g4c8d24ae-shallow",
|
||||
"pristine": true,
|
||||
"recovery_url": "https://github.com/Klipper3d/klipper.git",
|
||||
"remote_url": "https://github.com/Klipper3d/klipper.git",
|
||||
"warnings": [],
|
||||
"anomalies": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------------- | :----: | ----------------------------------------------------- |
|
||||
| `busy` | bool | Set to `true` if an update is currently in progress. |
|
||||
| `github_rate_limit` | int | The maximum number of GitHub API requests allowed. |
|
||||
| | | An unauthenticated user is typically allowed 60 |^
|
||||
| | | requests per hour. |^
|
||||
| `github_requests_remaining` | int | The number of GitHub API requests remaining until the |
|
||||
| | | reset time is reached. |^
|
||||
| `github_limit_reset_time` | int | The time when the rate limit will reset, reported in |
|
||||
| | | unix time. |^
|
||||
| `version_info` | object | A `Version Info` object containing the update status |
|
||||
| | | for each configured software updater. |^
|
||||
| | | #version-info-desc |+
|
||||
{ #update-status-spec }
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :----: | ---------------------------------------------------------- |
|
||||
| `system` | object | A [System Status](#system-status-spec) object. |
|
||||
| | | This field is only available when the `update_manager` is |^
|
||||
| | | configured to update system packages. |^
|
||||
| _updater_ | object | A `Status Update` object. There are multiple sub-types of |
|
||||
| | | status objects, the specific type can be determined by the |^
|
||||
| | | object's [configured_type](#configured-type-desc) field. |^
|
||||
| | | The `version_info` object may have multiple _updater_ |^
|
||||
| | | items. The field name for each updater will match the |^
|
||||
| | | object's `name`. |^
|
||||
{ #version-info-desc } Version Info
|
||||
|
||||
| Type | Description |
|
||||
| ---------- | ---------------------------------------------------------- |
|
||||
| `git_repo` | A [Git Repo Status](#git-repo-status-spec) object. |
|
||||
| | The software is distributed through a git repo on GitHub. |^
|
||||
| `web` | A [Net Hosted Status](#net-app-status-spec ) object. |
|
||||
| | The software is a web application. |^
|
||||
| | Updates are GitHub hosted releases packaged in a zip file. |^
|
||||
| `zip` | A [Net Hosted Status](#net-app-status-spec ) object. |
|
||||
| | The software is a local application, optionally installed |^
|
||||
| | as a system service. Updates are GitHub hosted releases |^
|
||||
| | packaged in a zip file. |^
|
||||
| `python` | A [Python Package Status](#python-status-spec) object. |
|
||||
| | The software is a Python Application installed in its own |^
|
||||
| | virtualenv. Updates may be hosted on PyPI or GitHub. |^
|
||||
| | Pip is used to deploy updates. |^
|
||||
| `system` | A [System Status](#system-status-spec) object. This type |
|
||||
| | is internally managed and only applicable to the system |^
|
||||
| | package manager. |^
|
||||
{ #configured-type-desc } Configured Types
|
||||
|
||||
| Field | Type | Description |
|
||||
| ---------------------- | :------: | -------------------------------------------------------- |
|
||||
| `name` | string | The name of the software to manage updates for. |
|
||||
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
|
||||
| `detected_type` | string | **DEPRECATED.** Will always report `git_repo`. |
|
||||
| `channel` | string | The configured update `channel`. |
|
||||
| | | #git-repo-channel-desc |+
|
||||
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
|
||||
| | | configuration is not supported by the type. Will |^
|
||||
| | | always be `false` for `git_repo` types as all channels |^
|
||||
| | | are supported. |^
|
||||
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
|
||||
| | | enabled. In this condition updates may proceed when the |^
|
||||
| | | repo's HEAD is detached. |^
|
||||
| `is_valid` | bool | Set to `true` when repo detection completes and passes |
|
||||
| | | all validity checks. |^
|
||||
| `version` | string | The current detected version. |
|
||||
| `remote_version` | string | The latest version available on the remote. |
|
||||
| `rollback_version` | string | The version prior to the last update. This version is |
|
||||
| | | used during a `rollback` request. |^
|
||||
| `full_version_string` | string | The complete version string reported by `git describe`. |
|
||||
| | | Generally includes an abbreviated hash of the current |^
|
||||
| | | commit and tags such as "dirty" when appropriate. |^
|
||||
| `remote_hash` | string | The latest available commit hash on the remote. |
|
||||
| `current_hash` | string | The commit hash the local repo is currently on. |
|
||||
| `remote_alias` | string | The git alias of the remote. The git default for the |
|
||||
| | | primary alias is `origin`. |^
|
||||
| `remote_url` | string | Full URL of the git remote matching the current |
|
||||
| | | `remote_alias`. |^
|
||||
| `recovery_url` | string | The `origin` git remote URL for this repo. This URL is |
|
||||
| | | used to perform a `hard recovery` when requested. |^
|
||||
| `owner` | string | The owner of the remote repo as detected from the remote |
|
||||
| | | URL. |^
|
||||
| `branch` | string | The name of the current git branch. |
|
||||
| `repo_name` | string | The name of the remote repo as detected from the remote |
|
||||
| | | URL. |^
|
||||
| `is_dirty` | bool | Set to `true` if the repo is "dirty", ie: if one or |
|
||||
| | | more files in the repo have been modified. |^
|
||||
| `corrupt` | bool | Set to `true` if the repo is corrupt. This indicates |
|
||||
| | | that the local repo is broken and needs to be recovered. |^
|
||||
| `pristine` | bool | Set to `true` when the repo is clean and no untracked |
|
||||
| | | files exist in the repo. |^
|
||||
| `detached` | bool | Set to `true` when the git repo's HEAD is detached. |
|
||||
| `git_messages` | [string] | An array of strings containing the output from a failed |
|
||||
| | | `git` command during initialization or an update. This |^
|
||||
| | | array will be empty if all `git` commands succeed. |^
|
||||
| `anomalies` | [string] | An array of strings that describe anomalies found during |
|
||||
| | | initialization. An anomaly can be defined as an |^
|
||||
| | | unexpected condition that does not result in an |^
|
||||
| | | `invalid` repo state. Updates may proceed when |^
|
||||
| | | anomalies are detected. An example of an anomaly is the |^
|
||||
| | | presence of "untracked files" in the repo. |^
|
||||
| `warnings` | [string] | An array of strings that describe warnings detected |
|
||||
| | | during repo initialization. When a warning is present |^
|
||||
| | | the repo is marked invalid and updates are disabled. |^
|
||||
| `commits_behind` | [object] | An array of `Commit Info` objects providing commit data |
|
||||
| | | on upstream commits available for update. This array is |^
|
||||
| | | limited to a size of 30 untagged commits. Any tagged |^
|
||||
| | | commits within 100 commits behind are included. |^
|
||||
| | | #git-commit-info-spec |+
|
||||
| `commits_behind_count` | int | The total number of commits the current repo is behind |
|
||||
| | | the next update. This number may be greater than the |^
|
||||
| | | length of the `commits_behind` array. |^
|
||||
| `info_tags` | object | An object containing custom tags added to the updater's |
|
||||
| | | configuration in `moonraker.conf`. The values will |^
|
||||
| | | always be strings. Client developers may define what |^
|
||||
| | | tags, if any, users will configure. The software can |^
|
||||
| | | then choose to display information or perform a |^
|
||||
| | | specific action pre/post update if necessary. |^
|
||||
{ #git-repo-status-spec } Git Repo Status
|
||||
|
||||
| Channel | Description |
|
||||
| -------- | --------------------------------------------------------- |
|
||||
| `stable` | The repo will update to the latest tagged stable release. |
|
||||
| `beta` | The repo will update to the latest tag. This may include |
|
||||
| | tags with `beta` and `release candidate` identifiers. |^
|
||||
| `dev` | The repo will update to the latest available commit. |
|
||||
{ #git-repo-channel-desc }
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :------------: | ----------------------------------------------------- |
|
||||
| `author` | string | The author of the commit. |
|
||||
| `date` | string | The date of the commit in unix time. Note that the |
|
||||
| | | date is extracted from the git log as a string value. |^
|
||||
| | | It should be converted to an integer prior to |^
|
||||
| | | processing from unix time. |^
|
||||
| `sha` | string | The commit hash. |
|
||||
| `subject` | string | The title of the commit. |
|
||||
| `message` | string | The content in the body of the commit. |
|
||||
| `tag` | string \| null | The name of the associated tag if present. Will be |
|
||||
| | | null if the commit has no tag. |^
|
||||
{ #git-commit-info-spec } Commit Info
|
||||
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------ | :------: | -------------------------------------------------------- |
|
||||
| `name` | string | The name of the software to manage updates for. |
|
||||
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
|
||||
| `channel` | string | The configured update `channel`. |
|
||||
| | | #net-hosted-channel-desc |+
|
||||
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
|
||||
| | | configuration is not supported by the type. |^
|
||||
| | | are supported. |^
|
||||
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
|
||||
| | | enabled. |^
|
||||
| `owner` | string | The owner of the GitHub repo hosting the software. |
|
||||
| `repo_name` | string | The name of the GitHub repo hosting the software. |
|
||||
| `last_error` | string | A message associated with the last error encountered |
|
||||
| | | after initialization or an update. Will be an empty |^
|
||||
| | | string if no errors were detected. |^
|
||||
| `version` | string | The current detected version. |
|
||||
| `remote_version` | string | The version of the latest available release on GitHub. |
|
||||
| `rollback_version` | string | The version prior to the last update. This version is |
|
||||
| | | used during a `rollback` request. |^
|
||||
| `is_valid` | bool | Set to `true` when the updater has completed |
|
||||
| | | initialization and all validity checks passed. |^
|
||||
| `anomalies` | [string] | An array of strings that describe anomalies found during |
|
||||
| | | initialization. An anomaly can be defined as an |^
|
||||
| | | unexpected condition that does not result in an |^
|
||||
| | | `invalid` updater state. Updates may proceed when |^
|
||||
| | | anomalies are detected. |^
|
||||
| `warnings` | [string] | An array of strings that describe warnings detected |
|
||||
| | | during initialization. When a warning is present |^
|
||||
| | | the updater is marked invalid and updates are disabled. |^
|
||||
| `info_tags` | object | An object containing custom tags added to the updater's |
|
||||
| | | configuration in `moonraker.conf`. The values will |^
|
||||
| | | always be strings. Client developers may define what |^
|
||||
| | | tags, if any, users will configure. The software can |^
|
||||
| | | then choose to display information or perform a |^
|
||||
| | | specific action pre/post update if necessary. |^
|
||||
{ #net-app-status-spec } Net Hosted Status
|
||||
|
||||
| Channel | Description |
|
||||
| -------- | --------------------------------------------------------- |
|
||||
| `stable` | The software will update to the stable release on GitHub. |
|
||||
| `beta` | The software will update to the latest release on GitHub, |
|
||||
| | including those marked as "pre-release". |^
|
||||
{ #net-hosted-channel-desc }
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------------------- | :------------: | --------------------------------------------------------- |
|
||||
| `name` | string | The name of the software to manage updates for. |
|
||||
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
|
||||
| `channel` | string | The configured update `channel`. |
|
||||
| | | #python-channel-desc |+
|
||||
| `channel_invalid` | bool | A value of `true` indicates that the current `channel` |
|
||||
| | | configuration is not supported by the type. |^
|
||||
| | | are supported. |^
|
||||
| `debug_enabled` | bool | Set to `true` when Moonraker's debug features are |
|
||||
| | | enabled. |^
|
||||
| `owner` | string | The owner of the GitHub repo hosting the software. |
|
||||
| | | Will be a `?` when no repo owner is detected. |^
|
||||
| `repo_name` | string | The name of the GitHub repo hosting the software. |
|
||||
| | | Will be a `?` when no repo name is detected. |^
|
||||
| `branch` | string \| null | The name of the branch on the GitHub remote to build |
|
||||
| | | `dev` updates from. Will be `null` if no primary branch |^
|
||||
| | | is configured. |^
|
||||
| `version` | string | The current detected version. |
|
||||
| `remote_version` | string | The version of the latest available release on GitHub. |
|
||||
| `rollback_version` | string | The version prior to the last update. This version is |
|
||||
| | | used during a `rollback` request. |^
|
||||
| `full_version_string` | string | The complete version string extracted from the python |
|
||||
| | | package's metadata. |^
|
||||
| `current_hash` | string | The hash of the commit used to build the current version |
|
||||
| | | of the package. A placeholder of `not-specified` is used |^
|
||||
| | | when the the current hash is not provided in the package |^
|
||||
| | | metadata. |^
|
||||
| `remote_hash` | string | The hash of the latest update available. A placeholder of |
|
||||
| | | `update-available` is used when the remote hash is not |^
|
||||
| | | provided by the remote host and updates are available. |^
|
||||
| `is_valid` | bool | Set to `true` when the updater has completed |
|
||||
| | | initialization and all validity checks passed. |^
|
||||
| `is_dirty` | bool | Set to `true` if the repo was modified at the time the |
|
||||
| | | package was built. |^
|
||||
| `changelog_url` | string | A URL to the software's changelog. Will be an empty |
|
||||
| | | string if no changelog URL is detected. |^
|
||||
| `anomalies` | [string] | An array of strings that describe anomalies found during |
|
||||
| | | initialization. An anomaly can be defined as an |^
|
||||
| | | unexpected condition that does not result in an |^
|
||||
| | | `invalid` updater state. Updates may proceed when |^
|
||||
| | | anomalies are detected. |^
|
||||
| `warnings` | [string] | An array of strings that describe warnings detected |
|
||||
| | | during initialization. When a warning is present |^
|
||||
| | | the updater is marked invalid and updates are disabled. |^
|
||||
| `info_tags` | object | An object containing custom tags added to the updater's |
|
||||
| | | configuration in `moonraker.conf`. The values will |^
|
||||
| | | always be strings. Client developers may define what |^
|
||||
| | | tags, if any, users will configure. The software can |^
|
||||
| | | then choose to display information or perform a |^
|
||||
| | | specific action pre/post update if necessary. |^
|
||||
{ #python-status-spec } Python Package Status
|
||||
|
||||
| Channel | Description |
|
||||
| -------- | -------------------------------------------------------- |
|
||||
| `stable` | The software will update to the stable release on GitHub |
|
||||
| | or PyPI. |^
|
||||
| `beta` | Only applies to packages installed via GitHub. The |
|
||||
| | software will update to the latest release, including |^
|
||||
| | hose marked as "pre-release". |^
|
||||
| `dev` | Only applies to packages installed via GitHub. The |
|
||||
| | software will update to the latest commit available. |^
|
||||
{ #python-channel-desc }
|
||||
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------------- | :------: | -------------------------------------------------------- |
|
||||
| `name` | string | The name of the software to manage updates for. Will |
|
||||
| | | always be `system`. |^
|
||||
| `configured_type` | string | The [type](#configured-type-desc) of updater configured. |
|
||||
| | | Will always be `system`. |^
|
||||
| `package_count` | int | The number of system packages that require updating. |
|
||||
| `package_list` | [string] | An array of package names that require updating. |
|
||||
{ #system-status-spec } System Update Status
|
||||
|
||||
///
|
||||
|
||||
## Refresh update status
|
||||
|
||||
Refreshes the internal update state for the requested software.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/refresh
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "klipper"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.refresh",
|
||||
"params": {
|
||||
"name": "klipper"
|
||||
},
|
||||
"id": 4644
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------- | ----------------------------------------------------- |
|
||||
| `name` | string | `null` | The name of the software to refresh. |
|
||||
| | | | If omitted all registered software will be refreshed. |^
|
||||
|
||||
///
|
||||
|
||||
/// Note
|
||||
This endpoint will raise 503 error under the following conditions:
|
||||
|
||||
- An update is in progress
|
||||
- A print is in progress
|
||||
- The update manager hasn't completed initialization
|
||||
///
|
||||
|
||||
For an example response refer to the
|
||||
[Status Example Response](#status-example-response).
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
The response spec is identical to the
|
||||
[Status Request Specification](#update-status-spec)
|
||||
///
|
||||
|
||||
/// Tip
|
||||
Applications should use care when calling this method as a refresh
|
||||
is CPU intensive and may be time consuming. Moonraker can be
|
||||
configured to refresh state periodically, thus it is recommended
|
||||
that applications avoid their own procedural implementations.
|
||||
Instead it is best to call this API only when a user requests a
|
||||
refresh.
|
||||
///
|
||||
|
||||
## Perform an Upgrade
|
||||
|
||||
*Added in API Version 1.5.0*
|
||||
|
||||
Upgrade to the most recent release of the requested software.
|
||||
If an update is requested while a print is in progress then this
|
||||
request will return an error.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/upgrade
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "app_name"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.upgrade",
|
||||
"params": {
|
||||
"name": "app_name"
|
||||
},
|
||||
"id": 8546
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------- | ------------------------------------ |
|
||||
| `name` | string | null | The name of the software to upgrade. |
|
||||
| | | | If omitted all registered |^
|
||||
| | | | software updates will be upgraded. |^
|
||||
|
||||
///
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Recover a corrupt repo
|
||||
|
||||
On occasion a git command may fail resulting in a repo in a
|
||||
dirty or invalid state. This endpoint may be used to attempt
|
||||
to recover a git repo that is dirty, broken, or corrupt.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/recover
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "moonraker",
|
||||
"hard": false
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.recover",
|
||||
"params": {
|
||||
"name": "moonraker",
|
||||
"hard": false
|
||||
},
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------------ | --------------------------------------------------- |
|
||||
| `name` | string | **REQUIRED** | The name of the software to recover. |
|
||||
| `hard` | bool | false | Determines the [mode](#git-repo-recovery-mode-desc) |
|
||||
| | | | used to perform the recovery. |^
|
||||
|
||||
| Name | Description |
|
||||
| --------------- | ------------------------------------------------------- |
|
||||
| `hard == false` | Moonraker will attempt to recover the repo by running |
|
||||
| | `git reset`. This will generally work for repos that |^
|
||||
| | are dirty, but will not correct repos that are corrupt. |^
|
||||
| `hard == true` | Moonraker will remove the current repo and re-clone it. |
|
||||
{ #git-repo-recovery-mode-desc } Recovery Modes
|
||||
|
||||
///
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Rollback to the previous version
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/rollback
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "moonraker"
|
||||
}
|
||||
```
|
||||
|
||||
JSON-RPC request:
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.rollback",
|
||||
"params": {
|
||||
"name": "moonraker"
|
||||
},
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Perform a full update
|
||||
|
||||
*Deprecated in API Version 1.5.0, superseded by the*
|
||||
*[Upgrade](#perform-an-upgrade) endpoint.*
|
||||
|
||||
Attempts to update all registered software. Updates are performed in the
|
||||
following order:
|
||||
|
||||
- `system` if enabled
|
||||
- All optional software configured in `moonraker.conf`.
|
||||
- Klipper
|
||||
- Moonraker
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/full
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.full",
|
||||
"id": 4645
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Update Moonraker
|
||||
|
||||
*Deprecated in API Version 1.5.0, superseded by the*
|
||||
*[Upgrade](#perform-an-upgrade) endpoint.*
|
||||
|
||||
Upgrades to the latest version of Moonraker and restarts
|
||||
the service. If an update is requested while a print is in progress then
|
||||
this request will return an error.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/moonraker
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.moonraker",
|
||||
"id": 4645
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Update Klipper
|
||||
|
||||
*Deprecated in API Version 1.5.0, superseded by the*
|
||||
*[Upgrade](#perform-an-upgrade) endpoint.*
|
||||
|
||||
Upgrades to the latest version of Klipper and restarts
|
||||
the service. If an update is requested while a print is in progress
|
||||
then this request will return an error.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/klipper
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.klipper",
|
||||
"id": 5745
|
||||
}
|
||||
```
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Update Client
|
||||
|
||||
*Deprecated in API Version 1.5.0, superseded by the*
|
||||
*[Upgrade](#perform-an-upgrade) endpoint.*
|
||||
|
||||
Update to the most recent release of the requested software.
|
||||
If an update is requested while a print is in progress then this
|
||||
request will return an error.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/client
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "app_name"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.client",
|
||||
"params": {
|
||||
"name": "app_name"
|
||||
},
|
||||
"id": 8546
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | ------- | ------------------------------------ |
|
||||
| `name` | string | null | The name of the software to upgrade. |
|
||||
| | | | If omitted all registered |^
|
||||
| | | | software updates will be upgraded. |^
|
||||
|
||||
///
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
## Update System Packages
|
||||
|
||||
*Deprecated in API Version 1.5.0, superseded by the*
|
||||
*[Upgrade](#perform-an-upgrade) endpoint.*
|
||||
|
||||
Upgrades system packages. If an update is requested while a print is
|
||||
in progress then this request will return an error.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /machine/update/system
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "machine.update.system",
|
||||
"id": 4564
|
||||
}
|
||||
```
|
||||
|
||||
```{.text .apiresponse title="Response"}
|
||||
"ok"
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
# Webcam Management
|
||||
|
||||
Moonraker maintains webcam configuration in its database so
|
||||
various applications and front-ends can share this configuration
|
||||
through a consistent interface. The endpoints in this section
|
||||
may be used to manage various webcam configurations.
|
||||
|
||||
/// note
|
||||
Moonraker does not directly manipulate webcams.
|
||||
External applications, such as
|
||||
[crowsnest](https://github.com/mainsail-crew/crowsnest),
|
||||
handle direct webcam functionality.
|
||||
///
|
||||
|
||||
## List Webcams
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/webcams/list
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.webcams.list",
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"webcams": [
|
||||
{
|
||||
"name": "testcam3",
|
||||
"location": "door",
|
||||
"service": "mjpegstreamer",
|
||||
"enabled": true,
|
||||
"icon": "mdiWebcam",
|
||||
"target_fps": 20,
|
||||
"target_fps_idle": 5,
|
||||
"stream_url": "http://camera.lan/webcam?action=stream",
|
||||
"snapshot_url": "http://camera.lan/webcam?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": true,
|
||||
"rotation": 90,
|
||||
"aspect_ratio": "4:3",
|
||||
"extra_data": {},
|
||||
"source": "config",
|
||||
"uid": "55d3801e-fdc1-438d-8728-2fff8b83b909"
|
||||
},
|
||||
{
|
||||
"name": "tc2",
|
||||
"location": "printer",
|
||||
"service": "mjpegstreamer",
|
||||
"enabled": true,
|
||||
"icon": "mdiWebcam",
|
||||
"target_fps": 15,
|
||||
"target_fps_idle": 5,
|
||||
"stream_url": "http://printer.lan/webcam?action=stream",
|
||||
"snapshot_url": "http://printer.lan/webcam?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": false,
|
||||
"rotation": 0,
|
||||
"aspect_ratio": "4:3",
|
||||
"extra_data": {},
|
||||
"source": "database",
|
||||
"uid": "65e51c8a-6763-41d4-8e76-345bb6e8e7c3"
|
||||
},
|
||||
{
|
||||
"name": "TestCam",
|
||||
"location": "printer",
|
||||
"service": "mjpegstreamer",
|
||||
"enabled": true,
|
||||
"icon": "mdiWebcam",
|
||||
"target_fps": 15,
|
||||
"target_fps_idle": 5,
|
||||
"stream_url": "/webcam/?action=stream",
|
||||
"snapshot_url": "/webcam/?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": false,
|
||||
"rotation": 0,
|
||||
"aspect_ratio": "4:3",
|
||||
"extra_data": {},
|
||||
"source": "database",
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| --------- | :------: | ------------------------------------------------------- |
|
||||
| `webcams` | [object] | An array of [Webcam Entry](#webcam-entry-spec) objects. |
|
||||
|
||||
| Field | Type | Description |
|
||||
| ----------------- | :----: | ------------------------------------------------------------- |
|
||||
| `name` | string | Friendly name of the webcam. |
|
||||
| `location` | string | A single word description of where the webcam |
|
||||
| | | is located or what it is viewing. |^
|
||||
| `service` | string | The name of the webcam streaming service used to |
|
||||
| | | operate the webcam. |^
|
||||
| `enabled` | bool | Set to `true` when the webcam is available, `false` |
|
||||
| | | otherwise. |^
|
||||
| `icon` | string | Name of the icon associated with the webcam. |
|
||||
| `target_fps` | int | Target frames per second when the printer is active. |
|
||||
| `target_fps_idle` | int | Target frames per second when the printer is idle. |
|
||||
| `stream_url` | string | The url for the webcam's stream request. This may |
|
||||
| | | be a complete url, or a url path relative to |^
|
||||
| | | Moonraker's host. |^
|
||||
| `snapshot_url` | string | The url for the webcam's snapshot request. This may |
|
||||
| | | be a complete url, or a url path relative to |^
|
||||
| | | Moonraker's host. If the webcam does not support |^
|
||||
| | | a snapshot url this will be an empty string. |^
|
||||
| `flip_horizontal` | bool | A value of `true` indicates that the stream should |
|
||||
| | | be flipped horizontally. |^
|
||||
| `flip_vertical` | bool | A value of `true` indicates that the stream should |
|
||||
| | | be flipped vertically. |^
|
||||
| `rotation` | int | Indicates the amount of clockwise rotation, in |
|
||||
| | | degrees, that should be applied to the stream. May |^
|
||||
| | | be 0, 90, 180, or 270. |^
|
||||
| `aspect_ratio` | string | Indicates the aspect ratio of the stream. The format |
|
||||
| | | should be `W:H`, for example `4:3` or `16:9`. |^
|
||||
| `extra_data` | object | An object containing custom configuration added by |
|
||||
| | | frontends. |^
|
||||
| `source` | string | The [configuration source](#webcam-configuration-source-desc) |
|
||||
| | | of the webcam entry. |^
|
||||
| `uid` | string | A unique identifier assigned to the webcam entry. |
|
||||
{ #webcam-entry-spec } Webcam Entry
|
||||
|
||||
| Source | Description |
|
||||
| ---------- | -------------------------------------------------------------- |
|
||||
| `database` | The webcam's configuration is stored in Moonraker's database. |
|
||||
| | These entries are generally added by front-ends via the webcam |^
|
||||
| | API. Front-ends may modify and remove these entries. |^
|
||||
| `config` | The webcam's configuration is sourced from `moonraker.conf`. |
|
||||
| | The webcam endpoints can not modify or remove these entries. |^
|
||||
{ #webcam-configuration-source-desc } Configuration Source
|
||||
|
||||
//// note
|
||||
Moonraker does not provide a specification for the `location`, `service`,
|
||||
and `icon` fields. These fields can contain any string value, generally
|
||||
front-ends set these values based on their needs. Developers should
|
||||
consider using the same values that existing front-ends (such as Mainsail
|
||||
and Fluidd) currently use to maintain compatibility.
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
## Get Webcam Information
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
GET /server/webcams/item?uid=341778f9-387f-455b-8b69-ff68442d41d9
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.webcams.get_item",
|
||||
"params": {
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | -------------- | ----------------------------------------------- |
|
||||
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
|
||||
| | | | this parameter is considered required, if |^
|
||||
| | | | omitted the request will fall back on looking |^
|
||||
| | | | up the camera by `name`. |^
|
||||
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
|
||||
| | | | parameter is deprecated, all future |^
|
||||
| | | | implementations should use the `uid` parameter. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"webcam": {
|
||||
"name": "TestCam",
|
||||
"location": "printer",
|
||||
"service": "mjpegstreamer",
|
||||
"enabled": true,
|
||||
"icon": "mdiWebcam",
|
||||
"target_fps": 15,
|
||||
"target_fps_idle": 5,
|
||||
"stream_url": "/webcam/?action=stream",
|
||||
"snapshot_url": "/webcam/?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": false,
|
||||
"rotation": 0,
|
||||
"aspect_ratio": "4:3",
|
||||
"extra_data": {},
|
||||
"source": "database",
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :----: | ----------------------------------------------- |
|
||||
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
|
||||
| | | the requested webcam. |^
|
||||
|
||||
///
|
||||
|
||||
## Add or update a webcam
|
||||
|
||||
Adds a new webcam entry or updates an existing entry. When updating
|
||||
an entry only the fields provided will be modified.
|
||||
|
||||
/// Note
|
||||
A webcam configured in `moonraker.conf` cannot be updated or
|
||||
overwritten using this API.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/webcams/item
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "cam_name",
|
||||
"snapshot_url": "http://printer.lan:8080/webcam?action=snapshot",
|
||||
"stream_url": "http://printer.lan:8080/webcam?action=stream"
|
||||
}
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.webcams.post_item",
|
||||
"params": {
|
||||
"name": "cam_name",
|
||||
"snapshot_url": "/webcam?action=snapshot",
|
||||
"stream_url": "/webcam?action=stream"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
//// note
|
||||
The default values in the parameter specification below apply to *new* webcam
|
||||
entries. Existing entries to be updated only require the `uid` parameter,
|
||||
all other parameters default to their existing value.
|
||||
////
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------------- | :----: | --------------- | ---------------------------------------------------- |
|
||||
| `uid` | string | null | The unique ID of an existing Webcam Entry to |
|
||||
| | | | modify. If omitted the request will attempt |^
|
||||
| | | | to create a new Webcam Entry, otherwise the |^
|
||||
| | | | existing entry will be updated. |^
|
||||
| `name` | string | **REQUIRED** | The friendly name of the webcam. Each webcam |
|
||||
| | | | entry must have a *unique* name. |^
|
||||
| `location` | string | "printer" | A single word description of where the webcam |
|
||||
| | | | is located or what it is viewing. |^
|
||||
| `icon` | string | "mdiWebcam" | Name of the icon associated with the webcam. |
|
||||
| `enabled` | bool | true | Set to `true` when the webcam is available, `false` |
|
||||
| | | | otherwise. |^
|
||||
| `service` | string | "mjpegstreamer" | The name of the webcam streaming service used to |
|
||||
| | | | operate the webcam. |^
|
||||
| `target_fps` | int | 15 | Target frames per second when the printer is active. |
|
||||
| `target_fps_idle` | int | 5 | Target frames per second when the printer is idle. |
|
||||
| `stream_url` | string | **REQUIRED** | The url for the webcam's stream request. This may |
|
||||
| | | | be a complete url or a url path relative to |^
|
||||
| | | | Moonraker's host. |^
|
||||
| `snapshot_url` | string | "" | The url for the webcam's snapshot request. This may |
|
||||
| | | | be a complete url or a url path relative to |^
|
||||
| | | | Moonraker's host. |^
|
||||
| `flip_horizontal` | bool | false | A value of `true` indicates that the stream should |
|
||||
| | | | be flipped horizontally. |^
|
||||
| `flip_vertical` | bool | false | A value of `true` indicates that the stream should |
|
||||
| | | | be flipped vertically. |^
|
||||
| `rotation` | int | 0 | Indicates the amount of clockwise rotation, in |
|
||||
| | | | degrees, that should be applied to the stream. May |^
|
||||
| | | | be 0, 90, 180, or 270. |^
|
||||
| `aspect_ratio` | string | "4:3" | Indicates the aspect ratio of the stream. The format |
|
||||
| | | | should be `W:H`, for example `4:3` or `16:9`. |^
|
||||
| `extra_data` | object | {} | An object containing custom configuration added by |
|
||||
| | | | frontends. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"webcam": {
|
||||
"name": "TestCam",
|
||||
"location": "printer",
|
||||
"service": "mjpegstreamer",
|
||||
"enabled": true,
|
||||
"icon": "mdiWebcam",
|
||||
"target_fps": 15,
|
||||
"target_fps_idle": 5,
|
||||
"stream_url": "/webcam/?action=stream",
|
||||
"snapshot_url": "/webcam/?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": false,
|
||||
"rotation": 0,
|
||||
"aspect_ratio": "4:3",
|
||||
"extra_data": {},
|
||||
"source": "database",
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :----: | ----------------------------------------------- |
|
||||
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
|
||||
| | | the new or updated webcam. |^
|
||||
|
||||
///
|
||||
|
||||
## Delete a webcam
|
||||
|
||||
/// Note
|
||||
A webcam configured via `moonraker.conf` cannot be deleted
|
||||
using this API.
|
||||
///
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
DELETE /server/webcams/item?uid=341778f9-387f-455b-8b69-ff68442d41d9
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.webcams.delete_item",
|
||||
"params": {
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | -------------- | ----------------------------------------------- |
|
||||
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
|
||||
| | | | this parameter is considered required, if |^
|
||||
| | | | omitted the request will fall back on looking |^
|
||||
| | | | up the camera by `name`. |^
|
||||
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
|
||||
| | | | parameter is deprecated, all future |^
|
||||
| | | | implementations should use the `uid` parameter. |^
|
||||
|
||||
///
|
||||
|
||||
|
||||
Parameters:
|
||||
|
||||
- `uid`: The webcam's assigned unique ID. This parameter is optional, when
|
||||
not specified the request will fallback to the `name` parameter.
|
||||
- `name`: The name of the webcam to delete. If the named webcam is not
|
||||
available the request will return with an error. This parameter must
|
||||
be provided when the `uid` is omitted.
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"webcam": {
|
||||
"name": "TestCam",
|
||||
"location": "printer",
|
||||
"service": "mjpegstreamer",
|
||||
"target_fps": 15,
|
||||
"stream_url": "/webcam/?action=stream",
|
||||
"snapshot_url": "/webcam/?action=snapshot",
|
||||
"flip_horizontal": false,
|
||||
"flip_vertical": false,
|
||||
"rotation": 0,
|
||||
"source": "database",
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
}
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------- | :----: | ----------------------------------------------- |
|
||||
| `webcam` | object | A [Webcam Entry](#webcam-entry-spec) object for |
|
||||
| | | the deleted webcam. |^
|
||||
|
||||
///
|
||||
|
||||
|
||||
## Test a webcam
|
||||
|
||||
Resolves a webcam's stream and snapshot urls. If the snapshot
|
||||
is served over http, a test is performed to see if the url is
|
||||
reachable.
|
||||
|
||||
```{.http .apirequest title="HTTP Request"}
|
||||
POST /server/webcams/test?uid=341778f9-387f-455b-8b69-ff68442d41d9
|
||||
```
|
||||
|
||||
```{.json .apirequest title="JSON-RPC Request"}
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "server.webcams.test",
|
||||
"params": {
|
||||
"uid": "341778f9-387f-455b-8b69-ff68442d41d9"
|
||||
},
|
||||
"id": 4654
|
||||
}
|
||||
```
|
||||
|
||||
/// api-parameters
|
||||
open: True
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ------ | :----: | -------------- | ----------------------------------------------- |
|
||||
| `uid` | string | **REQUIRED** | The requested webcam's unique ID. While |
|
||||
| | | | this parameter is considered required, if |^
|
||||
| | | | omitted the request will fall back on looking |^
|
||||
| | | | up the camera by `name`. |^
|
||||
| `name` | string | **DEPRECATED** | The requested webcam's friendly name. This |
|
||||
| | | | parameter is deprecated, all future |^
|
||||
| | | | implementations should use the `uid` parameter. |^
|
||||
|
||||
///
|
||||
|
||||
/// collapse-code
|
||||
```{.json .apiresponse title="Example Response"}
|
||||
{
|
||||
"name": "TestCam",
|
||||
"snapshot_reachable": true,
|
||||
"snapshot_url": "http://127.0.0.1:80/webcam/?action=snapshot",
|
||||
"stream_url": "http://127.0.0.1:80/webcam/?action=stream"
|
||||
}
|
||||
```
|
||||
///
|
||||
|
||||
/// api-response-spec
|
||||
open: True
|
||||
|
||||
| Field | Type | Description |
|
||||
| -------------------- | :----: | ------------------------------------------ |
|
||||
| `name` | string | The friendly name of the webcam tested. |
|
||||
| `snapshot_reachable` | bool | Value will be `true` if Moonraker is able |
|
||||
| | | to successfully resolve and connect to the |^
|
||||
| | | snapshot url. |^
|
||||
| `snapshot_url` | string | The resolved snapshot url. |
|
||||
| `stream_url` | string | The resolved stream url. |
|
||||
|
||||
///
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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). Communication 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.
|
||||
|
||||
Front end and other client developers may refer to the
|
||||
[External API](./external_api/introduction.md)
|
||||
documentation.
|
||||
|
||||
Backend developers should refer to the
|
||||
[contributing](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.
|
||||
+708
-104
@@ -1,19 +1,44 @@
|
||||
## Installation
|
||||
#
|
||||
|
||||
This document provides a guide on how to install Moonraker on a Raspberry
|
||||
Pi running Raspian/Rasperry Pi OS. Other SBCs and/or linux distributions
|
||||
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.
|
||||
This document provides a guide on how to install Moonraker on a Debian
|
||||
based Linux Distributions. Other linux distributions 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. After installation you should make
|
||||
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
|
||||
[Klipper's Documentation](https://klipper3d.com/Overview.html) for details.
|
||||
After installing Klipper you should make sure to add Moonraker's
|
||||
[configuration requirements](#klipper-configuration-requirements).
|
||||
|
||||
After Klipper is installed, you need to modify its "default" file. This file
|
||||
contains klipper's command line arguments, and you must add an argument that
|
||||
instructs Klippy to create a Unix Domain socket:
|
||||
### Klipper Configuration Requirements
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
|
||||
- `[virtual_sdcard]`
|
||||
- `[pause_resume]`
|
||||
- `[display_status]`
|
||||
|
||||
If you have a `[filament_switch_sensor]` configured then `[pause_resume]` will
|
||||
automatically be loaded. Likewise, if you have a `[display]` configured then
|
||||
`[display_status]` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to `printer.cfg`:
|
||||
```ini
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/printer_data/gcodes
|
||||
```
|
||||
|
||||
### Enabling Klipper's Unix Domain Socket Server
|
||||
|
||||
After Klipper is installed it may be necessary to modify its `defaults` file in
|
||||
order to enable the Unix Domain Socket. Begin by opening the file in your
|
||||
editor of choice, for example:
|
||||
```
|
||||
sudo nano /etc/default/klipper
|
||||
```
|
||||
@@ -28,7 +53,7 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
|
||||
```
|
||||
|
||||
You need to add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
Add `-a /home/pi/printer_data/comms/klippy.sock` to KLIPPY_ARGS:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
@@ -36,14 +61,17 @@ 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"
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /home/pi/printer_data/comms/klippy.sock
|
||||
```
|
||||
You may also want to take this opportunity to change the location of
|
||||
printer.cfg to match Moonraker's "config_path" option (see the
|
||||
[configuration document](configuration.md#primary-configuration)
|
||||
for more information on the config_path). For example, if the `config_path`
|
||||
option is set to `~/printer_config`, your klipper defaults file might look
|
||||
like the following:
|
||||
|
||||
!!! 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
|
||||
|
||||
@@ -51,123 +79,699 @@ KLIPPY_USER=pi
|
||||
|
||||
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_data/config/printer.cfg -l /home/pi/printer_data/logs/klippy.log -a /home/pi/printer_data/comms/klippy.sock"
|
||||
```
|
||||
|
||||
If necessary, create the config directory and move printer.cfg to it:
|
||||
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
|
||||
|
||||
Moonraker provides an install script that can be used to facilitate
|
||||
installation. The type of installation depends on where the install
|
||||
script is located on the host file system. If the install script is
|
||||
downloaded and run individually, the script will install Moonraker as
|
||||
a Python Package using pip. If the script is run from Moonraker's
|
||||
original source it will install Moonraker from source.
|
||||
|
||||
Prior to installation it is necessary to open a terminal on the host
|
||||
machine, or SSH into it. It is recommended to read this entire
|
||||
section before proceeding with the installation.
|
||||
|
||||
### Installing the Moonraker Python package
|
||||
|
||||
The Python Package version of Moonraker will receive fewer updates, and
|
||||
should generally be more stable. This is intended for users that do
|
||||
not need to run unofficial 3rd party extensions, such as
|
||||
[Moonraker-Timelapse](https://github.com/mainsail-crew/moonraker-timelapse),
|
||||
and do not desire to run the "bleeding edge" version of Moonraker.
|
||||
|
||||
To perform this installation, download Moonraker's
|
||||
[install script](https://raw.githubusercontent.com/Arksine/moonraker/master/scripts/install-moonraker.sh)
|
||||
from Github, then run the installer:
|
||||
|
||||
```
|
||||
cd ~
|
||||
mkdir printer_config
|
||||
mv printer.cfg printer_config
|
||||
```
|
||||
|
||||
You can now install the Moonraker application:
|
||||
```
|
||||
cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
Prior to installation it is a good idea to create
|
||||
[moonraker.conf](configuration.md). If you are using the `config_path`,
|
||||
create it in the specified directory otherwise create it in the HOME
|
||||
directory. A sample `moonraker.conf` may be found in the `docs` folder
|
||||
of this repo.
|
||||
|
||||
For a default installation run the following commands:
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
wget https://raw.githubusercontent.com/Arksine/moonraker/master/scripts/install-moonraker.sh
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
Or to install with `moonraker.conf` in the `config_path`:
|
||||
### Installing Moonraker from source
|
||||
|
||||
Moonraker can be run directly from source. This method of installation will
|
||||
clone Moonraker's git repository, and may receive frequent bleeding edge
|
||||
updates. Users who want to test Moonraker, run unofficial modifications, and
|
||||
do not mind SSHing into the host to correct issues should choose this option.
|
||||
|
||||
To install Moonraker from source, clone its git repository then run the installer:
|
||||
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
|
||||
cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
~/moonraker/scripts/install-moonraker.sh
|
||||
```
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
### Customizing the installation
|
||||
|
||||
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
|
||||
[configuration documentation](./configuration.md).
|
||||
|
||||
|
||||
The install script has several command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
- -r\
|
||||
This will rebuild the virtual environment for existing installations.
|
||||
Sometimes this is necessary when a dependency has been added.
|
||||
- -f\
|
||||
This will tell the script to overwrite Moonraker's "defaults" file.
|
||||
By default the script will not modify the "defaults" file if it is
|
||||
detected as present.
|
||||
- -c /path/to/moonraker.conf\
|
||||
This allows the user to specify the path to Moonraker's config file.
|
||||
The default location is `/home/<user>/moonraker.conf`.
|
||||
|
||||
When the script completes it should start both Moonraker and Klipper. In
|
||||
`klippy.log` you should find the following entry:\
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
|
||||
- `-f`:
|
||||
Force an overwrite of Moonraker's systemd script. In addition, a
|
||||
new `moonraker.env` file will be created, and the PolKit rules will
|
||||
be re-installed. By default these items will not be modified if
|
||||
they exist.
|
||||
- `-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 configuration 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.
|
||||
- `-s`:
|
||||
Installs Moonraker's [speedup](#optional-speedups) Python packages in the
|
||||
Python environment.
|
||||
|
||||
Now you may install a client, such as
|
||||
[Mainsail](https://github.com/meteyou/mainsail) or
|
||||
[Fluidd](https://github.com/cadriel/fluidd)
|
||||
Additionally, installation may be customized with the following environment
|
||||
variables:
|
||||
|
||||
- `MOONRAKER_VENV`
|
||||
- `MOONRAKER_REBUILD_ENV`
|
||||
- `MOONRAKER_FORCE_SYSTEM_INSTALL`
|
||||
- `MOONRAKER_DISABLE_SYSTEMCTL`
|
||||
- `MOONRAKER_SKIP_POLKIT`
|
||||
- `MOONRAKER_CONFIG_PATH`
|
||||
- `MOONRAKER_LOG_PATH`
|
||||
- `MOONRAKER_DATA_PATH`
|
||||
- `MOONRAKER_SPEEDUPS`
|
||||
|
||||
When the script completes it should start the Moonraker system service. If Klipper
|
||||
is running and Moonraker is able to establish a connection the following log entry
|
||||
should be available in `klippy.log`:
|
||||
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
|
||||
|
||||
Now you may wish to install a frontend, such as
|
||||
[Mainsail](https://github.com/mainsail-crew/mainsail) or
|
||||
[Fluidd](https://github.com/fluidd-core/fluidd).
|
||||
|
||||
!!! Note
|
||||
Moonraker's installer does not include nginx as a 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`.
|
||||
|
||||
## Command line Usage
|
||||
The configuration and log file paths may be specified via the command
|
||||
line.
|
||||
```
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
|
||||
/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
|
||||
│ └── moonraker-sql.db
|
||||
├── 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 desirable 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. See the
|
||||
[environment file section](#the-environment-file) for details.
|
||||
- The `ExecStart` field begins with the python executable, followed by
|
||||
by the environment variable `MOONRAKER_ARGS`. This variable is set in
|
||||
the environment file.
|
||||
|
||||
|
||||
## 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] [-d <data path>] [-c <configfile>] [-l <logfile>] [-u <unixsocket>] [-n] [-v] [-g] [-o]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
optional arguments:
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
-d <data path>, --datapath <data path>
|
||||
Location of Moonraker Data File Path
|
||||
-c <configfile>, --configfile <configfile>
|
||||
Location of moonraker configuration file
|
||||
Path to Moonraker's configuration file
|
||||
-l <logfile>, --logfile <logfile>
|
||||
log file name and location
|
||||
Path to Moonraker's log file
|
||||
-u <unixsocket>, --unixsocket <unixsocket>
|
||||
Path to Moonraker's unix domain socket
|
||||
-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:
|
||||
- config file path- `~/moonraker.conf`
|
||||
- log file path - `/tmp/moonraker.log`
|
||||
|
||||
- `data path`: `$HOME/printer_data`
|
||||
- `config file`: `$HOME/printer_data/config/moonraker.conf`
|
||||
- `log file`: `$HOME/printer_data/logs/moonraker.log`
|
||||
- `unix socket`: `$HOME/printer_data/comms/moonraker.sock`
|
||||
- logging to a file is enabled
|
||||
- Verbose logging is disabled
|
||||
- Moonraker's debug features are disabled
|
||||
- The asyncio debug flag is set to false
|
||||
|
||||
If one needs to start moonraker without generating a log file, the
|
||||
'-n' option may be used, for example:
|
||||
!!! 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.
|
||||
|
||||
!!! Warning
|
||||
Moonraker's `--unixsocket` option should not be confused with Klipper's
|
||||
`--api-server` option. The `unixsocket` option for Moonraker specifies
|
||||
the path where Moonraker will create a unix domain socket that serves its
|
||||
JSON-RPC API.
|
||||
|
||||
If is necessary to run Moonraker without logging to a file the
|
||||
`-n` option may be used, for example:
|
||||
```
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -d ~/printer_data -n
|
||||
```
|
||||
In general it is not recommended to install moonraker with this option.
|
||||
While moonraker will still log to stdout, all requests for support must
|
||||
be accompanied by moonraker.log.
|
||||
|
||||
These options may be changed by editing
|
||||
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
|
||||
may also be used to modify the config file location.
|
||||
!!! Tip
|
||||
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`.
|
||||
|
||||
## Prerequisites (Klipper Configuration)
|
||||
Each command line argument has an associated environment variable that may
|
||||
be used to specify options in place of the command line.
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
- [virtual_sdcard]
|
||||
- [pause_resume]
|
||||
- [display_status]
|
||||
- `MOONRAKER_DATA_PATH="<data path>"`: equivalent to `-d <data path>`
|
||||
- `MOONRAKER_CONFIG_PATH="<configfile>"`: equivalent to `-c <configfile>`
|
||||
- `MOONRAKER_LOG_PATH="<logfile>"`: equivalent to `-l <logfile>`
|
||||
- `MOONRAKER_UDS_PATH="<unixsocket>"`: equivalent to `-u <unixsocket>`
|
||||
- `MOONRAKER_DISABLE_FILE_LOG="y"`: equivalent to `-n`
|
||||
- `MOONRAKER_VERBOSE_LOGGING="y"`: equivalent to `-v`
|
||||
- `MOONRAKER_ENABLE_DEBUG="y"`: equivalent to `-g`.
|
||||
- `MOONRAKER_ASYNCIO_DEBUG="y"`: equivalent to `-o`
|
||||
|
||||
!!! Note
|
||||
Command line arguments take priority over environment variables when
|
||||
both are specified.
|
||||
|
||||
[The environment file](#the-environment-file) may be used to set Moonraker's
|
||||
command line arguments and/or environment variables.
|
||||
|
||||
## 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:
|
||||
|
||||
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:
|
||||
```
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
MOONRAKER_DATA_PATH="/home/pi/printer_data"
|
||||
MOONRAKER_ARGS="-m moonraker"
|
||||
PYTHONPATH="/home/pi/moonraker"
|
||||
```
|
||||
NOTES:
|
||||
- Make sure that Moonraker (and Klipper) has read and write access to the
|
||||
directory set in the `path` option for the `virtual_sdcard`.
|
||||
- Upon first starting Moonraker is not aware of the gcode file path, thus
|
||||
it cannot serve gcode files, add directories, etc. After Klippy enters
|
||||
the "ready" state it sends Moonraker the gcode file path.
|
||||
Once Moonraker receives the path it will retain it regardless of Klippy's
|
||||
state, and update it if the path is changed in printer.cfg.
|
||||
|
||||
Please see [configuration.md](configuration.md) for details on how to
|
||||
configure moonraker.conf.
|
||||
A legacy installation converted to the updated flexible service unit
|
||||
might contain the following. Note that this example uses command line
|
||||
arguments instead of environment variables, either would be acceptable:
|
||||
|
||||
```
|
||||
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
|
||||
[arguments and/or environment variables](#command-line-usage)
|
||||
supplied to Moonraker by editing this file and restarting the service.
|
||||
The following example sets a custom config file path, log file path,
|
||||
enables verbose logging, and enables debug features:
|
||||
|
||||
```
|
||||
MOONRAKER_DATA_PATH="/home/pi/printer_data"
|
||||
MOONRAKER_CONFIG_PATH="/home/pi/printer_data/config/moonraker-1.conf"
|
||||
MOONRAKER_LOG_PATH="/home/pi/printer_data/logs/moonraker-1.log"
|
||||
MOONRAKER_VERBOSE_LOGGING="y"
|
||||
MOONRAKER_ENABLE_DEBUG="y"
|
||||
MOONRAKER_ARGS="-m moonraker"
|
||||
PYTHONPATH="/home/pi/moonraker"
|
||||
```
|
||||
|
||||
## Optional Speedups
|
||||
|
||||
Moonraker supports two optional Python packages that can be used to reduce
|
||||
its CPU load:
|
||||
|
||||
- [msgspec](https://github.com/jcrist/msgspec): Replaces the builtin `json`
|
||||
encoder/decoder. Requires Python >= 3.8.
|
||||
- [uvloop](https://github.com/MagicStack/uvloop/): Replaces the default asyncio
|
||||
eventloop implementation.
|
||||
|
||||
If these packages are installed in Moonraker's python environment Moonraker will
|
||||
load them. For existing installations this can be done manually with a command
|
||||
like:
|
||||
|
||||
```
|
||||
~/moonraker-env/bin/pip install -r ~/moonraker/scripts/moonraker-speedups.txt
|
||||
```
|
||||
|
||||
After installing the speedup packages it is possible to revert back to the
|
||||
default implementation by specifying one or both of the following
|
||||
environment variables in [moonraker.env](#the-environment-file):
|
||||
|
||||
- `MOONRAKER_ENABLE_MSGSPEC="n"`
|
||||
- `MOONRAKER_ENABLE_UVLOOP="n"`
|
||||
|
||||
|
||||
## 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 authorized 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
|
||||
```
|
||||
|
||||
!!! 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.
|
||||
|
||||
```shell
|
||||
cd ~/moonraker/scripts
|
||||
./install-moonraker.sh
|
||||
```
|
||||
|
||||
2) Configure Moonraker to use the legacy backend implementations for
|
||||
the `machine` and/or `update_manager` components, ie:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
!!! 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:
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
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):
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./fetch-apikey.sh
|
||||
```
|
||||
|
||||
Additionally its possible to generate a new API Key with the `-g`
|
||||
option:
|
||||
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./fetch-apikey.sh -g
|
||||
```
|
||||
|
||||
If Moonraker is running it must be restarted for the new API key to
|
||||
take affect:
|
||||
|
||||
```
|
||||
sudo systemctl restart moonraker
|
||||
```
|
||||
|
||||
#### Retrieve the API Key via the browser from a trusted client:
|
||||
|
||||
- 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"}
|
||||
|
||||
## Database Backup and Restore
|
||||
|
||||
Moonraker stores persistent data using an Sqlite database. By default
|
||||
the database file is located at `<data_folder>/database/moonraker-sql.db`.
|
||||
API Endpoints are available to backup and restore the database. All
|
||||
backups are stored at `<data_folder>/backup/database/<backup_name>` and
|
||||
restored from the same location. Database files may contain sensitive
|
||||
information, therefore they are not served by Moonraker. Another protocol
|
||||
such as SCP, SMB, etc is required to transfer a backup off of the host.
|
||||
|
||||
Alternatively it is possible to perform a manual backup by copying the
|
||||
existing database file when the Moonraker service has been stopped.
|
||||
Restoration can be performed by stopping the Moonraker service and
|
||||
overwriting the existing database with the backup.
|
||||
|
||||
### LDMB Database (deprecated)
|
||||
|
||||
Previous versions of Moonraker used 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
|
||||
```
|
||||
+16
-2
@@ -1,9 +1,12 @@
|
||||
# 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: True
|
||||
config_path: ~/printer_config
|
||||
enable_debug_logging: False
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
@@ -13,3 +16,14 @@ trusted_clients:
|
||||
cors_domains:
|
||||
# Allow CORS requests for Fluidd
|
||||
http://app.fluidd.xyz
|
||||
|
||||
# Enable OctoPrint compatibility for Slicer uploads
|
||||
# Supports Cura, Slic3r, and Slic3r derivatives
|
||||
# (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
|
||||
+2243
-250
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,129 @@
|
||||
# The MIT License (MIT)
|
||||
#
|
||||
# Copyright (c) 2014 - 2023 Isaac Muse
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in all
|
||||
# copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
# SOFTWARE.
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
"""Collapsible code."""
|
||||
import xml.etree.ElementTree as etree
|
||||
from markdown import util as mutil
|
||||
import re
|
||||
from pymdownx.blocks.block import Block
|
||||
from pymdownx.blocks import BlocksExtension
|
||||
|
||||
# Fenced block placeholder for SuperFences
|
||||
FENCED_BLOCK_RE = re.compile(
|
||||
r'^([\> ]*){}({}){}$'.format(
|
||||
mutil.HTML_PLACEHOLDER[0],
|
||||
mutil.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)',
|
||||
mutil.HTML_PLACEHOLDER[-1]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class CollapseCode(Block):
|
||||
"""Collapse code."""
|
||||
|
||||
NAME = 'collapse-code'
|
||||
|
||||
def on_init(self):
|
||||
"""Handle initialization."""
|
||||
|
||||
# Track tab group count across the entire page.
|
||||
if 'collapse_code_count' not in self.tracker:
|
||||
self.tracker['collapse_code_count'] = 0
|
||||
|
||||
self.expand = self.config['expand_text']
|
||||
if not isinstance(self.expand, str):
|
||||
raise ValueError("'expand_text' must be a string")
|
||||
|
||||
self.collapse = self.config['collapse_text']
|
||||
if not isinstance(self.collapse, str):
|
||||
raise ValueError("'collapse_text' must be a string")
|
||||
|
||||
self.expand_title = self.config['expand_title']
|
||||
if not isinstance(self.expand_title, str):
|
||||
raise ValueError("'expand_title' must be a string")
|
||||
|
||||
self.collapse_title = self.config['collapse_title']
|
||||
if not isinstance(self.collapse_title, str):
|
||||
raise ValueError("'collapse_title' must be a string")
|
||||
|
||||
def on_create(self, parent):
|
||||
"""Create the element."""
|
||||
|
||||
self.count = self.tracker['collapse_code_count']
|
||||
self.tracker['collapse_code_count'] += 1
|
||||
el = etree.SubElement(parent, 'div', {'class': 'collapse-code'})
|
||||
etree.SubElement(
|
||||
el,
|
||||
'input',
|
||||
{
|
||||
"type": "checkbox",
|
||||
"id": "__collapse{}".format(self.count),
|
||||
"name": "__collapse{}".format(self.count),
|
||||
'checked': 'checked'
|
||||
}
|
||||
)
|
||||
return el
|
||||
|
||||
def on_end(self, block):
|
||||
"""Convert non list items to details."""
|
||||
|
||||
el = etree.SubElement(block, 'div', {'class': 'code-footer'})
|
||||
attrs = {'for': '__collapse{}'.format(self.count), 'class': 'expand', 'tabindex': '0'}
|
||||
if self.expand_title:
|
||||
attrs['title'] = self.expand_title
|
||||
expand = etree.SubElement(el, 'label', attrs)
|
||||
expand.text = self.expand
|
||||
|
||||
attrs = {'for': '__collapse{}'.format(self.count), 'class': 'collapse', 'tabindex': '0'}
|
||||
if self.collapse_title:
|
||||
attrs['title'] = self.collapse_title
|
||||
collapse = etree.SubElement(el, 'label', attrs)
|
||||
collapse.text = self.collapse
|
||||
|
||||
|
||||
class CollapseCodeExtension(BlocksExtension):
|
||||
"""Admonition Blocks Extension."""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize."""
|
||||
|
||||
self.config = {
|
||||
'expand_text': ['Expand', "Set the text for the expand button."],
|
||||
'collapse_text': ['Collapse', "Set the text for the collapse button."],
|
||||
'expand_title': ['expand', "Set the text for the expand title."],
|
||||
'collapse_title': ['collapse', "Set the text for the collapse title."]
|
||||
}
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def extendMarkdownBlocks(self, md, blocks):
|
||||
"""Extend Markdown blocks."""
|
||||
|
||||
blocks.register(CollapseCode, self.getConfigs())
|
||||
|
||||
|
||||
def makeExtension(*args, **kwargs):
|
||||
"""Return extension."""
|
||||
|
||||
return CollapseCodeExtension(*args, **kwargs)
|
||||
@@ -0,0 +1,7 @@
|
||||
from setuptools import setup
|
||||
setup(
|
||||
name='pymdown_extras',
|
||||
version='1.0.0',
|
||||
py_modules=['collapse_code'],
|
||||
install_requires=['pymdown-extensions>=10.7'],
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
:root>*{--md-code-link-bg-color:hsla(0, 0%, 96%, 1);--md-code-link-accent-bg-color:var(--md-code-link-bg-color);--md-default-bg-color--trans:rgb(100%, 100%, 100%, 0);--md-code-title-bg-color:var(--md-code-bg-color);--md-code-inline-bg-color:var(--md-code-bg-color);--md-code-special-bg-color:#e8e8e8;--md-code-alternate-bg-color:var(--md-code-bg-color);--md-code-hl-punctuation-color:var(--md-code-fg-color);--md-code-hl-namespace-color:var(--md-code-fg-color);--md-code-hl-entity-color:var(--md-code-hl-keyword-color);--md-code-hl-tag-color:var(--md-code-hl-keyword-color);--md-code-hl-builtin-color:var(--md-code-hl-constant-color);--md-code-hl-class-color:var(--md-code-hl-function-color);--md-typeset-a-color:#00bcd4;--md-progress-stripe:var(--md-default-bg-color--lighter);--md-progress-100:#00e676;--md-progress-80:#00e676;--md-progress-60:#fbc02d;--md-progress-40:#ff9100;--md-progress-20:#ff5252;--md-progress-0:#ff1744;--md-typeset-kbd-color:#ebebeb;--md-typeset-kbd-border-color:#b8b8b8;--md-typeset-kbd-accent-color:hsla(0, 100%, 100%, 1)}:root>[data-md-color-scheme=slate]{--md-code-link-bg-color:hsla(232, 15%, 15%, 1);--md-code-link-accent-bg-color:var(--md-code-link-bg-color);--md-code-special-bg-color:#2b2d3b;--md-default-bg-color--trans:hsla(232,15%,15%, 0);--md-default-bg-color--ultra-dark:#111217;--md-code-title-bg-color:var(--md-primary-fg-color--dark);--md-shadow-z2:0 0.2rem 0.5rem hsla(0, 0%, 0%, 0.3),0 0 0.05rem hsla(0, 0%, 0%, 0.2);--md-typeset-kbd-color:var(--md-default-fg-color--lightest);--md-typeset-kbd-border-color:#1a1c24;--md-typeset-kbd-accent-color:var(--md-default-fg-color--lighter)}:root>[data-md-color-scheme=dracula]{--md-default-fg-color:rgba(248, 248, 242, 0.87);--md-default-fg-color--light:rgba(248, 248, 242, 0.54);--md-default-fg-color--lighter:rgba(248, 248, 242, 0.16);--md-default-fg-color--lightest:rgba(248, 248, 242, 0.07);--md-default-autocomplete-fg-color:rgba(248, 248, 242, 0.4);--md-shadow-z2:0 0.2rem 0.5rem hsla(0, 0%, 0%, 0.3),0 0 0.05rem hsla(0, 0%, 0%, 0.2);--md-default-bg-color:var(--md-default-bg-color--darkest);--md-default-bg-color--light:rgba(50, 52, 67, 0.7);--md-default-bg-color--lighter:rgba(50, 52, 67, 0.3);--md-default-bg-color--lightest:rgba(50, 52, 67, 0.12);--md-default-bg-color--trans:rgba(50, 52, 67, 0);--md-default-bg-color--dark:#2b2e3b;--md-default-bg-color--darker:#252732;--md-default-bg-color--darkest:#1e2029;--md-default-bg-color--ultra-dark:#111217;--md-text-color:var(--md-default-fg-color);--md-typeset-color:var(--md-default-fg-color);--md-admonition-fg-color:var(--md-default-fg-color);--md-code-fg-color:hsl(60, 30%, 96%);--md-code-bg-color:hsl(231, 15%, 18%);--md-code-title-bg-color:var(--md-default-bg-color--ultra-dark);--md-code-inline-bg-color:#323443;--md-code-hl-operator-color:hsl(326, 100%, 74%);--md-code-hl-punctuation-color:hsl(60, 30%, 96%);--md-code-hl-string-color:hsl(65, 92%, 76%);--md-code-hl-special-color:hsl(265, 89%, 78%);--md-code-hl-number-color:hsl(265, 89%, 78%);--md-code-hl-keyword-color:hsl(326, 100%, 74%);--md-code-hl-name-color:hsl(60, 30%, 96%);--md-code-hl-constant-color:hsl(265, 89%, 78%);--md-code-hl-function-color:hsl(135, 94%, 65%);--md-code-hl-comment-color:hsl(225, 27%, 51%);--md-code-hl-variable-color:hsl(31, 100%, 71%);--md-code-hl-generic-color:hsl(225, 27%, 51%);--md-code-hl-color:hsl(231, 25%, 25%);--md-code-hl-entity-color:hsl(135, 94%, 65%);--md-code-hl-tag-color:hsl(326, 100%, 74%);--md-code-hl-namespace-color:hsl(60, 30%, 96%);--md-code-hl-builtin-color:hsl(191, 97%, 77%);--md-code-hl-class-color:hsl(191, 97%, 77%);--md-code-special-bg-color:#1c1e26;--md-code-alternate-bg-color:#3d3e49;--md-code-link-bg-color:#364653;--md-typeset-a-color:hsl(191, 97%, 77%);--md-typeset-mark-color:#6e7252;--md-typeset-del-color:#734568;--md-typeset-ins-color:#36724e;--md-progress-stripe:var(--md-default-bg-color--lightest);--md-progress-100:hsl(135, 94%, 65%);--md-progress-80:hsl(135, 92%, 79%);--md-progress-60:hsl(65, 92%, 76%);--md-progress-40:hsl(31, 100%, 71%);--md-progress-20:hsl(326, 100%, 74%);--md-progress-0:hsl(0, 100%, 67%);--md-typeset-kbd-color:var(--md-default-fg-color--lightest);--md-typeset-kbd-border-color:var(--md-default-bg-color--ultra-dark);--md-typeset-kbd-accent-color:var(--md-default-fg-color--lighter)}[data-md-color-scheme=dracula] :not([data-md-color-scheme])[data-md-color-primary=red],[data-md-color-scheme=dracula][data-md-color-primary=red]{--md-primary-code-bg-color:#47303a;--md-primary-fg-color:hsla(0deg, 100%, 67%, 1);--md-primary-fg-color--transparent:hsla(0deg, 100%, 67%, 0.1);--md-primary-fg-color--light:hsla(0deg, 100%, 72%, 1);--md-primary-fg-color--dark:hsla(0deg, 100%, 62%, 1);--md-primary-bg-color:var(--md-default-bg-color);--md-primary-bg-color--light:var(--md-default-bg-color--light)}[data-md-color-scheme=dracula] :not([data-md-color-scheme])[data-md-color-primary=pink],[data-md-color-scheme=dracula][data-md-color-primary=pink]{--md-primary-code-bg-color:#47354b;--md-primary-fg-color:hslLine truncated
|
||||
/*# sourceMappingURL=extra-950ac449d4.css.map */
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["palette/_colors.scss","extra.css","extensions/_highlight.scss","extensions/_tables.scss","utilities/_break.scss"],"names":[],"mappings":"AAEA,QAEE,wBAAA,oBACA,+BAAA,6BACA,6BAAA,yBACA,yBAAA,wBACA,0BAAA,wBAEA,2BAAA,QACA,6BAAA,wBAEA,+BAAA,wBACA,6BAAA,wBAEA,0BAAA,gCACA,uBAAA,gCACA,2BAAA,iCACA,yBAAA,iCAGA,qBAAA,QAGA,qBAAA,oCACA,kBAAA,QACA,iBAAA,QACA,iBAAA,QACA,iBAAA,QACA,iBAAA,QACA,gBAAA,QAGA,uBAAA,QACA,8BAAA,QACA,8BAAA,uBAEA,mCAEE,wBAAA,uBACA,+BAAA,6BACA,2BAAA,QACA,6BAAA,qBAEA,kCAAA,QAGA,yBAAA,iCAGA,eAAA,EAAA,OAAA,OAAA,oBAAA,CCjBmC,EAAE,EAAE,QAAQ,qBDqB/C,uBAAA,qCACA,8BAAA,QACA,8BAAA,oCAIF,qCAEE,sBAAA,0BACA,6BAAA,0BACA,+BAAA,0BACA,gCAAA,0BACA,mCAAA,yBACA,eAAA,EAAA,OAAA,OAAA,oBAAA,CCtBmC,EAAE,EAAE,QAAQ,qBDyB/C,sBAAA,oCACA,6BAAA,sBACA,+BAAA,sBACA,gCAAA,uBACA,6BAAA,oBAGA,4BAAA,QACA,8BAAA,QACA,+BAAA,QACA,kCAAA,QAGA,gBAAA,2BACA,mBAAA,2BAGA,yBAAA,2BAGA,mBAAA,kBACA,mBAAA,mBACA,yBAAA,uCACA,0BAAA,QACA,4BAAA,oBACA,+BAAA,kBACA,0BAAA,kBACA,2BAAA,mBACA,0BAAA,mBACA,2BAAA,oBACA,wBAAA,kBACA,4BAAA,mBACA,4BAAA,mBACA,2BAAA,mBACA,4BAAA,mBACA,2BAAA,mBACA,mBAAA,mBAGA,0BAAA,mBACA,uBAAA,oBACA,6BAAA,kBACA,2BAAA,mBACA,yBAAA,mBAEA,2BAAA,QACA,6BAAA,QACA,wBAAA,QAGA,qBAAA,mBACA,wBAAA,QACA,uBAAA,QACA,uBAAA,QAGA,qBAAA,qCACA,kBAAA,mBACA,iBAAA,mBACA,iBAAA,kBACA,iBAAA,mBACA,iBAAA,oBACA,gBAAA,kBAGA,uBAAA,qCACA,8BAAA,uCACA,8BAAA,oCCrCJ,uFDiEE,0DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCChEJ,wFDsDE,2DAIE,2BAAA,QACA,sBAAA,2BACA,mCAAA,6BACA,6BAAA,2BACA,4BAAA,2BACA,sBAAA,2BACA,6BAAA,kCCrDJ,0FD2CE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC1CJ,+FDgCE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC/BJ,wFDqBE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCpBJ,0FDUE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCTJ,8FDDE,iEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCEJ,wFDZE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCaJ,wFDvBE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCwBJ,yFDlCE,4DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCmCJ,+FD7CE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC8CJ,wFDxDE,2DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCyDJ,0FDnEE,6DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCCoEJ,yFD9EE,4DAIE,2BAAA,QACA,sBAAA,yBACA,mCAAA,2BACA,6BAAA,yBACA,4BAAA,yBACA,sBAAA,2BACA,6BAAA,kCC+EJ,0FDzFE,6DAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCC0FJ,+FDpGE,kEAIE,2BAAA,QACA,sBAAA,0BACA,mCAAA,4BACA,6BAAA,0BACA,4BAAA,0BACA,sBAAA,2BACA,6BAAA,kCCqGJ,uFDzEE,yDAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCC4EJ,wFDlFE,0DAEE,+BAAA,QACA,qBAAA,2BACA,kCAAA,6BACA,qBAAA,2BACA,4BAAA,kCCqFJ,0FD3FE,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC8FJ,+FDpGE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCuGJ,wFD7GE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCgHJ,0FDtHE,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCyHJ,8FD/HE,gEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCkIJ,wFDxIE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC2IJ,wFDjJE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCoJJ,yFD1JE,2DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC6JJ,+FDnKE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCCsKJ,wFD5KE,0DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC+KJ,0FDrLE,4DAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCCwLJ,yFD9LE,2DAEE,+BAAA,QACA,qBAAA,yBACA,kCAAA,2BACA,qBAAA,2BACA,4BAAA,kCCiMJ,0FDvME,4DAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCC0MJ,+FDhNE,iEAEE,+BAAA,QACA,qBAAA,0BACA,kCAAA,4BACA,qBAAA,2BACA,4BAAA,kCEjNF,eACE,MAAA,iCAGF,eDmaF,eChaI,MAAA,8BAGF,eACE,MAAA,+BDmaJ,eChaE,eAEE,MAAA,gCAGF,eACE,MAAA,kCAGF,eD8ZF,eACA,eC5ZI,MAAA,+BAEF,eD8ZF,eC5ZI,MAAA,4BAOF,2BACI,OAAA,EACA,QAAA,EAAA,cACA,MAAA,wBACA,iBAAA,+BACA,cAAA,MACA,WAAA,KAKF,mBACE,MAAA,kBACA,iBAAA,uCACA,WAAA,MAAA,MACA,WAAA,iBAAA,MAGA,qBACE,MAAA,oCAGF,yBACE,iBAAA,8CAEA,2BACE,MAAA,oCAMR,qBACE,QAAA,EAIF,oBACE,WAAA,OAGF,uBAGE,cAAA,EAAA,YAAA,EAAA,SAAA,EAEA,+BACE,aAAA,MAOA,sDACE,iBAAA,gCAQF,gDACE,aAAA,eACA,YAAA,gBACA,cAAA,cACA,aAAA,eACA,iBAAA,gCAMN,qCAaE,SAAA,SACA,QAAA,MACA,WAAA,IACA,QAAA,KAAA,eAAA,KAAA,eACA,YAAA,IACA,UAAA,OACA,iBAAA,8BACA,uBAAA,MACA,wBAAA,MAlBA,yCACE,WAAA,EAEA,8CACE,uBAAA,EACA,wBAAA,EAgBJ,6CACE,SAAA,SACA,KAAA,cACA,MAAA,eACA,OAAA,eACA,iBAAA,2BACA,mBAAA,uRAAA,WAAA,uRACA,oBAAA,UAAA,YAAA,UACA,kBAAA,QAAA,UAAA,QACA,QAAA,GAIJ,8CACE,mBAAA,qoBAAA,WAAA,qoBAGF,+CACE,mBAAA,kRAAA,WAAA,kRAGF,2BACE,SAAA,SACA,WAAA,IACA,cAAA,IAEA,+BACE,WAAA,EACA,cAAA,EAGF,iCACE,QAAA,KAEA,8CACE,MAAA,KACA,OAAALine truncated
|
||||
@@ -0,0 +1,2 @@
|
||||
!function(){"use strict";var t;t=function(){for(var t=document.querySelectorAll("tbody"),e=0;e<t.length;e++)for(var n=t[e].children,o=function(){var t=n[r];if(t.hasAttribute("compact-container")){var e=n[r-1];t.classList.add("table-container"),e.classList.add("table-container-ctrl"),e.addEventListener("click",(function(n){e.hasAttribute("open")?(t.removeAttribute("open"),e.removeAttribute("open")):(t.setAttribute("open",""),e.setAttribute("open",""))}))}},r=1;r<n.length;r++)o()},window.document$?window.document$.subscribe(t):document.addEventListener("DOMContentLoaded",t)}();
|
||||
//# sourceMappingURL=compact-tables-qqTQvuZ9.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"compact-tables-qqTQvuZ9.js","sources":["compact-tables.js"],"sourcesContent":["(() => {\n const main = () => {\n // Iterate through all tables looking for containers. This\n // works without assigning IDs to everything.\n const tbody_list = document.querySelectorAll(\"tbody\")\n for (let i = 0; i < tbody_list.length; i++) {\n const tbody = tbody_list[i]\n const row_list = tbody.children\n for (let j = 1; j < row_list.length; j++) {\n const cur_row = row_list[j]\n if (cur_row.hasAttribute(\"compact-container\")) {\n const control_row = row_list[j-1]\n cur_row.classList.add(\"table-container\")\n control_row.classList.add(\"table-container-ctrl\")\n control_row.addEventListener(\"click\", (event) => {\n if (control_row.hasAttribute(\"open\")) {\n cur_row.removeAttribute(\"open\")\n control_row.removeAttribute(\"open\")\n } else {\n cur_row.setAttribute(\"open\", \"\")\n control_row.setAttribute(\"open\", \"\")\n }\n })\n }\n }\n }\n }\n\n if (window.document$) {\n // Material specific hook\n window.document$.subscribe(main)\n } else {\n // Normal non-Material specific hook\n document.addEventListener(\"DOMContentLoaded\", main)\n }\n\n})()"],"names":["main","tbody_list","document","querySelectorAll","i","length","row_list","children","_loop","cur_row","j","hasAttribute","control_row","classList","add","addEventListener","event","removeAttribute","setAttribute","window","document$","subscribe"],"mappings":"yBAAA,IACUA,IAAO,WAIT,IADA,IAAMC,EAAaC,SAASC,iBAAiB,SACpCC,EAAI,EAAGA,EAAIH,EAAWI,OAAQD,IAGnC,IAFA,IACME,EADQL,EAAWG,GACFG,SAAQC,EAAAA,WAE3B,IAAMC,EAAUH,EAASI,GACzB,GAAID,EAAQE,aAAa,qBAAsB,CAC3C,IAAMC,EAAcN,EAASI,EAAE,GAC/BD,EAAQI,UAAUC,IAAI,mBACtBF,EAAYC,UAAUC,IAAI,wBAC1BF,EAAYG,iBAAiB,SAAS,SAACC,GAC/BJ,EAAYD,aAAa,SACzBF,EAAQQ,gBAAgB,QACxBL,EAAYK,gBAAgB,UAE5BR,EAAQS,aAAa,OAAQ,IAC7BN,EAAYM,aAAa,OAAQ,IAEzC,GACJ,GAfKR,EAAI,EAAGA,EAAIJ,EAASD,OAAQK,IAAGF,KAoB5CW,OAAOC,UAEPD,OAAOC,UAAUC,UAAUrB,GAG3BE,SAASa,iBAAiB,mBAAoBf"}
|
||||
+177
-20
@@ -1,5 +1,162 @@
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
##
|
||||
This file tracks configuration changes and deprecations. Additionally
|
||||
changes to Moonraker that require user intervention will be tracked
|
||||
here.
|
||||
|
||||
### December 24th 2023
|
||||
- The `gpio` component no longer depends on `libgpiod`. Instead,
|
||||
Moonraker now uses the [python-periphery](https://github.com/vsergeev/python-periphery)
|
||||
library to manage GPIOs. This comes with several benefits:
|
||||
- Distributions that do no ship with `libgpiod` will not fail during
|
||||
installation if the `python3-libgpiod` package isn't present.
|
||||
- Distributions with a Kernel Version of 5.5 or higher support bias
|
||||
flags (ie: pull up or pull down). Previously this functionality
|
||||
was tied to the `libgpiod` version. Specifically, Debian Buster
|
||||
ships with a Kernel that supports bias, however the `libgpiod`
|
||||
version does not.
|
||||
- Version 2.0+ of `libgpiod` includes dramatic API changes that are
|
||||
wholly incompatible with prior versions. Therefore maintaining
|
||||
future versions would effectively require supporting two APIs.
|
||||
- The `[button]` component now includes a `debounce_period` option.
|
||||
This addition is the result of a behavior change in how gpio state
|
||||
changes are debounced. Debouncing will now delay the event by the
|
||||
time specified in the `debounce_period`. Additional state changes
|
||||
received during this delay will not trigger a button event. The
|
||||
`[button]` module retains the `minimum_event_time` option which will
|
||||
ignore events shorter than the specified time.
|
||||
|
||||
### July 18th 2023
|
||||
- The following changes have been made to `[update_manager <name>]`
|
||||
extensions of the `git_repo` type:
|
||||
- The `env` option has been deprecated. New configurations should
|
||||
use the `virtualenv` option in its place.
|
||||
- The `install_script` option has been deprecated. New configurations
|
||||
should use the `system_dependencies` option to specify system package
|
||||
dependencies.
|
||||
- Configuration options for `[spoolman]` have been added
|
||||
- Configuration options for `[sensor]` have been added
|
||||
|
||||
### February 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 precedence. 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.
|
||||
|
||||
### February 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 `[authorization]` 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
|
||||
@@ -15,10 +172,10 @@ such as a configuration change or a reinstallation.
|
||||
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
|
||||
```
|
||||
|
||||
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
|
||||
@@ -31,24 +188,24 @@ such as a configuration change or a reinstallation.
|
||||
will update the defaults file wih the new path.
|
||||
- New dependencies have been added to Moonraker which require reinstallation.
|
||||
Run the following command to reinstall and rebuild the virtualenv:
|
||||
```
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
```
|
||||
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
|
||||
- The power plugin configuration has changed. See the
|
||||
[install guide](installation.md#power-control-plugin) for
|
||||
[the configuration documentation](./configuration.md#power) 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
|
||||
to unexport any currently used pins. For example, the following command
|
||||
may be used to unexport pin 19:
|
||||
```
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
```
|
||||
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
|
||||
Alternatively one may reboot the machine after upgrading:
|
||||
```
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
```
|
||||
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
|
||||
Make sure that the power plugin configuration has been updated prior
|
||||
to rebooting the machine.
|
||||
-1377
File diff suppressed because it is too large.
Load diff
+144
@@ -0,0 +1,144 @@
|
||||
site_name: Moonraker
|
||||
site_url: https://moonraker.readthedocs.io
|
||||
repo_url: https://github.com/Arksine/moonraker
|
||||
edit_uri: blob/master/docs/
|
||||
nav:
|
||||
- Installation: installation.md
|
||||
- Configuration : configuration.md
|
||||
- Developer Documentation:
|
||||
- External API:
|
||||
- Introduction: external_api/introduction.md
|
||||
- Server Administration: external_api/server.md
|
||||
- Printer Administration: external_api/printer.md
|
||||
- System Administration: external_api/machine.md
|
||||
- File Management: external_api/file_manager.md
|
||||
- Authorization and Authentication: external_api/authorization.md
|
||||
- Database Management: external_api/database.md
|
||||
- Job Queue Management: external_api/job_queue.md
|
||||
- Job History Management: external_api/history.md
|
||||
- Announcements: external_api/announcements.md
|
||||
- Webcam Management: external_api/webcams.md
|
||||
- Update Management: external_api/update_manager.md
|
||||
- Switches, Sensors, and Devices: external_api/devices.md
|
||||
- Third Party Integrations: external_api/integrations.md
|
||||
- Extensions: external_api/extensions.md
|
||||
- JSON-RPC Notifications: external_api/jsonrpc_notifications.md
|
||||
- Printer Objects: printer_objects.md
|
||||
- Components: components.md
|
||||
- Contribution Guidelines: contributing.md
|
||||
- Changelog: changelog.md
|
||||
theme:
|
||||
name: material
|
||||
palette:
|
||||
- scheme: default
|
||||
primary: blue grey
|
||||
accent: light blue
|
||||
toggle:
|
||||
icon: material/weather-sunny
|
||||
name: Switch to Dark Mode
|
||||
- scheme: slate
|
||||
primary: black
|
||||
accent: light blue
|
||||
toggle:
|
||||
icon: material/weather-night
|
||||
name: Switch to Light Mode
|
||||
font:
|
||||
text: Roboto
|
||||
code: Roboto Mono
|
||||
features:
|
||||
- navigation.top
|
||||
- navigation.instant
|
||||
- navigation.indexes
|
||||
- navigation.expand
|
||||
- toc.follow
|
||||
- content.tabs.link
|
||||
- search.share
|
||||
- search.highlight
|
||||
- search.suggest
|
||||
- content.code.copy
|
||||
- content.code.annotations
|
||||
plugins:
|
||||
- search
|
||||
markdown_extensions:
|
||||
- abbr
|
||||
- admonition
|
||||
- attr_list
|
||||
- def_list
|
||||
- footnotes
|
||||
- md_in_html
|
||||
- toc:
|
||||
permalink: true
|
||||
- pymdownx.arithmatex:
|
||||
generic: true
|
||||
- pymdownx.betterem:
|
||||
smart_enable: all
|
||||
- pymdownx.caret
|
||||
- pymdownx.details
|
||||
- pymdownx.emoji:
|
||||
emoji_index: !!python/name:material.extensions.emoji.twemoji
|
||||
emoji_generator: !!python/name:material.extensions.emoji.to_svg
|
||||
- pymdownx.highlight
|
||||
- pymdownx.inlinehilite
|
||||
- pymdownx.keys
|
||||
- pymdownx.mark
|
||||
- pymdownx.smartsymbols
|
||||
- pymdownx.superfences
|
||||
- pymdownx.tabbed:
|
||||
alternate_style: true
|
||||
- pymdownx.tasklist:
|
||||
custom_checkbox: true
|
||||
- pymdownx.tilde
|
||||
- pymdownx.saneheaders
|
||||
- pymdownx.blocks.admonition
|
||||
- pymdownx.blocks.details:
|
||||
types:
|
||||
- name: details-new
|
||||
class: new
|
||||
- name: details-settings
|
||||
class: settings
|
||||
- name: details-note
|
||||
class: note
|
||||
- name: details-abstract
|
||||
class: abstract
|
||||
- name: details-info
|
||||
class: info
|
||||
- name: details-tip
|
||||
class: tip
|
||||
- name: details-success
|
||||
class: success
|
||||
- name: details-question
|
||||
class: question
|
||||
- name: details-warning
|
||||
class: warning
|
||||
- name: details-failure
|
||||
class: failure
|
||||
- name: details-danger
|
||||
class: danger
|
||||
- name: details-bug
|
||||
class: bug
|
||||
- name: details-example
|
||||
class: example
|
||||
- name: details-quote
|
||||
class: quote
|
||||
- name: api-example-response
|
||||
class: example
|
||||
title: "Response Example"
|
||||
- name: api-response-spec
|
||||
class: info
|
||||
title: "Response Specification"
|
||||
- name: api-parameters
|
||||
class: info
|
||||
title: "Parameters"
|
||||
- name: api-notification-spec
|
||||
class: info
|
||||
title: "Notification Parameter Specification"
|
||||
- tables
|
||||
- compact_tables:
|
||||
auto_insert_break: false
|
||||
- collapse_code:
|
||||
expand_text: ''
|
||||
collapse_text: ''
|
||||
extra_css:
|
||||
- src/css/extra-950ac449d4.css
|
||||
extra_javascript:
|
||||
- src/js/compact-tables-qqTQvuZ9.js
|
||||
@@ -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()
|
||||
@@ -1,364 +0,0 @@
|
||||
# Klipper Web Server Rest API
|
||||
#
|
||||
# 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 mimetypes
|
||||
import logging
|
||||
import tornado
|
||||
from inspect import isclass
|
||||
from tornado.escape import url_unescape
|
||||
from tornado.routing import Rule, PathMatches, AnyMatches
|
||||
from utils import ServerError
|
||||
from websockets import WebRequest, WebsocketManager, WebSocket
|
||||
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
|
||||
from authorization import Authorization
|
||||
|
||||
# These endpoints are reserved for klippy/server communication only and are
|
||||
# not exposed via http or the websocket
|
||||
RESERVED_ENDPOINTS = [
|
||||
"list_endpoints", "gcode/subscribe_output",
|
||||
"register_remote_method"
|
||||
]
|
||||
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
|
||||
|
||||
# Status objects require special parsing
|
||||
def _status_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
val = request_handler.get_argument(key)
|
||||
if not val:
|
||||
args[key] = None
|
||||
else:
|
||||
args[key] = val.split(',')
|
||||
logging.debug(f"Parsed Arguments: {args}")
|
||||
return {'objects': args}
|
||||
|
||||
# Built-in Query String Parser
|
||||
def _default_parser(request_handler):
|
||||
request = request_handler.request
|
||||
arg_list = request.arguments.keys()
|
||||
args = {}
|
||||
for key in arg_list:
|
||||
if key in EXCLUDED_ARGS:
|
||||
continue
|
||||
args[key] = request_handler.get_argument(key)
|
||||
return args
|
||||
|
||||
class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
def __init__(self, application):
|
||||
self.application = application
|
||||
self.pattern_to_rule = {}
|
||||
super(MutableRouter, self).__init__(None)
|
||||
|
||||
def get_target_delegate(self, target, request, **target_params):
|
||||
if isclass(target) and issubclass(target, tornado.web.RequestHandler):
|
||||
return self.application.get_handler_delegate(
|
||||
request, target, **target_params)
|
||||
|
||||
return super(MutableRouter, self).get_target_delegate(
|
||||
target, request, **target_params)
|
||||
|
||||
def has_rule(self, pattern):
|
||||
return pattern in self.pattern_to_rule
|
||||
|
||||
def add_handler(self, pattern, target, target_params):
|
||||
if pattern in self.pattern_to_rule:
|
||||
self.remove_handler(pattern)
|
||||
new_rule = Rule(PathMatches(pattern), target, target_params)
|
||||
self.pattern_to_rule[pattern] = new_rule
|
||||
self.rules.append(new_rule)
|
||||
|
||||
def remove_handler(self, pattern):
|
||||
rule = self.pattern_to_rule.pop(pattern, None)
|
||||
if rule is not None:
|
||||
try:
|
||||
self.rules.remove(rule)
|
||||
except Exception:
|
||||
logging.exception(f"Unable to remove rule: {pattern}")
|
||||
|
||||
class APIDefinition:
|
||||
def __init__(self, endpoint, http_uri, ws_methods,
|
||||
request_methods, parser):
|
||||
self.endpoint = endpoint
|
||||
self.uri = http_uri
|
||||
self.ws_methods = ws_methods
|
||||
if not isinstance(request_methods, list):
|
||||
request_methods = [request_methods]
|
||||
self.request_methods = request_methods
|
||||
self.parser = parser
|
||||
|
||||
class MoonrakerApp:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.tornado_server = None
|
||||
self.api_cache = {}
|
||||
self.registered_base_handlers = []
|
||||
self.max_upload_size = config.getint('max_upload_size', 200)
|
||||
self.max_upload_size *= 1024 * 1024
|
||||
|
||||
# Set Up Websocket and Authorization Managers
|
||||
self.wsm = WebsocketManager(self.server)
|
||||
self.auth = Authorization(config['authorization'])
|
||||
|
||||
mimetypes.add_type('text/plain', '.log')
|
||||
mimetypes.add_type('text/plain', '.gcode')
|
||||
mimetypes.add_type('text/plain', '.cfg')
|
||||
debug = config.getboolean('enable_debug_logging', True)
|
||||
|
||||
# Set up HTTP only requests
|
||||
self.mutable_router = MutableRouter(self)
|
||||
app_handlers = [
|
||||
(AnyMatches(), self.mutable_router),
|
||||
(r"/websocket", WebSocket),
|
||||
(r"/api/version", EmulateOctoprintHandler)]
|
||||
|
||||
self.app = tornado.web.Application(
|
||||
app_handlers,
|
||||
serve_traceback=debug,
|
||||
websocket_ping_interval=10,
|
||||
websocket_ping_timeout=30,
|
||||
parent=self)
|
||||
self.get_handler_delegate = self.app.get_handler_delegate
|
||||
|
||||
# Register handlers
|
||||
logfile = config['system_args'].get('logfile')
|
||||
if logfile:
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
self.register_static_file_handler(
|
||||
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
|
||||
self.auth.register_handlers(self)
|
||||
|
||||
def listen(self, host, port):
|
||||
self.tornado_server = self.app.listen(
|
||||
port, address=host, max_body_size=self.max_upload_size,
|
||||
xheaders=True)
|
||||
|
||||
def get_server(self):
|
||||
return self.server
|
||||
|
||||
def get_auth(self):
|
||||
return self.auth
|
||||
|
||||
def get_websocket_manager(self):
|
||||
return self.wsm
|
||||
|
||||
async def close(self):
|
||||
if self.tornado_server is not None:
|
||||
self.tornado_server.stop()
|
||||
await self.tornado_server.close_all_connections()
|
||||
await self.wsm.close()
|
||||
self.auth.close()
|
||||
|
||||
def register_remote_handler(self, endpoint):
|
||||
if endpoint in RESERVED_ENDPOINTS:
|
||||
return
|
||||
api_def = self._create_api_definition(endpoint)
|
||||
if api_def.uri in self.registered_base_handlers:
|
||||
# reserved handler or already registered
|
||||
return
|
||||
logging.info(
|
||||
f"Registering remote endpoint - "
|
||||
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
|
||||
f"Websocket: {', '.join(api_def.ws_methods)}")
|
||||
self.wsm.register_remote_handler(api_def)
|
||||
params = {}
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['remote_callback'] = api_def.endpoint
|
||||
self.mutable_router.add_handler(
|
||||
api_def.uri, RemoteRequestHandler, params)
|
||||
self.registered_base_handlers.append(api_def.uri)
|
||||
|
||||
def register_local_handler(self, uri, request_methods,
|
||||
callback, protocol=["http", "websocket"]):
|
||||
if uri in self.registered_base_handlers:
|
||||
return
|
||||
api_def = self._create_api_definition(
|
||||
uri, request_methods, is_remote=False)
|
||||
msg = "Registering local endpoint"
|
||||
if "http" in protocol:
|
||||
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
|
||||
params = {}
|
||||
params['methods'] = request_methods
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['callback'] = callback
|
||||
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
|
||||
self.registered_base_handlers.append(uri)
|
||||
if "websocket" in protocol:
|
||||
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
|
||||
self.wsm.register_local_handler(api_def, callback)
|
||||
logging.info(msg)
|
||||
|
||||
def register_static_file_handler(self, pattern, file_path):
|
||||
if pattern[0] != "/":
|
||||
pattern = "/server/files/" + pattern
|
||||
if os.path.isfile(file_path):
|
||||
pattern += '()'
|
||||
elif os.path.isdir(file_path):
|
||||
if pattern[-1] != "/":
|
||||
pattern += "/"
|
||||
pattern += "(.*)"
|
||||
else:
|
||||
logging.info(f"Invalid file path: {file_path}")
|
||||
return
|
||||
logging.debug(f"Registering static file: ({pattern}) {file_path}")
|
||||
params = {'path': file_path}
|
||||
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
|
||||
|
||||
def register_upload_handler(self, pattern):
|
||||
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
|
||||
|
||||
def remove_handler(self, endpoint):
|
||||
api_def = self.api_cache.get(endpoint)
|
||||
if api_def is not None:
|
||||
self.wsm.remove_handler(api_def.uri)
|
||||
self.mutable_router.remove_handler(api_def.ws_method)
|
||||
|
||||
def _create_api_definition(self, endpoint, request_methods=[],
|
||||
is_remote=True):
|
||||
if endpoint in self.api_cache:
|
||||
return self.api_cache[endpoint]
|
||||
if endpoint[0] == '/':
|
||||
uri = endpoint
|
||||
elif is_remote:
|
||||
uri = "/printer/" + endpoint
|
||||
else:
|
||||
uri = "/server/" + endpoint
|
||||
ws_methods = []
|
||||
if is_remote:
|
||||
# Remote requests accept both GET and POST requests. These
|
||||
# requests execute the same callback, thus they resolve to
|
||||
# only a single websocket method.
|
||||
ws_methods.append(uri[1:].replace('/', '.'))
|
||||
request_methods = ['GET', 'POST']
|
||||
else:
|
||||
name_parts = uri[1:].split('/')
|
||||
if len(request_methods) > 1:
|
||||
for req_mthd in request_methods:
|
||||
func_name = req_mthd.lower() + "_" + name_parts[-1]
|
||||
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
|
||||
else:
|
||||
ws_methods.append(".".join(name_parts))
|
||||
if not is_remote and len(request_methods) != len(ws_methods):
|
||||
raise self.server.error(
|
||||
"Invalid API definition. Number of websocket methods must "
|
||||
"match the number of request methods")
|
||||
if endpoint.startswith("objects/"):
|
||||
parser = _status_parser
|
||||
else:
|
||||
parser = _default_parser
|
||||
|
||||
api_def = APIDefinition(endpoint, uri, ws_methods,
|
||||
request_methods, parser)
|
||||
self.api_cache[endpoint] = api_def
|
||||
return api_def
|
||||
|
||||
# ***** Dynamic Handlers*****
|
||||
class RemoteRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, remote_callback, arg_parser):
|
||||
super(RemoteRequestHandler, self).initialize()
|
||||
self.remote_callback = remote_callback
|
||||
self.query_parser = arg_parser
|
||||
|
||||
async def get(self):
|
||||
await self._process_http_request()
|
||||
|
||||
async def post(self):
|
||||
await self._process_http_request()
|
||||
|
||||
async def _process_http_request(self):
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.server.make_request(
|
||||
WebRequest(self.remote_callback, args, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, callback, methods, arg_parser):
|
||||
super(LocalRequestHandler, self).initialize()
|
||||
self.callback = callback
|
||||
self.methods = methods
|
||||
self.query_parser = arg_parser
|
||||
|
||||
async def get(self):
|
||||
if 'GET' in self.methods:
|
||||
await self._process_http_request('GET')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def post(self):
|
||||
if 'POST' in self.methods:
|
||||
await self._process_http_request('POST')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def delete(self):
|
||||
if 'DELETE' in self.methods:
|
||||
await self._process_http_request('DELETE')
|
||||
else:
|
||||
raise tornado.web.HTTPError(405)
|
||||
|
||||
async def _process_http_request(self, method):
|
||||
conn = self.get_associated_websocket()
|
||||
args = self.query_parser(self)
|
||||
try:
|
||||
result = await self.callback(
|
||||
WebRequest(self.request.path, args, method, conn=conn))
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e)) from e
|
||||
self.finish({'result': result})
|
||||
|
||||
|
||||
class FileRequestHandler(AuthorizedFileHandler):
|
||||
def set_extra_headers(self, path):
|
||||
# The call below shold never return an empty string,
|
||||
# as the path should have already been validated to be
|
||||
# a file
|
||||
basename = os.path.basename(self.absolute_path)
|
||||
self.set_header(
|
||||
"Content-Disposition", f"attachment; filename={basename}")
|
||||
|
||||
async def delete(self, path):
|
||||
path = self.request.path.lstrip("/").split("/", 2)[-1]
|
||||
path = url_unescape(path, plus=False)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
try:
|
||||
filename = await file_manager.delete_file(path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise tornado.web.HTTPError(
|
||||
403, "File is loaded, DELETE not permitted")
|
||||
else:
|
||||
raise tornado.web.HTTPError(e.status_code, str(e))
|
||||
self.finish({'result': filename})
|
||||
|
||||
class FileUploadHandler(AuthorizedRequestHandler):
|
||||
async def post(self):
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
try:
|
||||
result = await file_manager.process_file_upload(self.request)
|
||||
except ServerError as e:
|
||||
raise tornado.web.HTTPError(
|
||||
e.status_code, str(e))
|
||||
self.finish(result)
|
||||
|
||||
|
||||
class EmulateOctoprintHandler(AuthorizedRequestHandler):
|
||||
def get(self):
|
||||
self.finish({
|
||||
'server': "1.1.1",
|
||||
'api': "0.1",
|
||||
'text': "OctoPrint Upload Emulator"})
|
||||
@@ -0,0 +1 @@
|
||||
# Assets Package Definition
|
||||
@@ -0,0 +1,10 @@
|
||||
klipper_mcu
|
||||
webcamd
|
||||
MoonCord
|
||||
KlipperScreen
|
||||
moonraker-telegram-bot
|
||||
moonraker-obico
|
||||
sonar
|
||||
crowsnest
|
||||
octoeverywhere
|
||||
ratos-configurator
|
||||
@@ -0,0 +1,502 @@
|
||||
<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. If the
|
||||
front end is hosted on a default port (80 for http, 443 for https),
|
||||
you may remove the port from the address.
|
||||
</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,284 +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 re
|
||||
import logging
|
||||
import tornado
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from utils import ServerError
|
||||
|
||||
TOKEN_TIMEOUT = 5
|
||||
CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300 * 1000
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, config):
|
||||
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
|
||||
self.api_key_file = os.path.expanduser(api_key_file)
|
||||
self.api_key = self._read_api_key()
|
||||
self.auth_enabled = config.getboolean('enabled', True)
|
||||
self.trusted_connections = {}
|
||||
self.access_tokens = {}
|
||||
|
||||
# Get allowed cors domains
|
||||
cors_cfg = config.get('cors_domains', "").strip()
|
||||
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
|
||||
for d in cors_cfg.split('\n')if d.strip()]
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
trusted_clients = config.get('trusted_clients', "")
|
||||
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
|
||||
if c.strip()]
|
||||
for ip in trusted_clients:
|
||||
# Check IP address
|
||||
try:
|
||||
tc = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
tc = None
|
||||
if tc is None:
|
||||
# Check ip network
|
||||
try:
|
||||
tc = ipaddress.ip_network(ip)
|
||||
except ValueError:
|
||||
raise ServerError(
|
||||
f"Invalid option in trusted_clients: {ip}")
|
||||
self.trusted_ranges.append(tc)
|
||||
else:
|
||||
self.trusted_ips.append(tc)
|
||||
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges])
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Auth Enabled: {self.auth_enabled}\n"
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
self.prune_handler.start()
|
||||
|
||||
def register_handlers(self, app):
|
||||
# Register Authorization Endpoints
|
||||
app.register_local_handler(
|
||||
"/access/api_key", ['GET', 'POST'],
|
||||
self._handle_apikey_request, protocol=['http'])
|
||||
app.register_local_handler(
|
||||
"/access/oneshot_token", ['GET'],
|
||||
self._handle_token_request, protocol=['http'])
|
||||
|
||||
async def _handle_apikey_request(self, web_request):
|
||||
action = web_request.get_action()
|
||||
if action.upper() == 'POST':
|
||||
self.api_key = self._create_api_key()
|
||||
return self.api_key
|
||||
|
||||
async def _handle_token_request(self, web_request):
|
||||
return self.get_access_token()
|
||||
|
||||
def _read_api_key(self):
|
||||
if os.path.exists(self.api_key_file):
|
||||
with open(self.api_key_file, 'r') as f:
|
||||
api_key = f.read()
|
||||
return api_key
|
||||
# API Key file doesn't exist. Generate
|
||||
# a new api key and create the file.
|
||||
logging.info(
|
||||
f"No API Key file found, creating new one at:"
|
||||
f"\n{self.api_key_file}")
|
||||
return self._create_api_key()
|
||||
|
||||
def _create_api_key(self):
|
||||
api_key = uuid.uuid4().hex
|
||||
with open(self.api_key_file, 'w') as f:
|
||||
f.write(api_key)
|
||||
return api_key
|
||||
|
||||
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(
|
||||
f"Trusted Connection Expired, IP: {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(
|
||||
f"Trusted Connection Detected, IP: {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(
|
||||
f"Unable to Create IP Address {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 check_cors(self, origin, request=None):
|
||||
if origin is None:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
if match is not None:
|
||||
if match.group() == origin:
|
||||
logging.debug(f"CORS Pattern Matched, origin: {origin} "
|
||||
f" | pattern: {regex}")
|
||||
self._set_cors_headers(origin, request)
|
||||
return True
|
||||
else:
|
||||
logging.debug(f"Partial Cors Match: {match.group()}")
|
||||
else:
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def _set_cors_headers(self, origin, request):
|
||||
if request is None:
|
||||
return
|
||||
request.set_header("Access-Control-Allow-Origin", origin)
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def close(self):
|
||||
self.prune_handler.stop()
|
||||
|
||||
class AuthorizedRequestHandler(tornado.web.RequestHandler):
|
||||
def initialize(self):
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
self.wsm = app.get_websocket_manager()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
# it is necessary to look up the parent app here,
|
||||
# as initialize() may not yet be called
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedRequestHandler, self).options()
|
||||
|
||||
def get_associated_websocket(self):
|
||||
# Return associated websocket connection if an id
|
||||
# was provided by the request
|
||||
conn = None
|
||||
conn_id = self.get_argument('connection_id', None)
|
||||
if conn_id is not None:
|
||||
try:
|
||||
conn_id = int(conn_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
conn = self.wsm.get_websocket(conn_id)
|
||||
return conn
|
||||
|
||||
# Due to the way Python treats multiple inheritance its best
|
||||
# to create a separate authorized handler for serving files
|
||||
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
|
||||
def initialize(self, path, default_filename=None):
|
||||
super(AuthorizedFileHandler, self).initialize(path, default_filename)
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedFileHandler, self).options()
|
||||
+1299
File diff suppressed because it is too large.
Load diff
@@ -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,546 @@
|
||||
# Printer GCode Analysis using Klipper Estimator
|
||||
#
|
||||
# Copyright (C) 2025 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import sys
|
||||
import os
|
||||
import platform
|
||||
import pathlib
|
||||
import stat
|
||||
import re
|
||||
import logging
|
||||
import asyncio
|
||||
import shlex
|
||||
from ..common import RequestType
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
Any,
|
||||
Tuple
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .update_manager.update_manager import UpdateManager
|
||||
from .application import MoonrakerApp
|
||||
from .klippy_connection import KlippyConnection
|
||||
from .authorization import Authorization
|
||||
from .file_manager.file_manager import FileManager
|
||||
from .machine import Machine
|
||||
from .shell_command import ShellCommandFactory
|
||||
from .http_client import HttpClient
|
||||
StrOrPath = Union[str, pathlib.Path]
|
||||
|
||||
ESTIMATOR_URL = (
|
||||
"https://github.com/Annex-Engineering/klipper_estimator/"
|
||||
"releases/latest/download/{asset}"
|
||||
)
|
||||
UPDATE_CONFIG = {
|
||||
"type": "executable",
|
||||
"channel": "stable",
|
||||
"repo": "Annex-Engineering/klipper_estimator",
|
||||
"is_system_service": "False",
|
||||
"path": ""
|
||||
}
|
||||
RELEASE_INFO = {
|
||||
"project_name": "klipper_estimator",
|
||||
"project_owner": "Annex-Engineering",
|
||||
"version": "",
|
||||
"asset_name": ""
|
||||
}
|
||||
|
||||
IDENT_REGEX = r"^; Processed by klipper_estimator (?P<version>v?\d+(?:\.\d+)*)"
|
||||
|
||||
def _check_processed(gc_path: pathlib.Path) -> str | None:
|
||||
size = gc_path.stat().st_size
|
||||
# Read the last 64K
|
||||
start = max(0, size - (64 * 1024))
|
||||
with gc_path.open("rb") as f:
|
||||
if start:
|
||||
f.seek(start)
|
||||
data = f.read().decode(errors="ignore")
|
||||
# If Klipper Estimator is processed multiple times it will
|
||||
# add a new identifier for each one.
|
||||
versions = re.findall(IDENT_REGEX, data, re.MULTILINE)
|
||||
if not versions:
|
||||
return None
|
||||
return versions[-1]
|
||||
|
||||
class GcodeAnalysis:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.cmd_lock = asyncio.Lock()
|
||||
self.file_manger: FileManager = self.server.lookup_component("file_manager")
|
||||
data_path = self.server.get_app_args()["data_path"]
|
||||
tool_folder = pathlib.Path(data_path).joinpath("tools/klipper_estimator")
|
||||
if not tool_folder.exists():
|
||||
tool_folder.mkdir(parents=True)
|
||||
self.estimator_timeout = config.getint("estimator_timeout", 600)
|
||||
self.auto_analyze = config.getboolean("enable_auto_analysis", False)
|
||||
self.auto_dump_defcfg = config.getboolean("auto_dump_default_config", False)
|
||||
self.default_config = tool_folder.joinpath("default_estimator_cfg.json")
|
||||
self.estimator_config = self.default_config
|
||||
est_config = config.get("estimator_config", None)
|
||||
if est_config is not None:
|
||||
est_path = self.file_manger.get_full_path("config", est_config.strip("/"))
|
||||
if ".." in est_path.parts:
|
||||
raise config.error(
|
||||
"Value for option 'estimator_config' must not contain "
|
||||
"a '..' segment"
|
||||
)
|
||||
if not est_path.exists():
|
||||
raise config.error(
|
||||
f"File '{est_config}' does not exist in 'config' root"
|
||||
)
|
||||
self.estimator_config = est_path
|
||||
self.estimator_path: pathlib.Path | None = None
|
||||
self.estimator_ready: bool = False
|
||||
self.estimator_version: str = "?"
|
||||
pltform_choices = ["rpi", "linux", "osx", "auto"]
|
||||
pltform = config.getchoice("platform", pltform_choices, default_key="auto")
|
||||
if pltform == "auto":
|
||||
auto_pfrm = self._detect_platform()
|
||||
if auto_pfrm is not None:
|
||||
self.estimator_path = tool_folder.joinpath(
|
||||
f"klipper_estimator_{auto_pfrm}"
|
||||
)
|
||||
else:
|
||||
exec_name = f"klipper_estimator_{pltform}"
|
||||
self.estimator_path = tool_folder.joinpath(exec_name)
|
||||
enable_updates = config.getboolean("enable_estimator_updates", False)
|
||||
self.updater_registered: bool = False
|
||||
if enable_updates:
|
||||
if self.estimator_path is None:
|
||||
logging.info(
|
||||
"Klipper estimator platform not detected, updates disabled"
|
||||
)
|
||||
elif not config.has_section("update_manager"):
|
||||
logging.info("Update Manager not configured, updates disabled")
|
||||
else:
|
||||
try:
|
||||
um: UpdateManager
|
||||
um = self.server.load_component(config, "update_manager")
|
||||
updater_cfg = UPDATE_CONFIG
|
||||
updater_cfg["path"] = str(tool_folder)
|
||||
um.register_updater("klipper_estimator", updater_cfg)
|
||||
except self.server.error:
|
||||
logging.exception("Klipper Estimator update registration failed")
|
||||
else:
|
||||
self.updater_registered = True
|
||||
if not self.updater_registered:
|
||||
# Add reserved path when updates are disabled
|
||||
self.file_manger.add_reserved_path("analysis", tool_folder, False)
|
||||
# Register Klipper Estimator's GCode Processor configuration
|
||||
# with the metadata processor. Keep a reference to the config
|
||||
# so it can be updated after the Klipper Estimator Executable is
|
||||
# verified in component_init().
|
||||
self.proc_config: Dict[str, Any] = {
|
||||
"name": "klipper_estimator",
|
||||
"command": [
|
||||
str(self.estimator_path),
|
||||
"--config_file",
|
||||
str(self.estimator_config),
|
||||
"post-process",
|
||||
"{gcode_file_path}"
|
||||
],
|
||||
"timeout": self.estimator_timeout,
|
||||
"version": self.estimator_version,
|
||||
"ident": {
|
||||
"regex": IDENT_REGEX,
|
||||
"location": "footer"
|
||||
},
|
||||
"enabled": False
|
||||
}
|
||||
mdst = self.file_manger.get_metadata_storage()
|
||||
mdst.register_gcode_processor("klipper_estimator", self.proc_config)
|
||||
self.server.register_endpoint(
|
||||
"/server/analysis/status", RequestType.GET,
|
||||
self._handle_status_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/analysis/estimate", RequestType.POST,
|
||||
self._handle_estimator_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/analysis/process", RequestType.POST,
|
||||
self._handle_estimator_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/analysis/dump_config", RequestType.POST,
|
||||
self._handle_dump_cfg_request
|
||||
)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._on_klippy_ready
|
||||
)
|
||||
|
||||
@property
|
||||
def estimator_version_tuple(self) -> Tuple[int, ...]:
|
||||
if self.estimator_version in ["?", ""]:
|
||||
return tuple()
|
||||
ver_string = self.estimator_version
|
||||
if ver_string[0] == "v":
|
||||
ver_string = ver_string[1:]
|
||||
return tuple([int(p) for p in ver_string.split(".")])
|
||||
|
||||
async def _on_klippy_ready(self) -> None:
|
||||
if not self.estimator_ready:
|
||||
return
|
||||
if self.auto_dump_defcfg or not self.default_config.exists():
|
||||
logging.info(
|
||||
"Dumping default Klipper Estimator configuration to "
|
||||
f"{self.default_config}"
|
||||
)
|
||||
eventloop = self.server.get_event_loop()
|
||||
if (
|
||||
self.auto_analyze and
|
||||
self.default_config == self.estimator_config and
|
||||
not self.default_config.exists()
|
||||
):
|
||||
async def _dump_and_update_proc_cfg() -> None:
|
||||
await self._dump_estimator_config(self.default_config)
|
||||
self._update_gcode_proc_config()
|
||||
eventloop.create_task(_dump_and_update_proc_cfg())
|
||||
else:
|
||||
eventloop.create_task(self._dump_estimator_config(self.default_config))
|
||||
|
||||
async def component_init(self) -> None:
|
||||
if self.estimator_path is not None:
|
||||
if not self.estimator_path.exists():
|
||||
# Download Klipper Estimator
|
||||
await self._download_klipper_estimator(self.estimator_path)
|
||||
if not self._check_estimator_perms(self.estimator_path):
|
||||
self.server.add_warning(
|
||||
"[analysis]: Moonraker lacks permission to execute "
|
||||
"Klipper Estimator"
|
||||
)
|
||||
else:
|
||||
await self._detect_estimator_version()
|
||||
if self.estimator_version == "?":
|
||||
logging.info("Failed to initialize Klipper Estimator")
|
||||
else:
|
||||
await self._check_release_info(self.estimator_path)
|
||||
self.estimator_ready = True
|
||||
logging.info(
|
||||
f"Klipper Estimator Version {self.estimator_version} detected"
|
||||
)
|
||||
self._update_gcode_proc_config()
|
||||
|
||||
def _update_gcode_proc_config(self) -> None:
|
||||
self.proc_config["version"] = self.estimator_version
|
||||
enabled = False
|
||||
if self.auto_analyze:
|
||||
if not self.estimator_ready:
|
||||
enabled = False
|
||||
logging.info(
|
||||
"Klipper Estimator executable failed validation, "
|
||||
"auto analysis disabled."
|
||||
)
|
||||
elif not self.estimator_config.is_file():
|
||||
enabled = False
|
||||
logging.info(
|
||||
"Klipper Estimator config file does not exist, "
|
||||
"auto analysis disabled."
|
||||
)
|
||||
else:
|
||||
logging.info("Klipper Estimator Auto Analysis Enabled")
|
||||
enabled = True
|
||||
self.proc_config["enabled"] = enabled
|
||||
|
||||
def _detect_platform(self) -> Optional[str]:
|
||||
# Detect OS
|
||||
if sys.platform.startswith("darwin"):
|
||||
return "osx"
|
||||
elif sys.platform.startswith("linux"):
|
||||
# Get architecture
|
||||
arch: str = platform.machine()
|
||||
if not arch:
|
||||
self.server.add_warning(
|
||||
"[analysis]: Failed to detect CPU architecture. "
|
||||
"Manual configuration of the 'platform' option is required.",
|
||||
"analysis_estimator"
|
||||
)
|
||||
return None
|
||||
if arch == "x86_64":
|
||||
return "linux"
|
||||
elif arch in ("armv7l", "aarch64"):
|
||||
# TODO: Other platforms may work, not sure
|
||||
return "rpi"
|
||||
else:
|
||||
self.server.add_warning(
|
||||
f"[analysis]: Unsupported CPU architecture '{arch}'. "
|
||||
"Manual configuration of the 'platform' option is required.",
|
||||
"analysis_estimator"
|
||||
)
|
||||
return None
|
||||
else:
|
||||
self.server.add_warning(
|
||||
f"[analysis]: Unsupported platform '{sys.platform}'. "
|
||||
"Manual configuration of the 'platform' option is required.",
|
||||
"analysis_estimator"
|
||||
)
|
||||
|
||||
async def _download_klipper_estimator(self, estimator_path: pathlib.Path) -> None:
|
||||
"""
|
||||
Download Klipper Estimator, set executable permissions, and generate
|
||||
the release_info.json file
|
||||
"""
|
||||
async with self.cmd_lock:
|
||||
est_name = estimator_path.name
|
||||
logging.info(f"Downloading latest {est_name}...")
|
||||
url = ESTIMATOR_URL.format(asset=est_name)
|
||||
http_client: HttpClient = self.server.lookup_component("http_client")
|
||||
try:
|
||||
await http_client.download_file(
|
||||
url, "application/octet-stream", estimator_path
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception("Failed to download Klipper estimator")
|
||||
else:
|
||||
logging.info("Klipper Estimator download complete.")
|
||||
|
||||
async def _detect_estimator_version(self) -> None:
|
||||
cmd = f"{self.estimator_path} --version"
|
||||
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
|
||||
ret = await scmd.exec_cmd(cmd, timeout=10.)
|
||||
ver_match = re.match(r"klipper_estimator (v?\d+(?:\.\d+)*)", ret)
|
||||
if ver_match is None:
|
||||
self.estimator_version = "?"
|
||||
else:
|
||||
self.estimator_version = ver_match.group(1)
|
||||
|
||||
def _check_estimator_perms(self, estimator_path: pathlib.Path) -> bool:
|
||||
if not estimator_path.is_file():
|
||||
return False
|
||||
req_perms = stat.S_IXUSR | stat.S_IXGRP
|
||||
kest_perms = stat.S_IMODE(estimator_path.stat().st_mode)
|
||||
if req_perms & kest_perms != req_perms:
|
||||
logging.info("Setting executable permissions for Klipper Estimator...")
|
||||
try:
|
||||
estimator_path.chmod(kest_perms | req_perms)
|
||||
except OSError:
|
||||
logging.exception(
|
||||
"Failed to set Klipper Estimator Permissions"
|
||||
)
|
||||
return os.access(estimator_path, os.X_OK)
|
||||
|
||||
async def _check_release_info(self, estimator_path: pathlib.Path) -> None:
|
||||
rinfo_file = estimator_path.parent.joinpath("release_info.json")
|
||||
if rinfo_file.is_file():
|
||||
return
|
||||
logging.info("Creating release_info.json for Klipper Estimator...")
|
||||
rinfo = dict(RELEASE_INFO)
|
||||
rinfo["version"] = self.estimator_version
|
||||
rinfo["asset_name"] = estimator_path.name
|
||||
eventloop = self.server.get_event_loop()
|
||||
await eventloop.run_in_thread(rinfo_file.write_bytes, jsonw.dumps(rinfo))
|
||||
if self.updater_registered:
|
||||
logging.info("Refreshing Klipper Estimator Updater Instance...")
|
||||
um: UpdateManager = self.server.lookup_component("update_manager")
|
||||
eventloop.create_task(um.refresh_updater("klipper_estimator", True))
|
||||
|
||||
def _get_moonraker_url(self) -> str:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
app: MoonrakerApp = self.server.lookup_component("application")
|
||||
host_info = self.server.get_host_info()
|
||||
host_addr: str = host_info["address"]
|
||||
if host_addr.lower() in ("all", "0.0.0.0", "localhost", "127.0.0.1"):
|
||||
address = "127.0.0.1"
|
||||
elif host_addr.lower() == "::":
|
||||
address = "::1"
|
||||
else:
|
||||
address = machine.public_ip
|
||||
if not address:
|
||||
address = f"{host_info['hostname']}.local"
|
||||
elif ":" in address:
|
||||
# ipv6 address
|
||||
address = f"[{address}]"
|
||||
port = host_info["port"]
|
||||
return f"http://{address}:{port}{app.route_prefix}"
|
||||
|
||||
def _gen_estimator_cmd(
|
||||
self,
|
||||
gc_path: pathlib.Path,
|
||||
est_cfg_path: pathlib.Path,
|
||||
is_post_process: bool = False
|
||||
) -> str:
|
||||
if self.estimator_path is None or not self.estimator_ready:
|
||||
raise self.server.error("Klipper Estimator not available")
|
||||
if not est_cfg_path.exists():
|
||||
raise self.server.error(
|
||||
f"Klipper Estimator config {est_cfg_path.name} does not exist"
|
||||
)
|
||||
action = "post-process" if is_post_process else "estimate -f json"
|
||||
cmd = str(self.estimator_path)
|
||||
cmd = f"{cmd} --config_file {shlex.quote(str(est_cfg_path))}"
|
||||
cmd = f"{cmd} {action} {shlex.quote(str(gc_path))}"
|
||||
return cmd
|
||||
|
||||
def _gen_dump_cmd(self) -> str:
|
||||
if self.estimator_path is None or not self.estimator_ready:
|
||||
raise self.server.error("Klipper Estimator not available")
|
||||
return f"{self.estimator_path} {self._gen_url_opts()} dump-config"
|
||||
|
||||
def _gen_url_opts(self) -> str:
|
||||
url = self._get_moonraker_url()
|
||||
opts = f"--config_moonraker_url {url}"
|
||||
auth: Optional[Authorization]
|
||||
auth = self.server.lookup_component("authorization", None)
|
||||
api_key = auth.get_api_key() if auth is not None else None
|
||||
if api_key is not None:
|
||||
opts = f"{opts} --config_moonraker_api_key {api_key}"
|
||||
return opts
|
||||
|
||||
async def _dump_estimator_config(self, dest: pathlib.Path) -> Dict[str, Any]:
|
||||
async with self.cmd_lock:
|
||||
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
|
||||
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
|
||||
eventloop = self.server.get_event_loop()
|
||||
if not kconn.is_ready():
|
||||
raise self.server.error(
|
||||
"Klipper Estimator cannot dump configuration, Klippy not ready",
|
||||
504
|
||||
)
|
||||
dump_cmd = self._gen_dump_cmd()
|
||||
try:
|
||||
ret = await scmd.exec_cmd(
|
||||
dump_cmd, timeout=10., log_complete=False, log_stderr=True
|
||||
)
|
||||
await eventloop.run_in_thread(dest.write_text, ret)
|
||||
except scmd.error:
|
||||
raise self.server.error(
|
||||
"Klipper Estimator dump-config failed", 500
|
||||
) from None
|
||||
return jsonw.loads(ret)
|
||||
|
||||
async def estimate_file(
|
||||
self, gc_path: pathlib.Path, est_config: Optional[pathlib.Path] = None
|
||||
) -> Dict[str, Any]:
|
||||
async with self.cmd_lock:
|
||||
if est_config is None:
|
||||
# Fall back to estimator config specified in the [analysis] section.
|
||||
est_config = self.estimator_config
|
||||
if not est_config.is_file():
|
||||
raise self.server.error(
|
||||
f"Estimator config file '{est_config}' does not exist"
|
||||
)
|
||||
if not gc_path.is_file():
|
||||
raise self.server.error(f"GCode File '{gc_path}' does not exist")
|
||||
scmd: ShellCommandFactory = self.server.lookup_component("shell_command")
|
||||
est_cmd = self._gen_estimator_cmd(gc_path, est_config)
|
||||
ret = await scmd.exec_cmd(est_cmd, self.estimator_timeout)
|
||||
data = jsonw.loads(ret)
|
||||
return data["sequences"][0]
|
||||
|
||||
async def post_process_file(
|
||||
self,
|
||||
gc_path: pathlib.Path,
|
||||
est_config: Optional[pathlib.Path] = None,
|
||||
force: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
async with self.cmd_lock:
|
||||
if est_config is None:
|
||||
# Fall back to estimator config specified in the [analysis] section.
|
||||
est_config = self.estimator_config
|
||||
if not est_config.is_file():
|
||||
raise self.server.error(
|
||||
f"Estimator config file '{est_config}' does not exist"
|
||||
)
|
||||
if not gc_path.is_file():
|
||||
raise self.server.error(f"GCode File '{gc_path}' does not exist")
|
||||
eventloop = self.server.get_event_loop()
|
||||
proc_ver = await eventloop.run_in_thread(_check_processed, gc_path)
|
||||
bypassed = processed = proc_ver is not None
|
||||
if not processed or force:
|
||||
scmd: ShellCommandFactory
|
||||
scmd = self.server.lookup_component("shell_command")
|
||||
pp_cmd = self._gen_estimator_cmd(gc_path, est_config, True)
|
||||
await scmd.exec_cmd(pp_cmd, self.estimator_timeout)
|
||||
proc_ver = self.estimator_version
|
||||
bypassed = False
|
||||
else:
|
||||
logging.info(f"File {gc_path.name} already processed, aborting")
|
||||
return {
|
||||
"prev_processed": processed,
|
||||
"version": proc_ver,
|
||||
"bypassed": bypassed,
|
||||
}
|
||||
|
||||
async def _handle_status_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
est_exec = "unknown"
|
||||
if self.estimator_path is not None:
|
||||
est_exec = self.estimator_path.name
|
||||
is_default = self.estimator_config == self.default_config
|
||||
return {
|
||||
"estimator_executable": est_exec,
|
||||
"estimator_ready": self.estimator_ready,
|
||||
"estimator_version": self.estimator_version,
|
||||
"estimator_config_exists": self.estimator_config.exists(),
|
||||
"using_default_config": is_default
|
||||
}
|
||||
|
||||
async def _handle_estimator_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
gcode_file = web_request.get_str("filename").strip("/")
|
||||
estimator_config = web_request.get_str("estimator_config", None)
|
||||
gc_path = self.file_manger.get_full_path("gcodes", gcode_file)
|
||||
if not gc_path.is_file():
|
||||
raise self.server.error(
|
||||
f"GCode File '{gcode_file}' does not exit in gcodes path"
|
||||
)
|
||||
est_cfg_path = self.estimator_config
|
||||
if estimator_config is not None:
|
||||
estimator_config = estimator_config.strip("/")
|
||||
est_cfg_path = self.file_manger.get_full_path("config", estimator_config)
|
||||
if ".." in est_cfg_path.parts:
|
||||
raise self.server.error(
|
||||
"Invalid value for param 'estimator_config', '..' segments "
|
||||
"are not allowed"
|
||||
)
|
||||
ep = web_request.get_endpoint().split("/")[-1]
|
||||
if ep == "estimate":
|
||||
ret = await self.estimate_file(gc_path, est_cfg_path)
|
||||
elif ep == "process":
|
||||
force = web_request.get_boolean("force", False)
|
||||
ret = await self.post_process_file(gc_path, est_cfg_path, force)
|
||||
else:
|
||||
raise self.server.error(f"Unknown request {ep}", 404)
|
||||
return ret
|
||||
|
||||
async def _handle_dump_cfg_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
dest = web_request.get_str("dest_config", None)
|
||||
root: str | None = None
|
||||
if dest is not None:
|
||||
root = "config"
|
||||
dest = dest.strip("/")
|
||||
if ".." in pathlib.Path(dest).parts:
|
||||
raise self.server.error(
|
||||
"Parameter 'dest_config' may not contain '..' parts"
|
||||
)
|
||||
dest_config = self.file_manger.get_full_path("config", dest)
|
||||
else:
|
||||
dest = self.default_config.name
|
||||
dest_config = self.default_config
|
||||
result = await self._dump_estimator_config(dest_config)
|
||||
return {
|
||||
"dest_root": root,
|
||||
"dest_config_path": dest,
|
||||
"klipper_estimator_config": result
|
||||
}
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> GcodeAnalysis:
|
||||
return GcodeAnalysis(config)
|
||||
@@ -0,0 +1,556 @@
|
||||
# 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 ..common import RequestType
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
List,
|
||||
Dict,
|
||||
Any,
|
||||
Optional
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common 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", RequestType.GET,
|
||||
self._list_announcements
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/dismiss", RequestType.POST,
|
||||
self._handle_dismiss_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/update", RequestType.POST,
|
||||
self._handle_update_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/feed", RequestType.POST | RequestType.DELETE,
|
||||
self._handle_feed_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/announcements/feeds", RequestType.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 = web_request.get_list("subscriptions", 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]:
|
||||
req_type = web_request.get_request_type()
|
||||
name: str = web_request.get("name")
|
||||
name = name.lower()
|
||||
changed: bool = False
|
||||
db: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
result = "skipped"
|
||||
if req_type == RequestType.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 req_type == RequestType.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)
|
||||
self.eventloop.create_task(self._notify_internal())
|
||||
return entry
|
||||
|
||||
async def _notify_internal(self) -> None:
|
||||
entries = await self.entry_mgr.list_entries()
|
||||
self.server.send_event(
|
||||
"announcements:entries_updated", {"entries": entries}
|
||||
)
|
||||
|
||||
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 register_feed(self, name: str) -> None:
|
||||
name = name.lower()
|
||||
if name in self.subscriptions:
|
||||
logging.info(f"Feed {name} already configured")
|
||||
return
|
||||
logging.info(f"Registering feed {name}")
|
||||
self.configured_feeds.append(name)
|
||||
self.subscriptions[name] = RssFeed(name, self.entry_mgr, self.dev_mode)
|
||||
|
||||
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:
|
||||
data_path = pathlib.Path(self.server.get_app_arg("data_path"))
|
||||
dev_folder = data_path.joinpath("development/announcements")
|
||||
dev_folder.mkdir(parents=True, exist_ok=True)
|
||||
self.dev_xml_path = dev_folder.joinpath(self.xml_file)
|
||||
logging.info(
|
||||
f"Announcement Feed {name}: Dev XML path set to {self.dev_xml_path}"
|
||||
)
|
||||
|
||||
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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,941 @@
|
||||
# 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
|
||||
from tornado.web import HTTPError
|
||||
from libnacl.sign import Signer, Verifier
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from ..common import RequestType, TransportType, SqlTableDefinition, UserInfo
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .websockets import WebsocketManager
|
||||
from tornado.httputil import HTTPServerRequest
|
||||
from .database import MoonrakerDatabase as DBComp
|
||||
from .database import DBProviderWrapper
|
||||
from .ldap import MoonrakerLDAP
|
||||
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
||||
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
|
||||
OneshotToken = Tuple[IPAddr, Optional[UserInfo], 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
|
||||
FQDN_CACHE_TIMEOUT = 84000
|
||||
PRUNE_CHECK_TIME = 300.
|
||||
|
||||
USER_TABLE = "authorized_users"
|
||||
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 UserSqlDefinition(SqlTableDefinition):
|
||||
name = USER_TABLE
|
||||
prototype = (
|
||||
f"""
|
||||
{USER_TABLE} (
|
||||
username TEXT PRIMARY KEY NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
created_on REAL NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
jwt_secret TEXT,
|
||||
jwk_id TEXT,
|
||||
groups pyjson
|
||||
)
|
||||
"""
|
||||
)
|
||||
version = 1
|
||||
|
||||
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
|
||||
if last_version == 0:
|
||||
users: Dict[str, Dict[str, Any]]
|
||||
users = db_provider.get_namespace("authorized_users")
|
||||
api_user = users.pop(API_USER, {})
|
||||
if not isinstance(api_user, dict):
|
||||
api_user = {}
|
||||
user_vals: List[Tuple[Any, ...]] = [
|
||||
UserInfo(
|
||||
username=API_USER,
|
||||
password=api_user.get("api_key", uuid.uuid4().hex),
|
||||
created_on=api_user.get("created_on", time.time())
|
||||
).as_tuple()
|
||||
]
|
||||
for key, user in users.items():
|
||||
if not isinstance(user, dict):
|
||||
logging.info(
|
||||
f"Auth migration, skipping invalid value: {key} {user}"
|
||||
)
|
||||
continue
|
||||
user_vals.append(UserInfo(**user).as_tuple())
|
||||
placeholders = ",".join("?" * len(user_vals[0]))
|
||||
conn = db_provider.connection
|
||||
with conn:
|
||||
conn.executemany(
|
||||
f"INSERT OR IGNORE INTO {USER_TABLE} VALUES({placeholders})",
|
||||
user_vals
|
||||
)
|
||||
db_provider.wipe_local_namespace("authorized_users")
|
||||
|
||||
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] = {}
|
||||
self.fqdn_cache: Dict[IPAddr, Dict[str, Any]] = {}
|
||||
if self.default_source not in AUTH_SOURCES:
|
||||
self.server.add_warning(
|
||||
"[authorization]: option 'default_source' - Invalid "
|
||||
f"value '{self.default_source}', falling back to "
|
||||
"'moonraker'."
|
||||
)
|
||||
self.default_source = "moonraker"
|
||||
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')
|
||||
self.user_table = database.register_table(UserSqlDefinition())
|
||||
self.users: Dict[str, UserInfo] = {}
|
||||
self.api_key = uuid.uuid4().hex
|
||||
hi = self.server.get_host_info()
|
||||
self.issuer = f"http://{hi['hostname']}:{hi['port']}"
|
||||
self.public_jwks: Dict[str, Dict[str, Any]] = {}
|
||||
self.trusted_users: Dict[IPAddr, Dict[str, Any]] = {}
|
||||
self.oneshot_tokens: Dict[str, OneshotToken] = {}
|
||||
|
||||
# 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:
|
||||
self.server.add_warning(
|
||||
f"[authorization]: Unsafe domain '{domain}' in option "
|
||||
f"'cors_domains'. Wildcards are not permitted in the"
|
||||
" top level domain."
|
||||
)
|
||||
continue
|
||||
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.server.register_endpoint(
|
||||
"/access/login", RequestType.POST, self._handle_login,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET,
|
||||
auth_required=False
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/logout", RequestType.POST, self._handle_logout,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/refresh_jwt", RequestType.POST, self._handle_refresh_jwt,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET,
|
||||
auth_required=False
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/user", RequestType.all(), self._handle_user_request,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/users/list", RequestType.GET, self._handle_list_request,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/user/password", RequestType.POST, self._handle_password_reset,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/api_key", RequestType.GET | RequestType.POST,
|
||||
self._handle_apikey_request,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/oneshot_token", RequestType.GET, self._handle_oneshot_request,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/access/info", RequestType.GET, self._handle_info_request,
|
||||
transports=TransportType.HTTP | TransportType.WEBSOCKET,
|
||||
auth_required=False
|
||||
)
|
||||
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"
|
||||
)
|
||||
|
||||
async def component_init(self) -> None:
|
||||
# Populate users from database
|
||||
cursor = await self.user_table.execute(f"SELECT * FROM {USER_TABLE}")
|
||||
self.users = {row[0]: UserInfo(**dict(row)) for row in await cursor.fetchall()}
|
||||
need_sync = self._initialize_users()
|
||||
if need_sync:
|
||||
await self._sync_user_table()
|
||||
self.prune_timer.start(delay=PRUNE_CHECK_TIME)
|
||||
|
||||
async def _sync_user(self, username: str) -> None:
|
||||
user = self.users[username]
|
||||
vals = user.as_tuple()
|
||||
placeholders = ",".join("?" * len(vals))
|
||||
async with self.user_table as tx:
|
||||
await tx.execute(
|
||||
f"REPLACE INTO {USER_TABLE} VALUES({placeholders})", vals
|
||||
)
|
||||
|
||||
async def _sync_user_table(self) -> None:
|
||||
async with self.user_table as tx:
|
||||
await tx.execute(f"DELETE FROM {USER_TABLE}")
|
||||
user_vals: List[Tuple[Any, ...]]
|
||||
user_vals = [user.as_tuple() for user in self.users.values()]
|
||||
if not user_vals:
|
||||
return
|
||||
placeholders = ",".join("?" * len(user_vals[0]))
|
||||
await tx.executemany(
|
||||
f"INSERT INTO {USER_TABLE} VALUES({placeholders})", user_vals
|
||||
)
|
||||
|
||||
def _initialize_users(self) -> bool:
|
||||
need_sync = False
|
||||
api_user: Optional[UserInfo] = self.users.get(API_USER, None)
|
||||
if api_user is None:
|
||||
need_sync = True
|
||||
self.users[API_USER] = UserInfo(username=API_USER, password=self.api_key)
|
||||
else:
|
||||
self.api_key = api_user.password
|
||||
for username, user_info in list(self.users.items()):
|
||||
if username == API_USER:
|
||||
continue
|
||||
# generate jwks for valid users
|
||||
if user_info.jwt_secret is not None:
|
||||
try:
|
||||
priv_key = self._load_private_key(user_info.jwt_secret)
|
||||
jwk_id = user_info.jwk_id
|
||||
assert jwk_id is not None
|
||||
except (self.server.error, KeyError, AssertionError):
|
||||
logging.info("Invalid jwk found for user, removing")
|
||||
user_info.jwt_secret = None
|
||||
user_info.jwk_id = None
|
||||
self.users[username] = user_info
|
||||
need_sync = True
|
||||
continue
|
||||
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
|
||||
return need_sync
|
||||
|
||||
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
|
||||
if web_request.get_request_type() == RequestType.POST:
|
||||
self.api_key = uuid.uuid4().hex
|
||||
self.users[API_USER].password = self.api_key
|
||||
await 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}")
|
||||
jwk_id: Optional[str] = self.users[username].jwk_id
|
||||
self.users[username].jwt_secret = None
|
||||
self.users[username].jwk_id = None
|
||||
if jwk_id is not None:
|
||||
self.public_jwks.pop(jwk_id, None)
|
||||
await self._sync_user(username)
|
||||
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")
|
||||
login_req = self.force_logins and len(self.users) > 1
|
||||
request_trusted: Optional[bool] = None
|
||||
user = web_request.get_current_user()
|
||||
req_ip = web_request.ip_addr
|
||||
if user is not None and user.username == TRUSTED_USER:
|
||||
request_trusted = True
|
||||
elif req_ip is not None:
|
||||
request_trusted = await self._check_authorized_ip(req_ip)
|
||||
return {
|
||||
"default_source": self.default_source,
|
||||
"available_sources": sources,
|
||||
"login_required": login_req,
|
||||
"trusted": request_trusted
|
||||
}
|
||||
|
||||
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 user_info.jwt_secret is None or user_info.jwk_id is None:
|
||||
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.source,
|
||||
'action': 'user_jwt_refresh'
|
||||
}
|
||||
|
||||
async def _handle_user_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
req_type = web_request.get_request_type()
|
||||
if req_type == RequestType.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.source,
|
||||
"created_on": user.created_on
|
||||
}
|
||||
elif req_type == RequestType.POST:
|
||||
# Create User
|
||||
return await self._login_jwt_user(web_request, new_user_request=True)
|
||||
elif req_type == RequestType.DELETE:
|
||||
# Delete User
|
||||
return await 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.source,
|
||||
'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.source == "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
|
||||
await self._sync_user(username)
|
||||
return {
|
||||
'username': username,
|
||||
'action': "user_password_reset"
|
||||
}
|
||||
|
||||
async def _login_jwt_user(
|
||||
self, web_request: WebRequest, new_user_request: 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}")
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(f"Invalid Request for user {username}")
|
||||
user_info: UserInfo
|
||||
is_local_user = source == "moonraker"
|
||||
need_create = new_user_request
|
||||
if source == "ldap":
|
||||
if new_user_request:
|
||||
raise self.server.error("Invalid Request to create new LDAP User")
|
||||
if self.ldap is None:
|
||||
raise self.server.error(
|
||||
"LDAP authentication not available", 401
|
||||
)
|
||||
await self.ldap.authenticate_ldap_user(username, password)
|
||||
need_create = username not in self.users
|
||||
if need_create:
|
||||
if username in self.users:
|
||||
raise self.server.error(f"User {username} already exists")
|
||||
if is_local_user:
|
||||
# only generate a hashed password when local authentication
|
||||
# is required
|
||||
salt = secrets.token_bytes(32)
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
else:
|
||||
salt = b""
|
||||
hashed_pass = ""
|
||||
user_info = UserInfo(
|
||||
username=username,
|
||||
password=hashed_pass,
|
||||
salt=salt.hex(),
|
||||
source=source,
|
||||
)
|
||||
self.users[username] = user_info
|
||||
await self._sync_user(username)
|
||||
else:
|
||||
if username not in self.users:
|
||||
raise self.server.error(f"Unregistered User: {username}")
|
||||
user_info = self.users[username]
|
||||
auth_src = user_info.source
|
||||
if auth_src != source:
|
||||
raise self.server.error(
|
||||
f"Moonraker cannot authenticate user '{username}', must "
|
||||
f"specify source '{auth_src}'", 401
|
||||
)
|
||||
if is_local_user:
|
||||
# Only local users require password authentication
|
||||
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")
|
||||
jwt_secret_hex: Optional[str] = user_info.jwt_secret
|
||||
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() # type: ignore
|
||||
user_info.jwk_id = jwk_id
|
||||
self.users[username] = user_info
|
||||
await 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)
|
||||
if user_info.jwk_id is None:
|
||||
user_info.jwk_id = base64url_encode(secrets.token_bytes()).decode()
|
||||
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 new_user_request:
|
||||
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.source,
|
||||
'refresh_token': refresh_token,
|
||||
'action': "user_created" if new_user_request else "user_logged_in"
|
||||
}
|
||||
|
||||
async 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.username
|
||||
if 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[UserInfo] = self.users.get(username)
|
||||
if user_info is None:
|
||||
raise self.server.error(f"No registered user: {username}")
|
||||
if user_info.jwk_id is not None:
|
||||
self.public_jwks.pop(user_info.jwk_id, None)
|
||||
del self.users[username]
|
||||
async with self.user_table as tx:
|
||||
await tx.execute(
|
||||
f"DELETE FROM {USER_TABLE} WHERE username = ?", (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(jsonw.dumps(header))
|
||||
jwt_payload = base64url_encode(jsonw.dumps(payload))
|
||||
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", check_exp: bool = True
|
||||
) -> UserInfo:
|
||||
message, sig = token.rsplit('.', maxsplit=1)
|
||||
enc_header, enc_payload = message.split('.')
|
||||
header: Dict[str, Any] = jsonw.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: Optional[str] = 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] = jsonw.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 check_exp and payload['exp'] < int(time.time()):
|
||||
raise self.server.error("JWT Expired", 401)
|
||||
|
||||
# get user
|
||||
user_info: Optional[UserInfo] = 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) -> UserInfo:
|
||||
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) -> UserInfo:
|
||||
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}")
|
||||
for ip, fqdn_info in list(self.fqdn_cache.items()):
|
||||
exp_time = fqdn_info["expires_at"]
|
||||
if cur_time >= exp_time:
|
||||
domain: str = fqdn_info["domain"]
|
||||
self.fqdn_cache.pop(ip, None)
|
||||
logging.info(f"Cached FQDN Expired, IP: {ip}, domain: {domain}")
|
||||
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[UserInfo]) -> 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, required: bool = True
|
||||
) -> Optional[UserInfo]:
|
||||
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(errors="ignore")
|
||||
elif auth_token.startswith("Bearer "):
|
||||
auth_token = auth_token[7:]
|
||||
else:
|
||||
return None
|
||||
if auth_token:
|
||||
try:
|
||||
return self.decode_jwt(auth_token, check_exp=required)
|
||||
except Exception:
|
||||
logging.exception(f"JWT Decode Error {auth_token}")
|
||||
raise HTTPError(401, "JWT Decode Error")
|
||||
return None
|
||||
|
||||
async 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
|
||||
if self.trusted_domains:
|
||||
if ip in self.fqdn_cache:
|
||||
fqdn: str = self.fqdn_cache[ip]["domain"]
|
||||
else:
|
||||
eventloop = self.server.get_event_loop()
|
||||
try:
|
||||
fut = eventloop.run_in_thread(socket.getfqdn, str(ip))
|
||||
fqdn = await asyncio.wait_for(fut, 5.0)
|
||||
except asyncio.TimeoutError:
|
||||
logging.info("Call to socket.getfqdn() timed out")
|
||||
return False
|
||||
else:
|
||||
fqdn = fqdn.lower()
|
||||
self.fqdn_cache[ip] = {
|
||||
"expires_at": time.time() + FQDN_CACHE_TIMEOUT,
|
||||
"domain": fqdn
|
||||
}
|
||||
return fqdn in self.trusted_domains
|
||||
return False
|
||||
|
||||
async def _check_trusted_connection(
|
||||
self, ip: Optional[IPAddr]
|
||||
) -> Optional[UserInfo]:
|
||||
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]["user"]
|
||||
elif await self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
f"Trusted Connection Detected, IP: {ip}")
|
||||
self.trusted_users[ip] = {
|
||||
"user": UserInfo(TRUSTED_USER, "", curtime),
|
||||
"expires_at": exp_time
|
||||
}
|
||||
return self.trusted_users[ip]["user"]
|
||||
return None
|
||||
|
||||
def _check_oneshot_token(
|
||||
self, token: str, cur_ip: Optional[IPAddr]
|
||||
) -> Optional[UserInfo]:
|
||||
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
|
||||
|
||||
async def authenticate_request(
|
||||
self, request: HTTPServerRequest, auth_required: bool = True
|
||||
) -> Optional[UserInfo]:
|
||||
if request.method == "OPTIONS":
|
||||
return None
|
||||
|
||||
# Check JSON Web Token
|
||||
jwt_user = self._check_json_web_token(request, auth_required)
|
||||
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
|
||||
# then trusted user authentication is disabled
|
||||
if self.force_logins and len(self.users) > 1:
|
||||
if not auth_required:
|
||||
return None
|
||||
raise HTTPError(401, "Unauthorized, Force Logins Enabled")
|
||||
|
||||
# Check if IP is trusted. If this endpoint doesn't require authentication
|
||||
# then it is acceptable to return None
|
||||
trusted_user = await self._check_trusted_connection(ip)
|
||||
if trusted_user is not None:
|
||||
return trusted_user
|
||||
if not auth_required:
|
||||
return None
|
||||
|
||||
raise HTTPError(401, "Unauthorized")
|
||||
|
||||
async def check_cors(self, origin: Optional[str]) -> 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}")
|
||||
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 await self._check_authorized_ip(ipaddr):
|
||||
logging.debug(f"Cors request matched trusted IP: {ip}")
|
||||
return True
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def cors_enabled(self) -> bool:
|
||||
return self.cors_domains is not None
|
||||
|
||||
def get_api_key(self) -> Optional[str]:
|
||||
if not self.enable_api_key:
|
||||
return None
|
||||
return self.api_key
|
||||
|
||||
def close(self) -> None:
|
||||
self.prune_timer.stop()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Authorization:
|
||||
return Authorization(config)
|
||||
@@ -0,0 +1,125 @@
|
||||
# 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 .application 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") # noqa: F841
|
||||
try:
|
||||
btn = GpioButton(cfg)
|
||||
except Exception as e:
|
||||
msg = f"Failed to load button [{cfg.get_name()}]\n{e}"
|
||||
self.server.add_warning(msg, exc_info=e)
|
||||
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()
|
||||
self.gpio_event = config.getgpioevent("pin", self._on_gpio_event)
|
||||
self.min_event_time = config.getfloat("minimum_event_time", 0, minval=0.0)
|
||||
debounce_period = config.getfloat("debounce_period", .05, minval=0.01)
|
||||
self.gpio_event.setup_debounce(debounce_period, 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:
|
||||
if elapsed_time < self.min_event_time:
|
||||
return
|
||||
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,174 @@
|
||||
# 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
|
||||
from ..common import RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .klippy_connection import KlippyConnection
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
GCQueue = Deque[Dict[str, Any]]
|
||||
TempStore = Dict[str, Dict[str, Deque[Optional[float]]]]
|
||||
|
||||
TEMP_UPDATE_TIME = 1.
|
||||
|
||||
def _round_null(val: Optional[float], ndigits: int) -> Optional[float]:
|
||||
if val is None:
|
||||
return val
|
||||
return round(val, ndigits)
|
||||
|
||||
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
|
||||
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
|
||||
self.subscription_cache = kconn.get_subscription_cache()
|
||||
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
|
||||
self.temperature_store: TempStore = {}
|
||||
self.temp_monitors: List[str] = []
|
||||
eventloop = self.server.get_event_loop()
|
||||
self.temp_update_timer = eventloop.register_timer(
|
||||
self._update_temperature_store)
|
||||
|
||||
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", RequestType.GET,
|
||||
self._handle_temp_store_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/gcode_store", RequestType.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
|
||||
heaters: Dict[str, List[str]] = result.get("heaters", {})
|
||||
sensors = heaters.get("available_sensors", [])
|
||||
self.temp_monitors = heaters.get("available_monitors", [])
|
||||
sensors.extend(self.temp_monitors)
|
||||
|
||||
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 = {}
|
||||
valid_fields = ("temperature", "target", "power", "speed")
|
||||
for sensor in sensors:
|
||||
reported_fields = [
|
||||
f for f in list(status.get(sensor, {}).keys()) if f in valid_fields
|
||||
]
|
||||
if not reported_fields:
|
||||
logging.info(f"No valid fields reported for sensor: {sensor}")
|
||||
self.temperature_store.pop(sensor, None)
|
||||
continue
|
||||
if sensor in self.temperature_store:
|
||||
new_store[sensor] = self.temperature_store[sensor]
|
||||
for field in list(new_store[sensor].keys()):
|
||||
if field not in reported_fields:
|
||||
new_store[sensor].pop(field, None)
|
||||
else:
|
||||
initial_val: Optional[float]
|
||||
initial_val = _round_null(status[sensor][field], 2)
|
||||
new_store[sensor][field].append(initial_val)
|
||||
else:
|
||||
new_store[sensor] = {}
|
||||
for field in reported_fields:
|
||||
if field not in new_store[sensor]:
|
||||
initial_val = _round_null(status[sensor][field], 2)
|
||||
new_store[sensor][field] = deque(
|
||||
[initial_val], maxlen=self.temp_store_size
|
||||
)
|
||||
self.temperature_store = new_store
|
||||
self.temp_update_timer.start(delay=1.)
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
self.temperature_store = {}
|
||||
self.temp_monitors = []
|
||||
self.temp_update_timer.stop()
|
||||
|
||||
def _update_temperature_store(self, eventtime: float) -> float:
|
||||
for sensor_name, sensor in self.temperature_store.items():
|
||||
sdata: Dict[str, Any] = self.subscription_cache.get(sensor_name, {})
|
||||
for field, store in sensor.items():
|
||||
store.append(_round_null(sdata.get(field, store[-1]), 2))
|
||||
return eventtime + TEMP_UPDATE_TIME
|
||||
|
||||
async def _handle_temp_store_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, List[Optional[float]]]]:
|
||||
include_monitors = web_request.get_boolean("include_monitors", False)
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
if not include_monitors and name in self.temp_monitors:
|
||||
continue
|
||||
store[name] = {f"{k}s": 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()
|
||||
if script.strip():
|
||||
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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,150 @@
|
||||
# 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 asyncio
|
||||
import pathlib
|
||||
import logging
|
||||
import dbus_fast
|
||||
from dbus_fast.aio import MessageBus, ProxyInterface
|
||||
from dbus_fast.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_fast.Variant
|
||||
DbusError = dbus_fast.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_fast.Variant("u", os.getpid()),
|
||||
"start-time": dbus_fast.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 asyncio.CancelledError:
|
||||
raise
|
||||
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 asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
if self.server.is_debug_enabled():
|
||||
logging.exception("Failed to get PolKit interface")
|
||||
else:
|
||||
logging.info(f"Failed to get PolKit interface: {e}")
|
||||
self.polkit = None
|
||||
|
||||
async def check_permission(self,
|
||||
action: str,
|
||||
err_msg: str = ""
|
||||
) -> bool:
|
||||
if self.polkit is None:
|
||||
self.server.add_warning(
|
||||
"Unable to find DBus PolKit Interface, this suggests PolKit "
|
||||
"is not installed on your OS.",
|
||||
"dbus_polkit"
|
||||
)
|
||||
return False
|
||||
try:
|
||||
ret = await self.polkit.call_check_authorization( # type: ignore
|
||||
self.polkit_subject, action, {}, 0, "")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
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 available")
|
||||
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,257 @@
|
||||
# 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
|
||||
from ..common import BaseRemoteConnection, RequestType, TransportType
|
||||
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 ..common 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, BaseRemoteConnection] = {}
|
||||
self.agent_methods: Dict[int, List[str]] = {}
|
||||
self.uds_server: Optional[asyncio.AbstractServer] = None
|
||||
self.server.register_endpoint(
|
||||
"/connection/register_remote_method", RequestType.POST,
|
||||
self._register_agent_method,
|
||||
transports=TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/connection/send_event", RequestType.POST, self._handle_agent_event,
|
||||
transports=TransportType.WEBSOCKET
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/extensions/list", RequestType.GET, self._handle_list_extensions
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/extensions/request", RequestType.POST, self._handle_call_agent
|
||||
)
|
||||
|
||||
def register_agent(self, connection: BaseRemoteConnection) -> 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: BaseRemoteConnection) -> None:
|
||||
name = connection.client_data["name"]
|
||||
if name in self.agents:
|
||||
klippy: Klippy = self.server.lookup_component("klippy_connection")
|
||||
registered_methods = self.agent_methods.pop(connection.uid, [])
|
||||
for method in registered_methods:
|
||||
klippy.unregister_method(method)
|
||||
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 _register_agent_method(self, web_request: WebRequest) -> str:
|
||||
conn = web_request.get_client_connection()
|
||||
if conn is None:
|
||||
raise self.server.error("No connection detected")
|
||||
method_name = web_request.get_str("method_name")
|
||||
klippy: Klippy = self.server.lookup_component("klippy_connection")
|
||||
klippy.register_method_from_agent(conn, method_name)
|
||||
self.agent_methods.setdefault(conn.uid, []).append(method_name)
|
||||
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_with_response(method, args)
|
||||
|
||||
async def start_unix_server(self) -> None:
|
||||
sockfile: str = self.server.get_app_args()["unix_socket_path"]
|
||||
sock_path = pathlib.Path(sockfile).expanduser().resolve()
|
||||
logging.info(f"Creating Unix Domain Socket at '{sock_path}'")
|
||||
try:
|
||||
self.uds_server = await asyncio.start_unix_server(
|
||||
self.on_unix_socket_connected, sock_path, limit=UNIX_BUFFER_LIMIT
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception(f"Failed to create Unix Domain Socket: {sock_path}")
|
||||
self.uds_server = None
|
||||
|
||||
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(BaseRemoteConnection):
|
||||
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[bytes, str]) -> None:
|
||||
if isinstance(message, str):
|
||||
data = message.encode() + b"\x03"
|
||||
else:
|
||||
data = message + 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,275 @@
|
||||
# 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 os
|
||||
import re
|
||||
import asyncio
|
||||
import pathlib
|
||||
import logging
|
||||
import periphery
|
||||
from ..utils import KERNEL_VERSION
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Dict,
|
||||
Optional
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..eventloop import EventLoop
|
||||
|
||||
GpioEventCallback = Callable[[float, float, int], Optional[Awaitable[None]]]
|
||||
|
||||
GPIO_PATTERN = r"""
|
||||
(?P<bias>[~^])?
|
||||
(?P<inverted>!)?
|
||||
(?:(?P<chip_id>gpiochip[0-9]+)/)?
|
||||
(?P<pin_name>gpio(?P<pin_id>[0-9]+))
|
||||
"""
|
||||
|
||||
BIAS_FLAG_TO_DESC: Dict[str, str] = {
|
||||
"^": "pull_up",
|
||||
"~": "pull_down",
|
||||
"*": "disable" if KERNEL_VERSION >= (5, 5) else "default"
|
||||
}
|
||||
|
||||
class GpioFactory:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.reserved_gpios: Dict[str, GpioBase] = {}
|
||||
|
||||
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, initial_value)
|
||||
gpio = self._request_gpio(pparams)
|
||||
try:
|
||||
gpio_out = GpioOutputPin(gpio, pparams)
|
||||
except Exception:
|
||||
logging.exception("Error Instantiating GpioOutputPin")
|
||||
gpio.close()
|
||||
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: GpioEventCallback
|
||||
) -> GpioEvent:
|
||||
pin_params = self._parse_pin(pin_name, req_type="event")
|
||||
gpio = self._request_gpio(pin_params)
|
||||
event_loop = self.server.get_event_loop()
|
||||
try:
|
||||
gpio_event = GpioEvent(event_loop, gpio, pin_params, callback)
|
||||
except Exception:
|
||||
logging.exception("Error Instantiating GpioEvent")
|
||||
gpio.close()
|
||||
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]) -> periphery.GPIO:
|
||||
full_name = pin_params["full_name"]
|
||||
if full_name in self.reserved_gpios:
|
||||
raise self.server.error(f"GPIO {full_name} already reserved")
|
||||
chip_path = pathlib.Path("/dev").joinpath(pin_params["chip_id"])
|
||||
if not chip_path.exists():
|
||||
raise self.server.error(f"Chip path {chip_path} does not exist")
|
||||
try:
|
||||
gpio = periphery.GPIO(
|
||||
str(chip_path),
|
||||
pin_params["pin_id"],
|
||||
pin_params["direction"],
|
||||
edge=pin_params.get("edge", "none"),
|
||||
bias=pin_params.get("bias", "default"),
|
||||
inverted=pin_params["inverted"],
|
||||
label="moonraker"
|
||||
)
|
||||
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 gpio
|
||||
|
||||
def _parse_pin(
|
||||
self, pin_desc: str, initial_value: int = 0, req_type: str = "out"
|
||||
) -> Dict[str, Any]:
|
||||
params: Dict[str, Any] = {
|
||||
"orig": pin_desc,
|
||||
"inverted": False,
|
||||
"request_type": req_type,
|
||||
"initial_value": initial_value
|
||||
}
|
||||
pin_match = re.match(GPIO_PATTERN, pin_desc, re.VERBOSE)
|
||||
if pin_match is None:
|
||||
raise self.server.error(
|
||||
f"Invalid pin format {pin_desc}. Refer to the configuration "
|
||||
"documentation for details on the pin format."
|
||||
)
|
||||
bias_flag: Optional[str] = pin_match.group("bias")
|
||||
params["inverted"] = pin_match.group("inverted") is not None
|
||||
if req_type == "event":
|
||||
params["direction"] = "in"
|
||||
params["edge"] = "both"
|
||||
params["bias"] = BIAS_FLAG_TO_DESC[bias_flag or "*"]
|
||||
elif req_type == "out":
|
||||
if bias_flag is not None:
|
||||
raise self.server.error(
|
||||
f"Invalid pin format {pin_desc}. Bias flag {bias_flag} "
|
||||
"not available for output pins."
|
||||
)
|
||||
initial_state = bool(initial_value) ^ params["inverted"]
|
||||
params["direction"] = "low" if not initial_state else "high"
|
||||
chip_id: str = pin_match.group("chip_id") or "gpiochip0"
|
||||
pin_name: str = pin_match.group("pin_name")
|
||||
params["pin_id"] = int(pin_match.group("pin_id"))
|
||||
params["chip_id"] = chip_id
|
||||
params["full_name"] = f"{chip_id}:{pin_name}"
|
||||
return params
|
||||
|
||||
def close(self) -> None:
|
||||
for gpio in self.reserved_gpios.values():
|
||||
gpio.close()
|
||||
|
||||
class GpioBase:
|
||||
def __init__(
|
||||
self, gpio: periphery.GPIO, pin_params: Dict[str, Any]
|
||||
) -> None:
|
||||
self.orig: str = pin_params["orig"]
|
||||
self.name: str = pin_params["full_name"]
|
||||
self.inverted: bool = pin_params["inverted"]
|
||||
self.gpio = gpio
|
||||
self.value: int = pin_params.get("initial_value", 0)
|
||||
|
||||
def close(self) -> None:
|
||||
self.gpio.close()
|
||||
|
||||
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.gpio.write(bool(self.value))
|
||||
|
||||
|
||||
MAX_ERRORS = 50
|
||||
ERROR_RESET_TIME = 5.
|
||||
|
||||
class GpioEvent(GpioBase):
|
||||
def __init__(
|
||||
self,
|
||||
event_loop: EventLoop,
|
||||
gpio: periphery.GPIO,
|
||||
pin_params: Dict[str, Any],
|
||||
callback: GpioEventCallback
|
||||
) -> None:
|
||||
super().__init__(gpio, pin_params)
|
||||
self.event_loop = event_loop
|
||||
self.callback = callback
|
||||
self.on_error: Optional[Callable[[str], None]] = None
|
||||
self.debounce_period: float = 0
|
||||
self.last_event_time: float = 0.
|
||||
self.error_count = 0
|
||||
self.last_error_reset = 0.
|
||||
self.started = False
|
||||
self.debounce_task: Optional[asyncio.Task] = None
|
||||
os.set_blocking(self.gpio.fd, False)
|
||||
|
||||
def fileno(self) -> int:
|
||||
return self.gpio.fd
|
||||
|
||||
def setup_debounce(
|
||||
self, debounce_period: float, err_callback: Optional[Callable[[str], None]]
|
||||
) -> None:
|
||||
self.debounce_period = max(debounce_period, 0)
|
||||
self.on_error = err_callback
|
||||
|
||||
def start(self) -> None:
|
||||
if not self.started:
|
||||
self.value = int(self.gpio.read())
|
||||
self.last_event_time = self.event_loop.get_loop_time()
|
||||
self.event_loop.add_reader(self.gpio.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.debounce_task is not None:
|
||||
self.debounce_task.cancel()
|
||||
self.debounce_task = None
|
||||
if self.started:
|
||||
self.event_loop.remove_reader(self.gpio.fd)
|
||||
self.started = False
|
||||
|
||||
def close(self) -> None:
|
||||
self.stop()
|
||||
self.gpio.close()
|
||||
|
||||
def _on_event_trigger(self) -> None:
|
||||
evt = self.gpio.read_event()
|
||||
last_value = self.value
|
||||
if evt.edge == "rising": # type: ignore
|
||||
self.value = 1
|
||||
elif evt.edge == "falling": # type: ignore
|
||||
self.value = 0
|
||||
else:
|
||||
return
|
||||
if self.debounce_period:
|
||||
if self.debounce_task is None:
|
||||
coro = self._debounce(last_value)
|
||||
self.debounce_task = self.event_loop.create_task(coro)
|
||||
else:
|
||||
self._increment_error()
|
||||
elif last_value != self.value:
|
||||
# No debounce period and change detected
|
||||
self._run_callback()
|
||||
|
||||
async def _debounce(self, last_value: int) -> None:
|
||||
await asyncio.sleep(self.debounce_period)
|
||||
self.debounce_task = None
|
||||
if last_value != self.value:
|
||||
self._run_callback()
|
||||
|
||||
def _run_callback(self) -> None:
|
||||
eventtime = self.event_loop.get_loop_time()
|
||||
evt_duration = eventtime - self.last_event_time
|
||||
self.last_event_time = eventtime
|
||||
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) -> None:
|
||||
eventtime = self.event_loop.get_loop_time()
|
||||
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(
|
||||
f"Too Many Consecutive Errors, GPIO Event Disabled on {self.name}"
|
||||
)
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> GpioFactory:
|
||||
return GpioFactory(config)
|
||||
@@ -0,0 +1,654 @@
|
||||
# History cache for printer jobs
|
||||
#
|
||||
# Copyright (C) 2024 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# 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
|
||||
from ..common import (
|
||||
JobEvent,
|
||||
RequestType,
|
||||
HistoryFieldData,
|
||||
FieldTracker,
|
||||
SqlTableDefinition
|
||||
)
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Tuple
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest, UserInfo
|
||||
from .database import MoonrakerDatabase as DBComp
|
||||
from .job_state import JobState
|
||||
from .file_manager.file_manager import FileManager
|
||||
from .database import DBProviderWrapper
|
||||
Totals = Dict[str, Union[float, int]]
|
||||
AuxTotals = List[Dict[str, Any]]
|
||||
|
||||
BASE_TOTALS = {
|
||||
"total_jobs": 0,
|
||||
"total_time": 0.,
|
||||
"total_print_time": 0.,
|
||||
"total_filament_used": 0.,
|
||||
"longest_job": 0.,
|
||||
"longest_print": 0.
|
||||
}
|
||||
HIST_TABLE = "job_history"
|
||||
TOTALS_TABLE = "job_totals"
|
||||
|
||||
def _create_totals_list(
|
||||
job_totals: Dict[str, Any],
|
||||
aux_totals: List[Dict[str, Any]],
|
||||
instance: str = "default"
|
||||
) -> List[Tuple[str, str, Any, Any, str]]:
|
||||
"""
|
||||
Returns a list of Tuples formatted for SQL Database insertion.
|
||||
|
||||
Fields of each tuple are in the following order:
|
||||
provider, field, maximum, total, instance_id
|
||||
"""
|
||||
totals_list: List[Tuple[str, str, Any, Any, str]] = []
|
||||
for key, value in job_totals.items():
|
||||
total = value if key.startswith("total_") else None
|
||||
maximum = value if total is None else None
|
||||
totals_list.append(("history", key, maximum, total, instance))
|
||||
for item in aux_totals:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
totals_list.append(
|
||||
(
|
||||
item["provider"],
|
||||
item["field"],
|
||||
item["maximum"],
|
||||
item["total"],
|
||||
instance
|
||||
)
|
||||
)
|
||||
return totals_list
|
||||
|
||||
class TotalsSqlDefinition(SqlTableDefinition):
|
||||
name = TOTALS_TABLE
|
||||
prototype = (
|
||||
f"""
|
||||
{TOTALS_TABLE} (
|
||||
provider TEXT NOT NULL,
|
||||
field TEXT NOT NULL,
|
||||
maximum REAL,
|
||||
total REAL,
|
||||
instance_id TEXT NOT NULL,
|
||||
PRIMARY KEY (provider, field, instance_id)
|
||||
)
|
||||
"""
|
||||
)
|
||||
version = 1
|
||||
|
||||
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
|
||||
if last_version == 0:
|
||||
# Migrate from "moonraker" namespace to a table
|
||||
logging.info("Migrating history totals from moonraker namespace...")
|
||||
hist_ns: Dict[str, Any] = db_provider.get_item("moonraker", "history", {})
|
||||
job_totals: Dict[str, Any] = hist_ns.get("job_totals", BASE_TOTALS)
|
||||
aux_totals: List[Dict[str, Any]] = hist_ns.get("aux_totals", [])
|
||||
if not isinstance(job_totals, dict):
|
||||
job_totals = dict(BASE_TOTALS)
|
||||
if not isinstance(aux_totals, list):
|
||||
aux_totals = []
|
||||
totals_list = _create_totals_list(job_totals, aux_totals)
|
||||
sql_conn = db_provider.connection
|
||||
with sql_conn:
|
||||
sql_conn.executemany(
|
||||
f"INSERT OR IGNORE INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)",
|
||||
totals_list
|
||||
)
|
||||
try:
|
||||
db_provider.delete_item("moonraker", "history")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
class HistorySqlDefinition(SqlTableDefinition):
|
||||
name = HIST_TABLE
|
||||
prototype = (
|
||||
f"""
|
||||
{HIST_TABLE} (
|
||||
job_id INTEGER PRIMARY KEY ASC,
|
||||
user TEXT NOT NULL,
|
||||
filename TEXT,
|
||||
status TEXT NOT NULL,
|
||||
start_time REAL NOT NULL,
|
||||
end_time REAL,
|
||||
print_duration REAL NOT NULL,
|
||||
total_duration REAL NOT NULL,
|
||||
filament_used REAL NOT NULL,
|
||||
metadata pyjson,
|
||||
auxiliary_data pyjson NOT NULL,
|
||||
instance_id TEXT NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
version = 1
|
||||
|
||||
def _get_entry_item(
|
||||
self, entry: Dict[str, Any], name: str, default: Any = 0.
|
||||
) -> Any:
|
||||
val = entry.get(name)
|
||||
if val is None:
|
||||
return default
|
||||
return val
|
||||
|
||||
def migrate(self, last_version: int, db_provider: DBProviderWrapper) -> None:
|
||||
if last_version == 0:
|
||||
conn = db_provider.connection
|
||||
for batch in db_provider.iter_namespace("history", 1000):
|
||||
conv_vals: List[Tuple[Any, ...]] = []
|
||||
entry: Dict[str, Any]
|
||||
for key, entry in batch.items():
|
||||
if not isinstance(entry, dict):
|
||||
logging.info(
|
||||
f"History migration, skipping invalid value: {key} {entry}"
|
||||
)
|
||||
continue
|
||||
try:
|
||||
conv_vals.append(
|
||||
(
|
||||
None,
|
||||
self._get_entry_item(entry, "user", "No User"),
|
||||
self._get_entry_item(entry, "filename", "unknown"),
|
||||
self._get_entry_item(entry, "status", "error"),
|
||||
self._get_entry_item(entry, "start_time"),
|
||||
self._get_entry_item(entry, "end_time"),
|
||||
self._get_entry_item(entry, "print_duration"),
|
||||
self._get_entry_item(entry, "total_duration"),
|
||||
self._get_entry_item(entry, "filament_used"),
|
||||
self._get_entry_item(entry, "metadata", {}),
|
||||
self._get_entry_item(entry, "auxiliary_data", []),
|
||||
"default"
|
||||
)
|
||||
)
|
||||
except KeyError:
|
||||
continue
|
||||
if not conv_vals:
|
||||
continue
|
||||
placeholders = ",".join("?" * len(conv_vals[0]))
|
||||
with conn:
|
||||
conn.executemany(
|
||||
f"INSERT INTO {HIST_TABLE} VALUES({placeholders})",
|
||||
conv_vals
|
||||
)
|
||||
db_provider.wipe_local_namespace("history")
|
||||
|
||||
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()
|
||||
FieldTracker.class_init(self)
|
||||
self.auxiliary_fields: List[HistoryFieldData] = []
|
||||
database: DBComp = self.server.lookup_component("database")
|
||||
self.history_table = database.register_table(HistorySqlDefinition())
|
||||
self.totals_table = database.register_table(TotalsSqlDefinition())
|
||||
self.job_totals: Totals = dict(BASE_TOTALS)
|
||||
self.aux_totals: AuxTotals = []
|
||||
|
||||
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:state_changed", self._on_job_state_changed)
|
||||
self.server.register_event_handler(
|
||||
"klippy_apis:job_start_complete", self._on_job_requested)
|
||||
self.server.register_notification("history:history_changed")
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/history/job", RequestType.GET | RequestType.DELETE,
|
||||
self._handle_job_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/list", RequestType.GET, self._handle_jobs_list
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/totals", RequestType.GET, self._handle_job_totals
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/reset_totals", RequestType.POST,
|
||||
self._handle_job_total_reset
|
||||
)
|
||||
|
||||
self.current_job: Optional[PrinterJob] = None
|
||||
self.current_job_id: Optional[int] = None
|
||||
self.job_user: str = "No User"
|
||||
self.job_paused: bool = False
|
||||
|
||||
async def component_init(self) -> None:
|
||||
# Popluate totals
|
||||
valid_aux_totals = [
|
||||
(item.provider, item.name) for item in self.auxiliary_fields
|
||||
if item.has_totals()
|
||||
]
|
||||
cursor = await self.totals_table.execute(f"SELECT * from {TOTALS_TABLE}")
|
||||
await cursor.set_arraysize(200)
|
||||
for row in await cursor.fetchall():
|
||||
provider, field, maximum, total, _ = tuple(row)
|
||||
if provider == "history":
|
||||
self.job_totals[field] = total if maximum is None else maximum
|
||||
elif (provider, field) in valid_aux_totals:
|
||||
item = dict(row)
|
||||
item.pop("instance_id", None)
|
||||
self.aux_totals.append(item)
|
||||
# Check for interrupted jobs
|
||||
cursor = await self.history_table.execute(
|
||||
f"SELECT job_id FROM {HIST_TABLE} WHERE status = 'in_progress'"
|
||||
)
|
||||
interrupted_jobs: List[int] = [row[0] for row in await cursor.fetchall()]
|
||||
if interrupted_jobs:
|
||||
async with self.history_table as tx:
|
||||
await tx.execute(
|
||||
f"UPDATE {HIST_TABLE} SET status = 'interrupted' "
|
||||
"WHERE status = 'in_progress'"
|
||||
)
|
||||
self.server.add_log_rollover_item(
|
||||
"interrupted_history",
|
||||
"The following jobs were detected as interrupted: "
|
||||
f"{interrupted_jobs}"
|
||||
)
|
||||
|
||||
async def _handle_job_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
async with self.request_lock:
|
||||
req_type = web_request.get_request_type()
|
||||
if req_type == RequestType.GET:
|
||||
job_id = web_request.get_str("uid")
|
||||
cursor = await self.history_table.execute(
|
||||
f"SELECT * FROM {HIST_TABLE} WHERE job_id = ?", (int(job_id, 16),)
|
||||
)
|
||||
result = await cursor.fetchone()
|
||||
if result is None:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
job = dict(result)
|
||||
return {"job": self._prep_requested_job(job, job_id)}
|
||||
if req_type == RequestType.DELETE:
|
||||
all = web_request.get_boolean("all", False)
|
||||
if all:
|
||||
cursor = await self.history_table.execute(
|
||||
f"SELECT job_id FROM {HIST_TABLE} WHERE instance_id = ?",
|
||||
("default",)
|
||||
)
|
||||
await cursor.set_arraysize(1000)
|
||||
deljobs = [f"{row[0]:06X}" for row in await cursor.fetchall()]
|
||||
async with self.history_table as tx:
|
||||
await tx.execute(
|
||||
f"DELETE FROM {HIST_TABLE} WHERE instance_id = ?",
|
||||
("default",)
|
||||
)
|
||||
return {'deleted_jobs': deljobs}
|
||||
|
||||
job_id = web_request.get_str("uid")
|
||||
async with self.history_table as tx:
|
||||
cursor = await tx.execute(
|
||||
f"DELETE FROM {HIST_TABLE} WHERE job_id = ?", (int(job_id, 16),)
|
||||
)
|
||||
if cursor.rowcount < 1:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
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:
|
||||
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").upper()
|
||||
|
||||
if order not in ["ASC", "DESC"]:
|
||||
raise self.server.error(f"Invalid `order` value: {order}", 400)
|
||||
# Build SQL Select Statement
|
||||
values: List[Any] = ["default"]
|
||||
sql_statement = f"SELECT * FROM {HIST_TABLE} WHERE instance_id = ?"
|
||||
if before != -1:
|
||||
sql_statement += " and end_time < ?"
|
||||
values.append(before)
|
||||
if since != -1:
|
||||
sql_statement += " and start_time > ?"
|
||||
values.append(since)
|
||||
sql_statement += f" ORDER BY job_id {order}"
|
||||
if limit > 0:
|
||||
sql_statement += " LIMIT ? OFFSET ?"
|
||||
values.append(limit)
|
||||
values.append(start)
|
||||
cursor = await self.history_table.execute(sql_statement, values)
|
||||
await cursor.set_arraysize(1000)
|
||||
jobs: List[Dict[str, Any]] = []
|
||||
for row in await cursor.fetchall():
|
||||
job = dict(row)
|
||||
job_id = f"{row['job_id']:06X}"
|
||||
jobs.append(self._prep_requested_job(job, job_id))
|
||||
return {"count": len(jobs), "jobs": jobs}
|
||||
|
||||
async def _handle_job_totals(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Union[Totals, AuxTotals]]:
|
||||
return {
|
||||
"job_totals": self.job_totals,
|
||||
"auxiliary_totals": self.aux_totals
|
||||
}
|
||||
|
||||
async def _handle_job_total_reset(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Union[Totals, AuxTotals]]:
|
||||
if self.current_job is not None:
|
||||
raise self.server.error("Job in progress, cannot reset totals")
|
||||
last_totals = self.job_totals
|
||||
self.job_totals = dict(BASE_TOTALS)
|
||||
last_aux_totals = self.aux_totals
|
||||
self._update_aux_totals(reset=True)
|
||||
totals_list = _create_totals_list(self.job_totals, self.aux_totals)
|
||||
async with self.totals_table as tx:
|
||||
await tx.execute(
|
||||
f"DELETE FROM {TOTALS_TABLE} WHERE instance_id = ?", ("default",)
|
||||
)
|
||||
await tx.executemany(
|
||||
f"INSERT INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)", totals_list
|
||||
)
|
||||
return {
|
||||
"last_totals": last_totals,
|
||||
"last_auxiliary_totals": last_aux_totals
|
||||
}
|
||||
|
||||
async def _on_job_state_changed(
|
||||
self,
|
||||
job_event: JobEvent,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
self.job_paused = job_event == JobEvent.PAUSED
|
||||
if job_event == JobEvent.STARTED:
|
||||
if self.current_job is not None:
|
||||
# Finish with the previous state
|
||||
await self.finish_job("cancelled", prev_stats)
|
||||
await self.add_job(PrinterJob(new_stats))
|
||||
elif job_event == JobEvent.COMPLETE:
|
||||
await self.finish_job("completed", new_stats)
|
||||
elif job_event == JobEvent.ERROR:
|
||||
await self.finish_job("error", new_stats)
|
||||
elif job_event in (JobEvent.CANCELLED, JobEvent.STANDBY):
|
||||
# Cancel on "standby" for backward compatibility with
|
||||
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
|
||||
await self.finish_job("cancelled", prev_stats)
|
||||
|
||||
def _on_job_requested(self, user: Optional[UserInfo]) -> None:
|
||||
username = user.username if user is not None else "No User"
|
||||
self.job_user = username
|
||||
if self.current_job is not None:
|
||||
self.current_job.user = username
|
||||
|
||||
async def _handle_shutdown(self) -> None:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
await self.finish_job("klippy_shutdown", last_ps)
|
||||
|
||||
async def _handle_disconnect(self) -> None:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
await self.finish_job("klippy_disconnect", last_ps)
|
||||
|
||||
async def add_job(self, job: PrinterJob) -> None:
|
||||
async with self.request_lock:
|
||||
self.current_job = job
|
||||
self.current_job_id = None
|
||||
self.current_job.user = self.job_user
|
||||
self.grab_job_metadata()
|
||||
for field in self.auxiliary_fields:
|
||||
field.tracker.reset()
|
||||
self.current_job.set_aux_data(self.auxiliary_fields)
|
||||
new_id = await self.save_job(job, None)
|
||||
if new_id is None:
|
||||
logging.info(f"Error saving job, filename '{job.filename}'")
|
||||
return
|
||||
self.current_job_id = new_id
|
||||
job_id = f"{new_id:06X}"
|
||||
self.update_metadata(job_id)
|
||||
logging.debug(
|
||||
f"History Job Added - Id: {job_id}, File: {job.filename}"
|
||||
)
|
||||
self.send_history_event("added")
|
||||
|
||||
async def save_job(self, job: PrinterJob, job_id: Optional[int]) -> Optional[int]:
|
||||
values: List[Any] = [
|
||||
job_id,
|
||||
job.user,
|
||||
job.filename,
|
||||
job.status,
|
||||
job.start_time,
|
||||
job.end_time,
|
||||
job.print_duration,
|
||||
job.total_duration,
|
||||
job.filament_used,
|
||||
job.metadata,
|
||||
job.auxiliary_data,
|
||||
"default"
|
||||
]
|
||||
placeholders = ",".join("?" * len(values))
|
||||
async with self.history_table as tx:
|
||||
cursor = await tx.execute(
|
||||
f"REPLACE INTO {HIST_TABLE} VALUES({placeholders})", values
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
async def delete_job(self, job_id: Union[int, str]) -> None:
|
||||
if isinstance(job_id, str):
|
||||
job_id = int(job_id, 16)
|
||||
async with self.history_table as tx:
|
||||
tx.execute(
|
||||
f"DELETE FROM {HIST_TABLE} WHERE job_id = ?", (job_id,)
|
||||
)
|
||||
|
||||
async def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
|
||||
async with self.request_lock:
|
||||
if self.current_job is None or self.current_job_id is None:
|
||||
self._reset_current_job()
|
||||
return
|
||||
if (
|
||||
pstats.get('filename') != self.current_job.filename or
|
||||
pstats.get('total_duration', 0.) < self.current_job.total_duration
|
||||
):
|
||||
# Print stats have been reset, do not update this job with them
|
||||
pstats = {}
|
||||
self.current_job.user = self.job_user
|
||||
self.current_job.finish(status, pstats)
|
||||
# Regrab metadata incase metadata wasn't parsed yet due to file upload
|
||||
self.grab_job_metadata()
|
||||
self.current_job.set_aux_data(self.auxiliary_fields)
|
||||
job_id = f"{self.current_job_id:06X}"
|
||||
await self.save_job(self.current_job, self.current_job_id)
|
||||
self.update_metadata(job_id)
|
||||
await self._update_job_totals()
|
||||
logging.debug(
|
||||
f"History Job Finished - Id: {job_id}, "
|
||||
f"File: {self.current_job.filename}, "
|
||||
f"Status: {status}"
|
||||
)
|
||||
self.send_history_event("finished")
|
||||
self._reset_current_job()
|
||||
|
||||
def _reset_current_job(self) -> None:
|
||||
self.current_job = None
|
||||
self.current_job_id = None
|
||||
self.job_user = "No User"
|
||||
|
||||
async def get_job(
|
||||
self, job_id: Union[int, str]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if isinstance(job_id, str):
|
||||
job_id = int(job_id, 16)
|
||||
cursor = await self.history_table.execute(
|
||||
f"SELECT * FROM {HIST_TABLE} WHERE job_id = ?", (job_id,)
|
||||
)
|
||||
result = await cursor.fetchone()
|
||||
return dict(result) if result is not None else result
|
||||
|
||||
def grab_job_metadata(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
filename: str = self.current_job.filename
|
||||
mdst = self.file_manager.get_metadata_storage()
|
||||
metadata: Dict[str, Any] = mdst.get(filename, {})
|
||||
# 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.metadata = metadata
|
||||
|
||||
def update_metadata(self, job_id: str) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
mdst = self.file_manager.get_metadata_storage()
|
||||
filename: str = self.current_job.filename
|
||||
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': job_id
|
||||
})
|
||||
mdst.insert(filename, metadata)
|
||||
|
||||
async def _update_job_totals(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
job = self.current_job
|
||||
self._accumulate_total("total_jobs", 1)
|
||||
self._accumulate_total("total_time", job.total_duration)
|
||||
self._accumulate_total("total_print_time", job.print_duration)
|
||||
self._accumulate_total("total_filament_used", job.filament_used)
|
||||
self._maximize_total("longest_job", job.total_duration)
|
||||
self._maximize_total("longest_print", job.print_duration)
|
||||
self._update_aux_totals()
|
||||
totals_list = _create_totals_list(self.job_totals, self.aux_totals)
|
||||
async with self.totals_table as tx:
|
||||
await tx.executemany(
|
||||
f"REPLACE INTO {TOTALS_TABLE} VALUES(?, ?, ?, ?, ?)", totals_list
|
||||
)
|
||||
|
||||
def _accumulate_total(self, field: str, val: Union[int, float]) -> None:
|
||||
self.job_totals[field] += val
|
||||
|
||||
def _maximize_total(self, field: str, val: Union[int, float]) -> None:
|
||||
self.job_totals[field] = max(self.job_totals[field], val)
|
||||
|
||||
def _update_aux_totals(self, reset: bool = False) -> None:
|
||||
last_totals = self.aux_totals
|
||||
self.aux_totals = [
|
||||
field.get_totals(last_totals, reset)
|
||||
for field in self.auxiliary_fields
|
||||
if field.has_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_id = f"{self.current_job_id:06X}"
|
||||
job = self._prep_requested_job(self.current_job.get_stats(), 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]:
|
||||
fm = self.file_manager
|
||||
mtime = job.get("metadata", {}).get("modified", None)
|
||||
job["exists"] = fm.check_file_exists("gcodes", job['filename'], mtime)
|
||||
job["job_id"] = job_id
|
||||
job.pop("instance_id", None)
|
||||
return job
|
||||
|
||||
def register_auxiliary_field(self, new_field: HistoryFieldData) -> None:
|
||||
if new_field.provider == "history":
|
||||
raise self.server.error("Provider name 'history' is reserved")
|
||||
for field in self.auxiliary_fields:
|
||||
if field == new_field:
|
||||
raise self.server.error(
|
||||
f"Field {field.name} already registered by "
|
||||
f"provider {field.provider}."
|
||||
)
|
||||
self.auxiliary_fields.append(new_field)
|
||||
|
||||
def tracking_enabled(self, check_paused: bool) -> bool:
|
||||
if self.current_job is None:
|
||||
return False
|
||||
return not self.job_paused if check_paused else True
|
||||
|
||||
async def on_exit(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_ps = jstate.get_last_stats()
|
||||
await 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: str = ""
|
||||
self.metadata: Dict[str, Any] = {}
|
||||
self.print_duration: float = 0.
|
||||
self.status: str = "in_progress"
|
||||
self.start_time = time.time()
|
||||
self.total_duration: float = 0.
|
||||
self.auxiliary_data: List[Dict[str, Any]] = []
|
||||
self.user: str = "No User"
|
||||
self.update_from_ps(data)
|
||||
|
||||
def finish(self,
|
||||
status: str,
|
||||
print_stats: Dict[str, Any] = {}
|
||||
) -> None:
|
||||
self.end_time = time.time()
|
||||
self.status = status if status is not None else "error"
|
||||
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 set_aux_data(self, fields: List[HistoryFieldData]) -> None:
|
||||
self.auxiliary_data = [field.as_dict() for field in fields]
|
||||
|
||||
def update_from_ps(self, data: Dict[str, Any]) -> None:
|
||||
for i in data:
|
||||
if hasattr(self, i) and data[i] is not None:
|
||||
setattr(self, i, data[i])
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> History:
|
||||
return History(config)
|
||||
@@ -0,0 +1,531 @@
|
||||
# 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 time
|
||||
import asyncio
|
||||
import pathlib
|
||||
import tempfile
|
||||
import logging
|
||||
import copy
|
||||
from ..utils import ServerError
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from tornado.escape import 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[bytes, 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,
|
||||
basic_auth_user: Optional[str] = None,
|
||||
basic_auth_pass: Optional[str] = None
|
||||
) -> 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 = jsonw.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
|
||||
req_args: Dict[str, Any] = dict(
|
||||
body=body,
|
||||
request_timeout=request_timeout,
|
||||
connect_timeout=connect_timeout
|
||||
)
|
||||
if basic_auth_user is not None:
|
||||
assert basic_auth_pass is not None
|
||||
req_args["auth_username"] = basic_auth_user
|
||||
req_args["auth_password"] = basic_auth_pass
|
||||
req_args["auth_mode"] = "basic"
|
||||
request = HTTPRequest(url, method, headers, **req_args)
|
||||
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 wrap_request(self, default_url: str, **kwargs) -> HttpRequestWrapper:
|
||||
return HttpRequestWrapper(self, default_url, **kwargs)
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
class HttpRequestWrapper:
|
||||
def __init__(
|
||||
self, client: HttpClient, default_url: str, **kwargs
|
||||
) -> None:
|
||||
self._do_request = client.request
|
||||
self._last_response: Optional[HttpResponse] = None
|
||||
self.default_request_args: Dict[str, Any] = {
|
||||
"method": "GET",
|
||||
"url": default_url,
|
||||
}
|
||||
self.default_request_args.update(kwargs)
|
||||
self.request_args = copy.deepcopy(self.default_request_args)
|
||||
self.reset()
|
||||
|
||||
async def send(self, **kwargs) -> HttpResponse:
|
||||
req_args = copy.deepcopy(self.request_args)
|
||||
req_args.update(kwargs)
|
||||
method = req_args.pop("method", self.default_request_args["method"])
|
||||
url = req_args.pop("url", self.default_request_args["url"])
|
||||
self._last_response = await self._do_request(method, url, **req_args)
|
||||
return self._last_response
|
||||
|
||||
def set_method(self, method: str) -> None:
|
||||
self.request_args["method"] = method
|
||||
|
||||
def set_url(self, url: str) -> None:
|
||||
self.request_args["url"] = url
|
||||
|
||||
def set_body(
|
||||
self, body: Optional[Union[str, List[Any], Dict[str, Any]]]
|
||||
) -> None:
|
||||
self.request_args["body"] = body
|
||||
|
||||
def add_header(self, name: str, value: str) -> None:
|
||||
headers = self.request_args.get("headers", {})
|
||||
headers[name] = value
|
||||
self.request_args["headers"] = headers
|
||||
|
||||
def set_headers(self, headers: Dict[str, str]) -> None:
|
||||
self.request_args["headers"] = headers
|
||||
|
||||
def reset(self) -> None:
|
||||
self.request_args = copy.deepcopy(self.default_request_args)
|
||||
|
||||
def last_response(self) -> Optional[HttpResponse]:
|
||||
return self._last_response
|
||||
|
||||
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) -> Union[List[Any], Dict[str, Any]]:
|
||||
return jsonw.loads(self._result)
|
||||
|
||||
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,357 @@
|
||||
# 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
|
||||
from ..common import JobEvent, RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Union,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest, UserInfo
|
||||
from .klippy_apis import KlippyAPI
|
||||
from .file_manager.file_manager import FileManager
|
||||
from .job_state import JobState
|
||||
|
||||
class JobQueue:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.queued_jobs: Dict[str, QueuedJob] = {}
|
||||
self.lock = asyncio.Lock()
|
||||
self.pause_requested: bool = False
|
||||
self.load_on_start = config.getboolean("load_on_startup", False)
|
||||
self.automatic = config.getboolean("automatic_transition", False)
|
||||
self.queue_state: str = "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:state_changed", self._on_job_state_changed
|
||||
)
|
||||
|
||||
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", RequestType.POST | RequestType.DELETE,
|
||||
self._handle_job_request
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/pause", RequestType.POST, self._handle_pause_queue
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/start", RequestType.POST, self._handle_start_queue
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/status", RequestType.GET, self._handle_queue_status
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/job_queue/jump", RequestType.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:
|
||||
has_requested_pause = self.pause_requested
|
||||
await self.pause_queue()
|
||||
self.pause_requested = has_requested_pause
|
||||
|
||||
async def _on_job_state_changed(self, job_event: JobEvent, *args) -> None:
|
||||
if job_event == JobEvent.COMPLETE:
|
||||
await self._on_job_complete()
|
||||
elif job_event.aborted:
|
||||
await self._on_job_abort()
|
||||
|
||||
async def _on_job_complete(self) -> None:
|
||||
if not self.automatic:
|
||||
return
|
||||
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) -> 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:
|
||||
self._set_queue_state("paused")
|
||||
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":
|
||||
self._set_queue_state("paused")
|
||||
raise self.server.error(
|
||||
"Queue State Changed during Transition Gcode")
|
||||
self._set_queue_state("starting")
|
||||
await kapis.start_print(
|
||||
filename, wait_klippy_started=True, user=job.user
|
||||
)
|
||||
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":
|
||||
# Set the queue to ready if items are in the queue
|
||||
# and auto transition is enabled
|
||||
set_ready = len(self.queued_jobs) > 0 and 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,
|
||||
user: Optional[UserInfo] = None
|
||||
) -> 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, user)
|
||||
self.queued_jobs[queued_job.job_id] = queued_job
|
||||
self._send_queue_event(action="jobs_added")
|
||||
if self.automatic and not self.pause_requested:
|
||||
jstate: JobState = self.server.lookup_component("job_state")
|
||||
last_evt = jstate.get_last_job_event()
|
||||
if last_evt.is_printing or last_evt == JobEvent.PAUSED:
|
||||
self._set_queue_state("ready")
|
||||
|
||||
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
|
||||
async with self.lock:
|
||||
self.pause_requested = True
|
||||
|
||||
async def start_queue(self) -> None:
|
||||
async with self.lock:
|
||||
self.pause_requested = False
|
||||
if self.queue_state in ("ready", "paused"):
|
||||
if not self.queued_jobs:
|
||||
self._set_queue_state("paused")
|
||||
elif 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, False
|
||||
)
|
||||
else:
|
||||
self._set_queue_state("ready" if self.automatic else "paused")
|
||||
|
||||
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]:
|
||||
req_type = web_request.get_request_type()
|
||||
if req_type == RequestType.POST:
|
||||
files = web_request.get_list('filenames')
|
||||
reset = web_request.get_boolean("reset", False)
|
||||
# Validate that all files exist before queueing
|
||||
user = web_request.get_current_user()
|
||||
await self.queue_job(files, reset=reset, user=user)
|
||||
elif req_type == RequestType.DELETE:
|
||||
if web_request.get_boolean("all", False):
|
||||
await self.delete_job([], all=True)
|
||||
else:
|
||||
job_ids = web_request.get_list('job_ids')
|
||||
await self.delete_job(job_ids)
|
||||
else:
|
||||
raise self.server.error(f"Invalid request type: {req_type}")
|
||||
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, user: Optional[UserInfo] = None) -> None:
|
||||
self.filename = filename
|
||||
self.job_id = f"{id(self):016X}"
|
||||
self.time_added = time.time()
|
||||
self._user = user
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.filename
|
||||
|
||||
@property
|
||||
def user(self) -> Optional[UserInfo]:
|
||||
return self._user
|
||||
|
||||
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,135 @@
|
||||
# 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,
|
||||
)
|
||||
from ..common import JobEvent, KlippyState
|
||||
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.last_event: JobEvent = JobEvent.STANDBY
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_started", self._handle_started
|
||||
)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._handle_disconnect
|
||||
)
|
||||
|
||||
def _handle_disconnect(self):
|
||||
state = self.last_print_stats.get("state", "")
|
||||
if state in ("printing", "paused"):
|
||||
# set error state
|
||||
self.last_print_stats["state"] = "error"
|
||||
self.last_event = JobEvent.ERROR
|
||||
|
||||
async def _handle_started(self, state: KlippyState) -> None:
|
||||
if state != KlippyState.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, self._status_update)
|
||||
except self.server.error:
|
||||
logging.info("Error subscribing to print_stats")
|
||||
return
|
||||
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], _: float) -> 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 != old_state:
|
||||
if self._check_idle(old_state):
|
||||
if new_state == "printing":
|
||||
new_state = "started"
|
||||
elif new_state != "standby":
|
||||
# send a started event prior to the detected event
|
||||
logging.info(
|
||||
f"Job started event inferred: transition from "
|
||||
f"{old_state} to {new_state} state"
|
||||
)
|
||||
self._send_job_event("started", prev_ps, new_ps)
|
||||
elif 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:
|
||||
new_state = "started"
|
||||
logging.debug(
|
||||
f"Job State Changed - Prev State: {old_state}, "
|
||||
f"New State: {new_state}"
|
||||
)
|
||||
self._send_job_event(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 _check_idle(self, state: str) -> bool:
|
||||
return state in ("standby", "complete", "cancelled", "error")
|
||||
|
||||
def _send_job_event(
|
||||
self, state: str, prev_ps: Dict[str, Any], new_ps: Dict[str, Any]
|
||||
) -> None:
|
||||
if state == "started":
|
||||
logging.info(f"Job Started: {new_ps['filename']}")
|
||||
# NOTE: Individual job_state events are DEPRECATED. New modules
|
||||
# should register handlers for "job_state: status_changed" and
|
||||
# match against the JobEvent object provided.
|
||||
self.server.send_event(f"job_state:{state}", prev_ps, new_ps)
|
||||
self.last_event = JobEvent.from_string(state)
|
||||
self.server.send_event(
|
||||
"job_state:state_changed",
|
||||
self.last_event,
|
||||
prev_ps,
|
||||
new_ps
|
||||
)
|
||||
|
||||
def get_last_stats(self) -> Dict[str, Any]:
|
||||
return dict(self.last_print_stats)
|
||||
|
||||
def get_last_job_event(self) -> JobEvent:
|
||||
return self.last_event
|
||||
|
||||
def load_component(config: ConfigHelper) -> JobState:
|
||||
return JobState(config)
|
||||
@@ -0,0 +1,302 @@
|
||||
# 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
|
||||
import logging
|
||||
from ..utils import Sentinel
|
||||
from ..common import WebRequest, APITransport, RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
TypeVar,
|
||||
Mapping,
|
||||
Callable,
|
||||
Coroutine
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import UserInfo
|
||||
from .klippy_connection import KlippyConnection as Klippy
|
||||
Subscription = Dict[str, Optional[List[Any]]]
|
||||
SubCallback = Callable[[Dict[str, Dict[str, Any]], float], Optional[Coroutine]]
|
||||
_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(APITransport):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
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 = {}
|
||||
self.subscription_callbacks: List[SubCallback] = []
|
||||
|
||||
# Register GCode Aliases
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/pause", RequestType.POST, self._gcode_pause
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/resume", RequestType.POST, self._gcode_resume
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/cancel", RequestType.POST, self._gcode_cancel
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/printer/print/start", RequestType.POST, self._gcode_start_print
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/printer/restart", RequestType.POST, self._gcode_restart
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", RequestType.POST, self._gcode_firmware_restart
|
||||
)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._on_klippy_disconnect
|
||||
)
|
||||
|
||||
def _on_klippy_disconnect(self) -> None:
|
||||
self.host_subscription.clear()
|
||||
self.subscription_callbacks.clear()
|
||||
|
||||
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')
|
||||
user = web_request.get_current_user()
|
||||
return await self.start_print(filename, user=user)
|
||||
|
||||
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,
|
||||
transport: Optional[APITransport] = None
|
||||
) -> Any:
|
||||
try:
|
||||
req = WebRequest(method, params, transport=transport or 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,
|
||||
user: Optional[UserInfo] = None
|
||||
) -> 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 specified
|
||||
# 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()
|
||||
logging.info(f"Requesting Job Start, filename = {filename}")
|
||||
ret = await self.run_gcode(script)
|
||||
self.server.send_event("klippy_apis:job_start_complete", user)
|
||||
return ret
|
||||
|
||||
async def pause_print(
|
||||
self, default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, str]:
|
||||
self.server.send_event("klippy_apis:pause_requested")
|
||||
logging.info("Requesting job pause...")
|
||||
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")
|
||||
logging.info("Requesting job resume...")
|
||||
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")
|
||||
logging.info("Requesting job cancel...")
|
||||
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 specified
|
||||
# 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']
|
||||
if default is not Sentinel.MISSING:
|
||||
return default
|
||||
raise self.server.error("Invalid response received from Klippy", 500)
|
||||
|
||||
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"]
|
||||
if default is not Sentinel.MISSING:
|
||||
return default
|
||||
raise self.server.error("Invalid response received from Klippy", 500)
|
||||
|
||||
async def subscribe_objects(
|
||||
self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
callback: Optional[SubCallback] = None,
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
# The host transport shares subscriptions amongst all components
|
||||
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": dict(self.host_subscription)}
|
||||
result = await self._send_klippy_request(SUBSCRIPTION_ENDPOINT, params, default)
|
||||
if isinstance(result, dict) and "status" in result:
|
||||
if callback is not None:
|
||||
self.subscription_callbacks.append(callback)
|
||||
return result["status"]
|
||||
if default is not Sentinel.MISSING:
|
||||
return default
|
||||
raise self.server.error("Invalid response received from Klippy", 500)
|
||||
|
||||
async def subscribe_from_transport(
|
||||
self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
transport: APITransport,
|
||||
default: Union[Sentinel, _T] = Sentinel.MISSING,
|
||||
full_response: bool = False
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
params = {"objects": dict(objects)}
|
||||
result = await self._send_klippy_request(
|
||||
SUBSCRIPTION_ENDPOINT, params, default, transport
|
||||
)
|
||||
if isinstance(result, dict) and "status" in result:
|
||||
if full_response:
|
||||
return result
|
||||
return result["status"]
|
||||
if default is not Sentinel.MISSING:
|
||||
return default
|
||||
raise self.server.error("Invalid response received from Klippy", 500)
|
||||
|
||||
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:
|
||||
for cb in self.subscription_callbacks:
|
||||
self.eventloop.register_callback(cb, status, eventtime)
|
||||
self.server.send_event("server:status_update", status)
|
||||
|
||||
def load_component(config: ConfigHelper) -> KlippyAPI:
|
||||
return KlippyAPI(config)
|
||||
@@ -0,0 +1,852 @@
|
||||
|
||||
# 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 getpass
|
||||
import asyncio
|
||||
import pathlib
|
||||
from ..utils import ServerError, get_unix_peer_credentials
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from ..common import KlippyState, RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Awaitable,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
List,
|
||||
Set,
|
||||
Tuple,
|
||||
Union
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..common import WebRequest, APITransport, BaseRemoteConnection
|
||||
from ..confighelper import ConfigHelper
|
||||
from .klippy_apis import KlippyAPI
|
||||
from .file_manager.file_manager import FileManager
|
||||
from .machine import Machine
|
||||
from .job_state import JobState
|
||||
from .database import MoonrakerDatabase as Database
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
Subscription = Dict[str, Optional[List[str]]]
|
||||
|
||||
# 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",
|
||||
]
|
||||
|
||||
# Items to exclude from the subscription cache. They never change and can be
|
||||
# quite large.
|
||||
CACHE_EXCLUSIONS = {
|
||||
"configfile": ["config", "settings"]
|
||||
}
|
||||
|
||||
INIT_TIME = .25
|
||||
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
|
||||
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
|
||||
SVC_INFO_KEY = "klippy_connection.service_info"
|
||||
SRC_PATH_KEY = "klippy_connection.path"
|
||||
PY_EXEC_KEY = "klippy_connection.executable"
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.uds_address = config.getpath(
|
||||
"klippy_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.subscription_lock = asyncio.Lock()
|
||||
self._klippy_info: Dict[str, Any] = {}
|
||||
self._klippy_identified: bool = False
|
||||
self._klippy_initializing: bool = False
|
||||
self._klippy_started: bool = False
|
||||
self._methods_registered: 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._path = pathlib.Path("~/klipper").expanduser()
|
||||
self._executable = pathlib.Path("~/klippy-env/bin/python").expanduser()
|
||||
self.init_attempts: int = 0
|
||||
self._state: KlippyState = KlippyState.DISCONNECTED
|
||||
self._state.set_message("Klippy Disconnected")
|
||||
self.subscriptions: Dict[APITransport, Subscription] = {}
|
||||
self.subscription_cache: Dict[str, Dict[str, Any]] = {}
|
||||
# Setup remote methods accessible 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)
|
||||
|
||||
@property
|
||||
def klippy_apis(self) -> KlippyAPI:
|
||||
return self.server.lookup_component("klippy_apis")
|
||||
|
||||
@property
|
||||
def state(self) -> KlippyState:
|
||||
if self.is_connected() and not self._klippy_started:
|
||||
return KlippyState.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]
|
||||
|
||||
@property
|
||||
def path(self) -> pathlib.Path:
|
||||
return self._path
|
||||
|
||||
@property
|
||||
def executable(self) -> pathlib.Path:
|
||||
return self._executable
|
||||
|
||||
def load_saved_state(self) -> None:
|
||||
db: Database = self.server.lookup_component("database")
|
||||
sync_provider = db.get_provider_wrapper()
|
||||
kc_info: Dict[str, Any]
|
||||
kc_info = sync_provider.get_item("moonraker", "klippy_connection", {})
|
||||
self._path = pathlib.Path(kc_info.get("path", str(self._path)))
|
||||
self._executable = pathlib.Path(kc_info.get("executable", str(self.executable)))
|
||||
self._service_info = kc_info.get("service_info", {})
|
||||
|
||||
async def component_init(self) -> None:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
if self._service_info:
|
||||
machine.log_service_info(self._service_info)
|
||||
|
||||
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 = jsonw.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:
|
||||
request.set_exception(ServerError("Klippy Host not connected", 503))
|
||||
return
|
||||
data = jsonw.dumps(request.to_dict()) + b"\x03"
|
||||
try:
|
||||
self.writer.write(data)
|
||||
await self.writer.drain()
|
||||
except asyncio.CancelledError:
|
||||
request.set_exception(ServerError("Klippy Write Request Cancelled", 503))
|
||||
raise
|
||||
except Exception:
|
||||
request.set_exception(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 register_method_from_agent(
|
||||
self, connection: BaseRemoteConnection, method_name: str
|
||||
) -> Optional[Awaitable]:
|
||||
if connection.client_data["type"] != "agent":
|
||||
raise self.server.error(
|
||||
"Only connections of the 'agent' type can register methods"
|
||||
)
|
||||
if method_name in self.remote_methods:
|
||||
raise self.server.error(
|
||||
f"Remote method ({method_name}) already registered"
|
||||
)
|
||||
|
||||
def _on_agent_method_received(**kwargs) -> None:
|
||||
connection.call_method(method_name, kwargs)
|
||||
self.remote_methods[method_name] = _on_agent_method_received
|
||||
self.klippy_reg_methods.append(method_name)
|
||||
if self._methods_registered and self._state != KlippyState.DISCONNECTED:
|
||||
coro = self.klippy_apis.register_method(method_name)
|
||||
return self.event_loop.create_task(coro)
|
||||
return None
|
||||
|
||||
def unregister_method(self, method_name: str):
|
||||
self.remote_methods.pop(method_name, None)
|
||||
try:
|
||||
self.klippy_reg_methods.remove(method_name)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
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 # type: ignore
|
||||
|
||||
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):
|
||||
await self._get_service_info(self._peer_cred["process_id"])
|
||||
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:
|
||||
peer_cred = get_unix_peer_credentials(writer, "Klippy")
|
||||
if not peer_cred:
|
||||
return False
|
||||
if peer_cred.get("process_id") == 1:
|
||||
logging.debug("Klipper Unix Socket created via Systemd Socket Activation")
|
||||
return False
|
||||
self._peer_cred = peer_cred
|
||||
logging.debug(
|
||||
f"Klippy Connection: Received Peer Credentials: {self._peer_cred}"
|
||||
)
|
||||
return True
|
||||
|
||||
async def _get_service_info(self, process_id: int) -> None:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
provider = machine.get_system_provider()
|
||||
svc_info = await provider.extract_service_info("klipper", process_id)
|
||||
if svc_info != self._service_info:
|
||||
db: Database = self.server.lookup_component('database')
|
||||
db.insert_item("moonraker", SVC_INFO_KEY, svc_info)
|
||||
self._service_info = svc_info
|
||||
machine.log_service_info(svc_info)
|
||||
|
||||
def _save_path_info(self) -> None:
|
||||
kpath = pathlib.Path(self._klippy_info["klipper_path"])
|
||||
kexec = pathlib.Path(self._klippy_info["python_path"])
|
||||
db: Database = self.server.lookup_component("database")
|
||||
if kpath != self.path:
|
||||
self._path = kpath
|
||||
db.insert_item("moonraker", SRC_PATH_KEY, str(kpath))
|
||||
logging.info(f"Updated Stored Klipper Source Path: {kpath}")
|
||||
if kexec != self.executable:
|
||||
self._executable = kexec
|
||||
db.insert_item("moonraker", PY_EXEC_KEY, str(kexec))
|
||||
logging.info(f"Updated Stored Klipper Python Path: {kexec}")
|
||||
|
||||
async def _init_klippy_connection(self) -> bool:
|
||||
self._klippy_identified = False
|
||||
self._klippy_started = False
|
||||
self._klippy_initializing = True
|
||||
self._methods_registered = False
|
||||
self._missing_reqs.clear()
|
||||
self.init_attempts = 0
|
||||
self._state = KlippyState.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', [])
|
||||
for ep in endpoints:
|
||||
if ep not in RESERVED_ENDPOINTS:
|
||||
self.server.register_endpoint(
|
||||
ep, RequestType.GET | RequestType.POST, self.request,
|
||||
is_remote=True
|
||||
)
|
||||
|
||||
async def _request_initial_subscriptions(self) -> None:
|
||||
try:
|
||||
await self.klippy_apis.subscribe_objects({'webhooks': None})
|
||||
except ServerError:
|
||||
logging.exception("Unable to subscribe to webhooks object")
|
||||
else:
|
||||
logging.info("Webhooks Subscribed")
|
||||
try:
|
||||
await self.klippy_apis.subscribe_gcode_output()
|
||||
except ServerError:
|
||||
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)
|
||||
klipper_pid: Optional[int] = result.get("process_id")
|
||||
if klipper_pid is not None:
|
||||
cur_pid: Optional[int] = self._peer_cred.get("process_id")
|
||||
if cur_pid is None or klipper_pid != cur_pid:
|
||||
self._peer_cred = dict(
|
||||
process_id=klipper_pid,
|
||||
group_id=result.get("group_id", -1),
|
||||
user_id=result.get("user_id", -1)
|
||||
)
|
||||
await self._get_service_info(klipper_pid)
|
||||
self._klippy_info = dict(result)
|
||||
state_message: str = self._state.message
|
||||
if "state_message" in self._klippy_info:
|
||||
state_message = self._klippy_info["state_message"]
|
||||
self._state.set_message(state_message)
|
||||
if "state" not in result:
|
||||
return
|
||||
if send_id:
|
||||
self._klippy_identified = True
|
||||
self._save_path_info()
|
||||
await self.server.send_event("server:klippy_identified")
|
||||
# Request initial endpoints to register info, emergency stop APIs
|
||||
await self._request_endpoints()
|
||||
self._state = KlippyState.from_string(result["state"], state_message)
|
||||
if self._state != KlippyState.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 != KlippyState.READY:
|
||||
logging.info("\n" + self._state.message)
|
||||
if (
|
||||
self._state == KlippyState.SHUTDOWN and
|
||||
startup_state != KlippyState.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}'")
|
||||
self._methods_registered = True
|
||||
if self._state == KlippyState.READY:
|
||||
logging.info("Klippy ready")
|
||||
await self.server.send_event("server:klippy_ready")
|
||||
if self._state == KlippyState.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("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("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"
|
||||
request.set_result(result)
|
||||
else:
|
||||
err: Union[str, Dict[str, str]]
|
||||
err = cmd.get('error', "Malformed Klippy Response")
|
||||
if isinstance(err, dict):
|
||||
err = err.get("message", "Malformed Klippy Response")
|
||||
request.set_exception(ServerError(err, 400))
|
||||
|
||||
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, Dict[str, Any]]
|
||||
) -> None:
|
||||
for field, item in status.items():
|
||||
self.subscription_cache.setdefault(field, {}).update(item)
|
||||
if 'webhooks' in status:
|
||||
wh: Dict[str, str] = status['webhooks']
|
||||
state_message: str = self._state.message
|
||||
if "state_message" in wh:
|
||||
state_message = wh["state_message"]
|
||||
self._state.set_message(state_message)
|
||||
# XXX - process other states (startup, ready, error, etc)?
|
||||
if "state" in wh:
|
||||
new_state = KlippyState.from_string(wh["state"], state_message)
|
||||
if (
|
||||
new_state == KlippyState.SHUTDOWN and
|
||||
not self._klippy_initializing and
|
||||
self._state != KlippyState.SHUTDOWN
|
||||
):
|
||||
# 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 = new_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]:
|
||||
async with self.subscription_lock:
|
||||
args = web_request.get_args()
|
||||
conn = web_request.get_subscribable()
|
||||
if conn is None:
|
||||
raise self.server.error(
|
||||
"No connection associated with subscription request"
|
||||
)
|
||||
# if the connection has an existing subscription pop it off
|
||||
self.subscriptions.pop(conn, None)
|
||||
requested_sub: Subscription = args.get('objects', {})
|
||||
all_subs: Subscription = dict(requested_sub)
|
||||
# Build the subscription request from a superset of all client subscriptions
|
||||
for sub in self.subscriptions.values():
|
||||
for obj, items in sub.items():
|
||||
if obj in all_subs:
|
||||
prev_items = all_subs[obj]
|
||||
if items is None or prev_items is None:
|
||||
all_subs[obj] = None
|
||||
else:
|
||||
uitems = list(set(prev_items) | 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, 20.0)
|
||||
|
||||
# prune the status response
|
||||
pruned_status: Dict[str, Dict[str, Any]] = {}
|
||||
status_diff: Dict[str, Dict[str, Any]] = {}
|
||||
all_status: Dict[str, Dict[str, Any]] = result['status']
|
||||
for obj, fields in all_status.items():
|
||||
# Diff the current cache, then update the cache
|
||||
if obj in self.subscription_cache:
|
||||
cached_status = self.subscription_cache[obj]
|
||||
for field_name, value in fields.items():
|
||||
if field_name not in cached_status:
|
||||
continue
|
||||
if value != cached_status[field_name]:
|
||||
status_diff.setdefault(obj, {})[field_name] = value
|
||||
if obj in CACHE_EXCLUSIONS:
|
||||
# Make a shallow copy so we can pop off fields we want to
|
||||
# exclude from the cache without modifying the return value
|
||||
fields_to_cache = dict(fields)
|
||||
removed: List[str] = []
|
||||
for excluded_field in CACHE_EXCLUSIONS[obj]:
|
||||
if excluded_field in fields_to_cache:
|
||||
removed.append(excluded_field)
|
||||
del fields_to_cache[excluded_field]
|
||||
if removed:
|
||||
logging.debug(
|
||||
"Removed excluded fields from subscription cache: "
|
||||
f"{obj}: {removed}"
|
||||
)
|
||||
self.subscription_cache[obj] = fields_to_cache
|
||||
else:
|
||||
self.subscription_cache[obj] = fields
|
||||
# Prune Response
|
||||
if obj in requested_sub:
|
||||
valid_fields = requested_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
|
||||
}
|
||||
if status_diff:
|
||||
# The response to the status request contains changed data, so it
|
||||
# is necessary to manually push the status update to existing
|
||||
# subscribers
|
||||
logging.debug(
|
||||
f"Detected status difference during subscription: {status_diff}"
|
||||
)
|
||||
self._process_status_update(result["eventtime"], status_diff)
|
||||
for obj_name in list(self.subscription_cache.keys()):
|
||||
# Prune the cache to match the current status response
|
||||
if obj_name not in all_status:
|
||||
del self.subscription_cache[obj_name]
|
||||
result['status'] = pruned_status
|
||||
if requested_sub:
|
||||
self.subscriptions[conn] = requested_sub
|
||||
return result
|
||||
|
||||
async def _request_standard(
|
||||
self, web_request: WebRequest, timeout: Optional[float] = None
|
||||
) -> 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)
|
||||
try:
|
||||
return await base_request.wait(timeout)
|
||||
finally:
|
||||
self.pending_requests.pop(base_request.id, None)
|
||||
|
||||
def remove_subscription(self, conn: APITransport) -> 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 == KlippyState.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"
|
||||
|
||||
def get_subscription_cache(self) -> Dict[str, Dict[str, Any]]:
|
||||
return self.subscription_cache
|
||||
|
||||
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._methods_registered = False
|
||||
self._state = KlippyState.DISCONNECTED
|
||||
self._state.set_message("Klippy Disconnected")
|
||||
for request in self.pending_requests.values():
|
||||
request.set_exception(ServerError("Klippy Disconnected", 503))
|
||||
self.pending_requests = {}
|
||||
self.subscriptions = {}
|
||||
self.subscription_cache.clear()
|
||||
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._fut = asyncio.get_running_loop().create_future()
|
||||
|
||||
async def wait(self, timeout: Optional[float] = None) -> Any:
|
||||
start_time = time.time()
|
||||
to = timeout or 60.
|
||||
while True:
|
||||
try:
|
||||
return await asyncio.wait_for(asyncio.shield(self._fut), to)
|
||||
except asyncio.TimeoutError:
|
||||
if timeout is not None:
|
||||
self._fut.cancel()
|
||||
raise ServerError("Klippy request timed out", 500) from None
|
||||
pending_time = time.time() - start_time
|
||||
logging.info(
|
||||
f"Request '{self.rpc_method}' pending: "
|
||||
f"{pending_time:.2f} seconds"
|
||||
)
|
||||
|
||||
def set_exception(self, exc: Exception) -> None:
|
||||
if not self._fut.done():
|
||||
self._fut.set_exception(exc)
|
||||
|
||||
def set_result(self, result: Any) -> None:
|
||||
if not self._fut.done():
|
||||
self._fut.set_result(result)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'id': self.id,
|
||||
'method': self.rpc_method,
|
||||
'params': self.params
|
||||
}
|
||||
|
||||
def load_component(config: ConfigHelper) -> KlippyConnection:
|
||||
return KlippyConnection(config)
|
||||
@@ -0,0 +1,147 @@
|
||||
# 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
|
||||
from ldap3.utils.conv import escape_filter_chars
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Optional
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ldap3.abstract.entry import Entry
|
||||
|
||||
VALID_MEMBERSHIP_ATTRS = ["memberOf", "isMemberOf"]
|
||||
|
||||
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)
|
||||
self.membership_attr = config.getchoice(
|
||||
"membership_attribute", VALID_MEMBERSHIP_ATTRS, "memberOf"
|
||||
)
|
||||
self.check_dn_case = config.getboolean("check_dn_case", True)
|
||||
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: str, password: str) -> 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: str, password: str) -> 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"
|
||||
escaped_user = escape_filter_chars(username)
|
||||
ldfilt = f"(&(objectClass=Person)({attr_name}={escaped_user}))"
|
||||
if self.user_filter:
|
||||
ldfilt = self.user_filter.replace("USERNAME", escaped_user)
|
||||
try:
|
||||
with ldap3.Connection(server, **conn_args) as conn:
|
||||
search_attrs = None if self.group_dn is None else [self.membership_attr]
|
||||
ret = conn.search(
|
||||
self.base_dn, ldfilt, attributes=search_attrs
|
||||
)
|
||||
if not ret:
|
||||
logging.info(f"LDAP User '{username}' Not Found")
|
||||
raise self.server.error("Unauthorized", 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:
|
||||
logging.exception("LDAP authentication failed")
|
||||
else:
|
||||
logging.info("Invalid LDAP Username or Password")
|
||||
raise self.server.error("Unauthorized", 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
|
||||
member_attr = getattr(user, self.membership_attr, None)
|
||||
if member_attr is None:
|
||||
logging.info(
|
||||
f"Membership attribute {self.membership_attr} not present "
|
||||
"in user entry"
|
||||
)
|
||||
return False
|
||||
groups: list[str] = getattr(member_attr, "values", [])
|
||||
req_dn = self.group_dn
|
||||
logging.debug(f"Required Group DN: {req_dn}, User Group DNs: {groups}")
|
||||
if not self.check_dn_case:
|
||||
groups = [grp.lower() for grp in groups]
|
||||
req_dn = req_dn.lower()
|
||||
if req_dn in groups:
|
||||
logging.debug(
|
||||
f"LDAP User {username} group match success, login successful"
|
||||
)
|
||||
return True
|
||||
logging.info(f"User '{username}' is not a member of configured group_dn.")
|
||||
return False
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> MoonrakerLDAP:
|
||||
return MoonrakerLDAP(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,883 @@
|
||||
# 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 pathlib
|
||||
import ssl
|
||||
from collections import deque
|
||||
import paho.mqtt.client as paho_mqtt
|
||||
import paho.mqtt
|
||||
from ..common import (
|
||||
TransportType,
|
||||
RequestType,
|
||||
WebRequest,
|
||||
APITransport,
|
||||
KlippyState
|
||||
)
|
||||
from ..utils import json_wrapper as jsonw
|
||||
try:
|
||||
from paho.mqtt.reasoncodes import ReasonCode
|
||||
except ImportError:
|
||||
from paho.mqtt.reasoncodes import ReasonCodes as ReasonCode
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
List,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Union,
|
||||
Tuple,
|
||||
Awaitable,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import JsonRPC, APIDefinition
|
||||
from ..eventloop import FlexTimer
|
||||
from .klippy_apis import KlippyAPI
|
||||
from paho.mqtt.properties import Properties
|
||||
FlexCallback = Callable[[bytes], Optional[Coroutine]]
|
||||
RPCCallback = Callable[..., Coroutine]
|
||||
|
||||
PAHO_MQTT_VERSION = tuple([int(p) for p in paho.mqtt.__version__.split(".")])
|
||||
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 PAHO_MQTT_VERSION >= (2, 0):
|
||||
return self._v2_reconnect(sock)
|
||||
if PAHO_MQTT_VERSION < (1, 6):
|
||||
# Paho Mqtt Version < 1.6.x
|
||||
self._in_packet = {
|
||||
"command": 0,
|
||||
"have_remaining": 0,
|
||||
"remaining_count": [],
|
||||
"remaining_mult": 1,
|
||||
"remaining_length": 0,
|
||||
"packet": b"", # type: ignore
|
||||
"to_process": 0,
|
||||
"pos": 0
|
||||
}
|
||||
with self._out_packet_mutex: # type: ignore
|
||||
self._out_packet = deque() # type: ignore
|
||||
|
||||
with self._current_out_packet_mutex: # type: ignore
|
||||
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 # type: ignore
|
||||
|
||||
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( # type: ignore
|
||||
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( # type: ignore
|
||||
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): # type: ignore
|
||||
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) # type: ignore
|
||||
|
||||
if self._transport == "websockets":
|
||||
sock.settimeout(self._keepalive)
|
||||
sock = paho_mqtt.WebsocketWrapper( # type: ignore
|
||||
sock, self._host, self._port, self._ssl,
|
||||
self._websocket_path, self._websocket_extra_headers
|
||||
) # type: ignore
|
||||
|
||||
self._sock = sock # type: ignore
|
||||
assert self._sock is not None
|
||||
self._sock.setblocking(False)
|
||||
self._registered_write = False
|
||||
self._call_socket_open() # type: ignore
|
||||
|
||||
return self._send_connect(self._keepalive)
|
||||
|
||||
def _v2_reconnect(self, sock: Optional[socket.socket] = None):
|
||||
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._ping_t = 0.0 # type: ignore
|
||||
self._state = paho_mqtt._ConnectionState.MQTT_CS_CONNECTING # type: ignore
|
||||
|
||||
self._sock_close()
|
||||
|
||||
# Mark all currently outgoing QoS = 0 packets as lost,
|
||||
# or `wait_for_publish()` could hang forever
|
||||
for pkt in self._out_packet:
|
||||
if (
|
||||
pkt["command"] & 0xF0 == paho_mqtt.PUBLISH and
|
||||
pkt["qos"] == 0 and pkt["info"] is not None
|
||||
):
|
||||
pkt["info"].rc = paho_mqtt.MQTT_ERR_CONN_LOST
|
||||
pkt["info"]._set_as_published()
|
||||
|
||||
self._out_packet.clear()
|
||||
|
||||
with self._msgtime_mutex:
|
||||
self._last_msg_in = paho_mqtt.time_func()
|
||||
self._last_msg_out = paho_mqtt.time_func()
|
||||
|
||||
# Put messages in progress in a valid state.
|
||||
self._messages_reconnect_reset()
|
||||
|
||||
with self._callback_mutex:
|
||||
on_pre_connect = self.on_pre_connect # type: ignore
|
||||
|
||||
if on_pre_connect:
|
||||
try:
|
||||
on_pre_connect(self, self._userdata)
|
||||
except Exception as err:
|
||||
self._easy_log(
|
||||
paho_mqtt.MQTT_LOG_ERR,
|
||||
'Caught exception in on_pre_connect: %s', err
|
||||
)
|
||||
if not self.suppress_exceptions:
|
||||
raise
|
||||
|
||||
if sock is None:
|
||||
self._sock = self._create_socket() # type: ignore
|
||||
elif self._ssl:
|
||||
self._sock = self._ssl_wrap_socket(sock)
|
||||
else:
|
||||
self._sock = sock # type: ignore
|
||||
|
||||
self._sock.setblocking(False) # type: ignore[attr-defined]
|
||||
self._registered_write = False
|
||||
self._call_socket_open(self._sock) # type: ignore
|
||||
|
||||
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[ReasonCode]]
|
||||
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, ReasonCode):
|
||||
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 | paho_mqtt.SocketLike
|
||||
) -> 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 | paho_mqtt.SocketLike
|
||||
) -> 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 | paho_mqtt.SocketLike
|
||||
) -> None:
|
||||
self.loop.add_writer(sock, client.loop_write)
|
||||
|
||||
def _on_socket_unregister_write(
|
||||
self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket | paho_mqtt.SocketLike
|
||||
) -> 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):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
self.address: str = config.get('address')
|
||||
self.port: int = config.getint('port', 1883)
|
||||
self.tls_enabled: bool = config.getboolean("enable_tls", False)
|
||||
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)
|
||||
client_id: str = config.get("client_id", "")
|
||||
if PAHO_MQTT_VERSION < (2, 0):
|
||||
self.client = ExtPahoClient(
|
||||
client_id, protocol=self.protocol # type: ignore
|
||||
)
|
||||
else:
|
||||
self.client = ExtPahoClient(
|
||||
paho_mqtt.CallbackAPIVersion.VERSION1, client_id, # type: ignore
|
||||
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] = {}
|
||||
|
||||
# We don't need to register these endpoints over the MQTT transport as they
|
||||
# are redundant. MQTT clients can already publish and subscribe.
|
||||
ep_transports = TransportType.all() & ~TransportType.MQTT
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/publish", RequestType.POST, self._handle_publish_request,
|
||||
transports=ep_transports
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/subscribe", RequestType.POST,
|
||||
self._handle_subscription_request,
|
||||
transports=ep_transports
|
||||
)
|
||||
|
||||
# Subscribe to API requests
|
||||
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, str] = config.getdict(
|
||||
"status_objects", {}, allow_empty_fields=True
|
||||
)
|
||||
self.status_interval = config.getfloat("status_interval", 0, above=.25)
|
||||
self.status_cache: Dict[str, Dict[str, Any]] = {}
|
||||
self.status_update_timer: Optional[FlexTimer] = None
|
||||
self.last_status_time = 0.
|
||||
self.status_objs: Dict[str, Optional[List[str]]] = {}
|
||||
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.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._handle_klippy_disconnect
|
||||
)
|
||||
if self.status_interval:
|
||||
self.status_update_timer = self.eventloop.register_timer(
|
||||
self._handle_timed_status_update
|
||||
)
|
||||
|
||||
self.timestamp_deque: Deque = deque(maxlen=20)
|
||||
self.api_qos = config.getint('api_qos', self.qos)
|
||||
if config.getboolean("enable_moonraker_api", True):
|
||||
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=jsonw.dumps({'server': 'offline'}),
|
||||
qos=self.qos, retain=True)
|
||||
if self.tls_enabled:
|
||||
self.client.tls_set()
|
||||
self.client.connect_async(self.address, self.port)
|
||||
self.connect_task = self.eventloop.create_task(
|
||||
self._do_reconnect(first=True)
|
||||
)
|
||||
|
||||
async def _handle_klippy_started(self, state: KlippyState) -> None:
|
||||
if self.status_objs:
|
||||
kapi: KlippyAPI = self.server.lookup_component("klippy_apis")
|
||||
result = await kapi.subscribe_from_transport(
|
||||
self.status_objs, self, default=None, full_response=True
|
||||
)
|
||||
if result is not None:
|
||||
status: Dict[str, Any] = result["status"]
|
||||
eventtime: float = result["eventtime"]
|
||||
self.send_status(status, eventtime)
|
||||
if self.status_update_timer is not None:
|
||||
self.status_update_timer.start(delay=self.status_interval)
|
||||
|
||||
def _handle_klippy_disconnect(self):
|
||||
if self.status_update_timer is not None:
|
||||
self.status_update_timer.stop()
|
||||
if self.status_cache:
|
||||
payload = self.status_cache
|
||||
self.status_cache = {}
|
||||
self._publish_status_update(payload, self.last_status_time)
|
||||
|
||||
def _on_message(self,
|
||||
client: str | paho_mqtt.Client,
|
||||
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.eventloop.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, ReasonCode],
|
||||
properties: Optional[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:
|
||||
_, msg_id = client.subscribe(subs)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = self.eventloop.create_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[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 = self.eventloop.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[ReasonCode]],
|
||||
properties: Optional[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[Properties] = None,
|
||||
reasoncodes: Optional[ReasonCode] = 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.eventloop.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) is not type(e) or last_err.args != e.args:
|
||||
logging.exception("MQTT Connection Error")
|
||||
last_err = e
|
||||
continue
|
||||
sock.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:
|
||||
_, msg_id = self.client.subscribe(topic, qos)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = self.eventloop.create_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]
|
||||
_, msg_id = self.client.unsubscribe(topic)
|
||||
if msg_id is not None:
|
||||
unsub_fut: asyncio.Future = self.eventloop.create_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 = self.eventloop.create_future()
|
||||
if isinstance(payload, (dict, list)):
|
||||
try:
|
||||
payload = jsonw.dumps(payload)
|
||||
except jsonw.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 = self.eventloop.create_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 = self.eventloop.create_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 = jsonw.loads(ret)
|
||||
except jsonw.JSONDecodeError:
|
||||
payload = ret.decode()
|
||||
return {
|
||||
'topic': topic,
|
||||
'payload': payload
|
||||
}
|
||||
|
||||
async def _process_api_request(self, payload: bytes) -> None:
|
||||
rpc: JsonRPC = self.server.lookup_component("jsonrpc")
|
||||
response = await rpc.dispatch(payload, self)
|
||||
if response is not None:
|
||||
await self.publish_topic(self.api_resp_topic, response,
|
||||
self.api_qos)
|
||||
|
||||
@property
|
||||
def transport_type(self) -> TransportType:
|
||||
return TransportType.MQTT
|
||||
|
||||
def screen_rpc_request(
|
||||
self, api_def: APIDefinition, req_type: RequestType, 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 not self.status_interval:
|
||||
self._publish_status_update(status, eventtime)
|
||||
else:
|
||||
for key, val in status.items():
|
||||
self.status_cache.setdefault(key, {}).update(val)
|
||||
self.last_status_time = eventtime
|
||||
|
||||
def _handle_timed_status_update(self, eventtime: float) -> float:
|
||||
if self.status_cache:
|
||||
payload = self.status_cache
|
||||
self.status_cache = {}
|
||||
self._publish_status_update(payload, self.last_status_time)
|
||||
return eventtime + self.status_interval
|
||||
|
||||
def _publish_status_update(self, status: Dict[str, Any], eventtime: float) -> None:
|
||||
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.status_update_timer is not None:
|
||||
self.status_update_timer.stop()
|
||||
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,217 @@
|
||||
# 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
|
||||
import pathlib
|
||||
import re
|
||||
from ..common import JobEvent, RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict,
|
||||
Any,
|
||||
List,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .file_manager.file_manager import FileManager
|
||||
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, List[NotifierInstance]] = {}
|
||||
prefix_sections = config.get_prefix_sections("notifier")
|
||||
self.register_remote_actions()
|
||||
logging.info(f"Loading notifiers, Apprise version {apprise.__version__}")
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
try:
|
||||
notifier = NotifierInstance(cfg)
|
||||
for job_event in list(JobEvent):
|
||||
if job_event == JobEvent.STANDBY:
|
||||
continue
|
||||
evt_name = str(job_event)
|
||||
if "*" in notifier.events or evt_name in notifier.events:
|
||||
self.events.setdefault(evt_name, []).append(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, exc_info=e)
|
||||
continue
|
||||
self.notifiers[notifier.get_name()] = notifier
|
||||
|
||||
self.register_endpoints(config)
|
||||
self.server.register_event_handler(
|
||||
"job_state:state_changed", self._on_job_state_changed
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
async def _on_job_state_changed(
|
||||
self,
|
||||
job_event: JobEvent,
|
||||
prev_stats: Dict[str, Any],
|
||||
new_stats: Dict[str, Any]
|
||||
) -> None:
|
||||
evt_name = str(job_event)
|
||||
for notifier in self.events.get(evt_name, []):
|
||||
await notifier.notify(evt_name, [prev_stats, new_stats])
|
||||
|
||||
def register_endpoints(self, config: ConfigHelper):
|
||||
self.server.register_endpoint(
|
||||
"/server/notifiers/list", RequestType.GET, self._handle_notifier_list
|
||||
)
|
||||
self.server.register_debug_endpoint(
|
||||
"/debug/notifiers/test", RequestType.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)
|
||||
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 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.attach = config.gettemplate("attach", None)
|
||||
url_template = config.gettemplate("url")
|
||||
self.url = url_template.render()
|
||||
|
||||
if re.match(r"\w+?://", self.url) is None:
|
||||
raise config.error(f"Invalid url for: {config.get_name()}")
|
||||
|
||||
self.title = config.gettemplate("title", None)
|
||||
self.body = config.gettemplate("body", None)
|
||||
upper_body_format = config.get("body_format", 'text').upper()
|
||||
if not hasattr(apprise.NotifyFormat, upper_body_format):
|
||||
raise config.error(f"Invalid body_format for {config.get_name()}")
|
||||
self.body_format = getattr(apprise.NotifyFormat, upper_body_format)
|
||||
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),
|
||||
"body_format": self.config.get("body_format", 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
|
||||
attachments: List[str] = []
|
||||
if self.attach is not None:
|
||||
fm: FileManager = self.server.lookup_component("file_manager")
|
||||
try:
|
||||
rendered = self.attach.render(context)
|
||||
except self.server.error as e:
|
||||
self.server.add_warning(
|
||||
f"[notifier {self.name}]: The attachment is not valid. The "
|
||||
"template failed to render.",
|
||||
f"notifier {self.name}",
|
||||
exc_info=e
|
||||
)
|
||||
self.attach = None
|
||||
else:
|
||||
for item in rendered.splitlines():
|
||||
item = item.strip()
|
||||
if not item:
|
||||
continue
|
||||
if re.match(r"https?://", item) is not None:
|
||||
# Attachment is a url, system check not necessary
|
||||
attachments.append(item)
|
||||
continue
|
||||
attach_path = pathlib.Path(item).expanduser().resolve()
|
||||
if not attach_path.is_file():
|
||||
self.server.add_warning(
|
||||
f"[notifier {self.name}]: Invalid attachment detected, "
|
||||
f"file does not exist: {attach_path}.",
|
||||
f"notifier {self.name}"
|
||||
)
|
||||
elif not fm.can_access_path(attach_path):
|
||||
self.server.add_warning(
|
||||
f"[notifier {self.name}]: Invalid attachment detected, "
|
||||
f"no read permission for the file {attach_path}.",
|
||||
f"notifier {self.name}"
|
||||
)
|
||||
else:
|
||||
attachments.append(str(attach_path))
|
||||
await self.apprise.async_notify(
|
||||
rendered_body.strip(), rendered_title.strip(),
|
||||
body_format=self.body_format,
|
||||
attach=None if not attachments else attachments
|
||||
)
|
||||
|
||||
def get_name(self) -> str:
|
||||
return self.name
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Notifier:
|
||||
return Notifier(config)
|
||||
@@ -0,0 +1,413 @@
|
||||
# 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
|
||||
from ..common import RequestType, TransportType, KlippyState
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from .klippy_connection import KlippyConnection
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common 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', RequestType.GET, self._get_version,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
'/api/server', RequestType.GET, self._get_server,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
|
||||
# Login, User & Settings
|
||||
self.server.register_endpoint(
|
||||
'/api/login', RequestType.POST, self._post_login_user,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
'/api/currentuser', RequestType.GET, self._post_login_user,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
'/api/settings', RequestType.GET, self._get_settings,
|
||||
transports=TransportType.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', RequestType.GET, self._get_job,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
# TODO: start/cancel/restart/pause jobs
|
||||
|
||||
# Printer operations
|
||||
self.server.register_endpoint(
|
||||
'/api/printer', RequestType.GET, self._get_printer,
|
||||
transports=TransportType.HTTP, wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/printer/command', RequestType.POST, self._post_command,
|
||||
transports=TransportType.HTTP, wrap_result=False
|
||||
)
|
||||
# TODO: head/tool/bed/chamber specific read/issue
|
||||
|
||||
# Printer profiles
|
||||
self.server.register_endpoint(
|
||||
'/api/printerprofiles', RequestType.GET, self._get_printerprofiles,
|
||||
transports=TransportType.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>.+)", RequestType.POST,
|
||||
self._select_file, transports=TransportType.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:
|
||||
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
|
||||
klippy_state = kconn.state
|
||||
if not klippy_state.startup_complete():
|
||||
return 'Offline'
|
||||
elif klippy_state != KlippyState.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
|
||||
"""
|
||||
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
|
||||
klippy_state = kconn.state
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'safemode': None if klippy_state == KlippyState.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_str('command')
|
||||
rel_path: str = web_request.get_str('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_boolean('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
|
||||
user = web_request.get_current_user()
|
||||
if pstate not in ["printing", "paused", "not_avail"]:
|
||||
try:
|
||||
await self.klippy_apis.start_print(filename, user=user)
|
||||
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, user=user)
|
||||
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)
|
||||
@@ -3,17 +3,33 @@
|
||||
# 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
|
||||
|
||||
from __future__ import annotations
|
||||
import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from utils import ServerError
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from ..utils import ServerError, async_serial
|
||||
from ..utils import json_wrapper as jsonw
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Deque,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Callable,
|
||||
Coroutine,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from .klippy_connection import KlippyConnection
|
||||
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.
|
||||
@@ -24,197 +40,79 @@ class PanelDueError(ServerError):
|
||||
|
||||
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
|
||||
|
||||
class SerialConnection:
|
||||
def __init__(self, config, paneldue):
|
||||
self.ioloop = IOLoop.current()
|
||||
self.paneldue = paneldue
|
||||
self.port = config.get('serial')
|
||||
self.baud = config.getint('baud', 57600)
|
||||
self.partial_input = b""
|
||||
self.ser = self.fd = None
|
||||
self.connected = False
|
||||
self.send_busy = False
|
||||
self.send_buffer = b""
|
||||
self.attempting_connect = True
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
|
||||
def disconnect(self, reconnect=False):
|
||||
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
|
||||
self.partial_input = b""
|
||||
self.send_buffer = b""
|
||||
self.paneldue.initialized = False
|
||||
logging.info("PanelDue Disconnected")
|
||||
if reconnect and not self.attempting_connect:
|
||||
self.attempting_connect = True
|
||||
self.ioloop.call_later(1., self._connect)
|
||||
|
||||
async def _connect(self):
|
||||
start_time = connect_time = time.time()
|
||||
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 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")
|
||||
self.attempting_connect = False
|
||||
|
||||
def _handle_incoming(self, fd, events):
|
||||
if events & IOLoop.ERROR:
|
||||
logging.info("PanelDue Connection Error")
|
||||
self.disconnect(reconnect=True)
|
||||
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(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:
|
||||
line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(line)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
f"GCode Processing Error: {line}")
|
||||
self.paneldue.handle_gcode_response(
|
||||
f"!! GCode Processing Error: {line}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
|
||||
def send(self, data):
|
||||
self.send_buffer += data
|
||||
if not self.send_busy:
|
||||
self.send_busy = True
|
||||
self.ioloop.spawn_callback(self._do_send)
|
||||
|
||||
async def _do_send(self):
|
||||
while self.send_buffer:
|
||||
try:
|
||||
sent = os.write(self.fd, self.send_buffer)
|
||||
except os.error as e:
|
||||
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
|
||||
sent = 0
|
||||
else:
|
||||
await gen.sleep(.001)
|
||||
continue
|
||||
if sent:
|
||||
self.send_buffer = self.send_buffer[sent:]
|
||||
else:
|
||||
logging.exception(
|
||||
"Error writing data, closing serial connection")
|
||||
self.disconnect(reconnect=True)
|
||||
return
|
||||
self.send_busy = False
|
||||
|
||||
class PanelDue:
|
||||
def __init__(self, config):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.ser_conn = SerialConnection(config, self)
|
||||
self.file_manager = self.server.lookup_plugin('file_manager')
|
||||
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
self.kinematics = "none"
|
||||
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 = "Repetier | Klipper"
|
||||
self.last_message = None
|
||||
self.last_gcode_response = None
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
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(maxlen=100)
|
||||
self.debug_queue: Deque[str] = deque(maxlen=100)
|
||||
self.enabled: bool = True
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state = {
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
self.initialized = False
|
||||
self.cq_busy = self.gq_busy = False
|
||||
self.command_queue = []
|
||||
self.gc_queue = []
|
||||
self.last_printer_state = 'O'
|
||||
self.last_update_time = 0.
|
||||
kconn: KlippyConnection = self.server.lookup_component("klippy_connection")
|
||||
self.printer_state: Dict[str, Dict[str, Any]] = kconn.get_subscription_cache()
|
||||
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 = ""
|
||||
self.mbox_sequence = 0
|
||||
self.available_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.get('macros', None)
|
||||
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
|
||||
macros = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
conf_macros = config.get('confirmed_macros', None)
|
||||
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
|
||||
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
|
||||
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
|
||||
self.available_macros.update(self.confirmed_macros)
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
|
||||
self.non_trivial_keys = config.getlist('non_trivial_keys', ["Klipper state"])
|
||||
self.ser_conn = async_serial.AsyncSerialConnection.from_config(config)
|
||||
logging.info("PanelDue Configured")
|
||||
|
||||
# Register server events
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._process_klippy_ready)
|
||||
"server:klippy_ready", self._process_klippy_ready
|
||||
)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._process_klippy_shutdown)
|
||||
"server:klippy_shutdown", self._process_klippy_shutdown
|
||||
)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._process_klippy_disconnect)
|
||||
"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)
|
||||
"server:gcode_response", self.handle_gcode_response
|
||||
)
|
||||
self.server.register_remote_method("paneldue_beep", self.paneldue_beep)
|
||||
|
||||
self.server.register_remote_method(
|
||||
"paneldue_beep", self.paneldue_beep)
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# These commands are directly executed on the server and do not to
|
||||
# make a request to Klippy
|
||||
self.direct_gcodes = {
|
||||
self.direct_gcodes: Dict[str, FlexCallback] = {
|
||||
'M20': self._run_paneldue_M20,
|
||||
'M30': self._run_paneldue_M30,
|
||||
'M36': self._run_paneldue_M36,
|
||||
@@ -223,7 +121,7 @@ class PanelDue:
|
||||
|
||||
# These gcodes require special parsing or handling prior to being
|
||||
# sent via Klippy's "gcode/script" api command.
|
||||
self.special_gcodes = {
|
||||
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
|
||||
'M0': lambda args: "CANCEL_PRINT",
|
||||
'M23': self._prepare_M23,
|
||||
'M24': lambda args: "RESUME",
|
||||
@@ -237,28 +135,60 @@ class PanelDue:
|
||||
'M999': lambda args: "FIRMWARE_RESTART"
|
||||
}
|
||||
|
||||
async def _process_klippy_ready(self):
|
||||
async def run_serial(self) -> None:
|
||||
last_exc = Exception()
|
||||
while self.enabled:
|
||||
try:
|
||||
self.ser_conn.open()
|
||||
except (self.ser_conn.error, OSError) as e:
|
||||
if type(last_exc) is not type(e) and last_exc.args != e.args:
|
||||
logging.exception("PanelDue Serial Open Error")
|
||||
last_exc = e
|
||||
await asyncio.sleep(2.)
|
||||
continue
|
||||
reader = self.ser_conn.reader
|
||||
decoded_line: str = ""
|
||||
async for line in reader:
|
||||
try:
|
||||
decoded_line = line.strip().decode('utf-8', 'ignore')
|
||||
self.process_line(decoded_line)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except ServerError:
|
||||
msg = f"GCode Processing Error: {decoded_line}"
|
||||
logging.exception(msg)
|
||||
self.handle_gcode_response(f"!! {msg}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
if self.enabled:
|
||||
await asyncio.sleep(2.)
|
||||
last_exc = Exception()
|
||||
self.initialized = False
|
||||
|
||||
async def component_init(self) -> None:
|
||||
self.serial_task = self.event_loop.create_task(self.run_serial())
|
||||
|
||||
async def _process_klippy_ready(self) -> None:
|
||||
# Request "info" and "configfile" status
|
||||
retries = 10
|
||||
printer_info = cfg_status = {}
|
||||
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})
|
||||
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 gen.sleep(1.)
|
||||
await asyncio.sleep(1.)
|
||||
continue
|
||||
break
|
||||
|
||||
self.firmware_name = "Repetier | Klipper " + \
|
||||
printer_info['software_version']
|
||||
config = cfg_status.get('configfile', {}).get('config', {})
|
||||
printer_cfg = config.get('printer', {})
|
||||
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(
|
||||
@@ -267,66 +197,65 @@ class PanelDue:
|
||||
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()}
|
||||
# Make subscription request
|
||||
sub_args: Dict[str, Optional[List[str]]] = {
|
||||
"motion_report": None,
|
||||
"gcode_move": None,
|
||||
"toolhead": None,
|
||||
"virtual_sdcard": None,
|
||||
"fan": None,
|
||||
"display_status": None,
|
||||
"print_stats": None,
|
||||
"idle_timeout": None,
|
||||
"gcode_macro PANELDUE_BEEP": None
|
||||
}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
extruders = []
|
||||
for cfg in config:
|
||||
if cfg.startswith("extruder"):
|
||||
self.extruder_count += 1
|
||||
self.printer_state[cfg] = {}
|
||||
self.heaters.append(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 = await self.klippy_apis.subscribe_objects(sub_args)
|
||||
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):
|
||||
def _process_klippy_shutdown(self) -> None:
|
||||
self.is_shutdown = True
|
||||
|
||||
def _process_klippy_disconnect(self):
|
||||
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_ready = False
|
||||
self.is_shutdown = self.is_shutdown = False
|
||||
|
||||
def handle_status_update(self, status):
|
||||
for obj, items in status.items():
|
||||
if obj in self.printer_state:
|
||||
self.printer_state[obj].update(items)
|
||||
else:
|
||||
self.printer_state[obj] = items
|
||||
|
||||
def paneldue_beep(self, frequency, duration):
|
||||
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):
|
||||
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.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
|
||||
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 = int(line[1:line_index])
|
||||
line_no: Optional[int] = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
@@ -368,7 +297,7 @@ class PanelDue:
|
||||
|
||||
# Check for commands that query state and require immediate response
|
||||
if cmd in self.direct_gcodes:
|
||||
params = {}
|
||||
params: Dict[str, Any] = {}
|
||||
for p in parts[1:]:
|
||||
if p[0] not in "PSR":
|
||||
params["arg_p"] = p.strip(" \"\t\n")
|
||||
@@ -389,20 +318,20 @@ class PanelDue:
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
if cmd in self.special_gcodes:
|
||||
func = self.special_gcodes[cmd]
|
||||
script = func(parts[1:])
|
||||
sgc_func = self.special_gcodes[cmd]
|
||||
script = sgc_func(parts[1:])
|
||||
|
||||
if not script:
|
||||
return
|
||||
self.queue_gcode(script)
|
||||
|
||||
def queue_gcode(self, script):
|
||||
def queue_gcode(self, script: str) -> None:
|
||||
self.gc_queue.append(script)
|
||||
if not self.gq_busy:
|
||||
self.gq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_gcode_queue)
|
||||
self.event_loop.register_callback(self._process_gcode_queue)
|
||||
|
||||
async def _process_gcode_queue(self):
|
||||
async def _process_gcode_queue(self) -> None:
|
||||
while self.gc_queue:
|
||||
script = self.gc_queue.pop(0)
|
||||
try:
|
||||
@@ -416,24 +345,24 @@ class PanelDue:
|
||||
logging.exception(msg)
|
||||
self.gq_busy = False
|
||||
|
||||
def queue_command(self, cmd, *args, **kwargs):
|
||||
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.ioloop.spawn_callback(self._process_command_queue)
|
||||
self.event_loop.register_callback(self._process_command_queue)
|
||||
|
||||
async def _process_command_queue(self):
|
||||
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 asyncio.iscoroutine(ret):
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception("Error processing command")
|
||||
self.cq_busy = False
|
||||
|
||||
def _clean_filename(self, filename):
|
||||
def _clean_filename(self, filename: str) -> str:
|
||||
# Remove quotes and whitespace
|
||||
filename.strip(" \"\t\n")
|
||||
# Remove drive number
|
||||
@@ -451,17 +380,17 @@ class PanelDue:
|
||||
filename = "/" + filename
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args):
|
||||
def _prepare_M23(self, args: List[str]) -> str:
|
||||
filename = self._clean_filename(args[0])
|
||||
return f"M23 {filename}"
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
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):
|
||||
def _prepare_M98(self, args: List[str]) -> str:
|
||||
macro = args[0][1:].strip(" \"\t\n")
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
@@ -473,12 +402,12 @@ class PanelDue:
|
||||
cmd = ""
|
||||
return cmd
|
||||
|
||||
def _prepare_M290(self, args):
|
||||
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):
|
||||
def _prepare_M292(self, args: List[str]) -> str:
|
||||
p_val = int(args[0][1])
|
||||
if p_val == 0:
|
||||
cmd = self.confirmed_gcode
|
||||
@@ -486,13 +415,13 @@ class PanelDue:
|
||||
return cmd
|
||||
return ""
|
||||
|
||||
def _create_confirmation(self, name, gcode):
|
||||
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 = {}
|
||||
mbox: Dict[str, Any] = {}
|
||||
mbox['msgBox.mode'] = 3
|
||||
mbox['msgBox.msg'] = msg
|
||||
mbox['msgBox.seq'] = self.mbox_sequence
|
||||
@@ -502,7 +431,7 @@ class PanelDue:
|
||||
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
|
||||
self.write_response(mbox)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
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 \
|
||||
@@ -514,11 +443,11 @@ class PanelDue:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
def write_response(self, response):
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
self.ser_conn.send(byte_resp.encode())
|
||||
def write_response(self, response: Dict[str, Any]) -> None:
|
||||
byte_resp = jsonw.dumps(response) + b"\r\n"
|
||||
self.ser_conn.send(byte_resp)
|
||||
|
||||
def _get_printer_status(self):
|
||||
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,
|
||||
@@ -526,8 +455,9 @@ class PanelDue:
|
||||
if self.is_shutdown:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
sd_state = printer_state['print_stats'].get('state', "standby")
|
||||
p_state = self.printer_state
|
||||
sd_state: str
|
||||
sd_state = p_state.get("print_stats", {}).get("state", "standby")
|
||||
if sd_state == "printing":
|
||||
if self.last_printer_state == 'A':
|
||||
# Resuming
|
||||
@@ -535,8 +465,9 @@ class PanelDue:
|
||||
# Printing
|
||||
return 'P'
|
||||
elif sd_state == "paused":
|
||||
p_active = printer_state['idle_timeout'].get(
|
||||
'state', 'Idle') == "Printing"
|
||||
p_active = (
|
||||
p_state.get("idle_timeout", {}).get("state", 'Idle') == "Printing"
|
||||
)
|
||||
if p_active and self.last_printer_state != 'A':
|
||||
# Pausing
|
||||
return 'D'
|
||||
@@ -546,12 +477,15 @@ class PanelDue:
|
||||
|
||||
return 'I'
|
||||
|
||||
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
response = {}
|
||||
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.ioloop.time()
|
||||
curtime = self.event_loop.get_loop_time()
|
||||
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
|
||||
self.initialized = False
|
||||
self.last_update_time = curtime
|
||||
@@ -579,54 +513,64 @@ class PanelDue:
|
||||
response['axes'] = 3
|
||||
|
||||
p_state = self.printer_state
|
||||
toolhead = p_state.get("toolhead", {})
|
||||
gcode_move = p_state.get("gcode_move", {})
|
||||
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)
|
||||
response['babystep'] = round(
|
||||
gcode_move.get('homing_origin', [0., 0., 0., 0.])[2], 3
|
||||
)
|
||||
|
||||
# Current position
|
||||
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
|
||||
pos: List[float]
|
||||
homed_pos: str
|
||||
sfactor: float
|
||||
pos = p_state.get("motion_report", {}).get('live_position', [0., 0., 0., 0.])
|
||||
response['pos'] = [round(p, 2) for p in pos[:3]]
|
||||
homed_pos = p_state['toolhead'].get('homed_axes', "")
|
||||
homed_pos = 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)
|
||||
sfactor = round(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 = print_stats.get('filename', "")
|
||||
sd_print_state = print_stats.get('state')
|
||||
sd_status = p_state.get('virtual_sdcard', {})
|
||||
print_stats = p_state.get('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 = sd_status.get('progress', 0)
|
||||
progress: float = sd_status.get('progress', 0)
|
||||
# progress and print tracking
|
||||
if progress:
|
||||
response['fraction_printed'] = round(progress, 3)
|
||||
est_time = self.file_metadata.get('estimated_time', 0)
|
||||
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 = print_stats.get('filament_used', 0.)
|
||||
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 = p_state['gcode_move'].get(
|
||||
'gcode_position', [0., 0., 0., 0.])[2]
|
||||
cur_height: float = 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 = print_stats.get('print_duration', 0.)
|
||||
duration: float = print_stats.get('print_duration', 0.)
|
||||
times_left = [int(duration / progress - duration)]
|
||||
response['timesLeft'] = times_left
|
||||
else:
|
||||
@@ -634,35 +578,39 @@ class PanelDue:
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
|
||||
fan_speed = p_state['fan'].get('speed')
|
||||
fan_speed: Optional[float] = p_state.get('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 is not None:
|
||||
extruder_name = toolhead.get('extruder', "")
|
||||
if extruder_name:
|
||||
tool = 0
|
||||
if extruder_name != "extruder":
|
||||
tool = int(extruder_name[-1])
|
||||
response['tool'] = tool
|
||||
|
||||
# Report Heater Status
|
||||
efactor = round(p_state['gcode_move'].get(
|
||||
'extrude_factor', 1.) * 100., 2)
|
||||
efactor: float = round(gcode_move.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)
|
||||
htr_state = p_state.get(name, {})
|
||||
temp: float = round(htr_state.get('temperature', 0.0), 1)
|
||||
target: float = round(htr_state.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'):
|
||||
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 = p_state['display_status'].get('message')
|
||||
msg: str = p_state.get('display_status', {}).get('message', "")
|
||||
if msg and msg != self.last_message:
|
||||
response['message'] = msg
|
||||
# reset the message so it only shows once. The paneldue
|
||||
@@ -671,7 +619,7 @@ class PanelDue:
|
||||
self.last_message = msg
|
||||
self.write_response(response)
|
||||
|
||||
def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
@@ -687,7 +635,7 @@ class PanelDue:
|
||||
# ie. "0:/"
|
||||
if path.startswith("0:/"):
|
||||
path = path[2:]
|
||||
response = {'dir': path}
|
||||
response: Dict[str, Any] = {'dir': path}
|
||||
response['files'] = []
|
||||
|
||||
if path == "/macros":
|
||||
@@ -711,7 +659,7 @@ class PanelDue:
|
||||
response['files'] = flist
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p=None):
|
||||
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
|
||||
@@ -725,9 +673,9 @@ class PanelDue:
|
||||
path = "gcodes/" + path
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
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:
|
||||
@@ -754,37 +702,41 @@ class PanelDue:
|
||||
if not filename.startswith("gcodes/"):
|
||||
filename = "gcodes/" + filename
|
||||
|
||||
metadata = self.file_manager.get_file_metadata(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 = metadata.get('slicer')
|
||||
slicer: Optional[str] = metadata.get('slicer')
|
||||
if slicer is not None:
|
||||
response['generatedBy'] = slicer
|
||||
height = metadata.get('object_height')
|
||||
height: Optional[float] = metadata.get('object_height')
|
||||
if height is not None:
|
||||
response['height'] = round(height, 2)
|
||||
layer_height = metadata.get('layer_height')
|
||||
layer_height: Optional[float] = metadata.get('layer_height')
|
||||
if layer_height is not None:
|
||||
response['layerHeight'] = round(layer_height, 2)
|
||||
filament = metadata.get('filament_total')
|
||||
filament: Optional[float] = metadata.get('filament_total')
|
||||
if filament is not None:
|
||||
response['filament'] = [round(filament, 1)]
|
||||
est_time = metadata.get('estimated_time')
|
||||
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):
|
||||
self.ser_conn.disconnect()
|
||||
async def close(self) -> None:
|
||||
self.enabled = False
|
||||
await self.ser_conn.close()
|
||||
if hasattr(self, "serial_task"):
|
||||
await self.serial_task
|
||||
msg = "\nPanelDue GCode Dump:"
|
||||
for i, gc in enumerate(self.debug_queue):
|
||||
msg += f"\nSequence {i}: {gc}"
|
||||
logging.debug(msg)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config: ConfigHelper) -> PanelDue:
|
||||
return PanelDue(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,418 @@
|
||||
# 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 struct
|
||||
import fcntl
|
||||
import time
|
||||
import re
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
from collections import deque
|
||||
from ..utils import ioctl_macros
|
||||
from ..common import RequestType
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Awaitable,
|
||||
Callable,
|
||||
Deque,
|
||||
Any,
|
||||
List,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .websockets import WebsocketManager
|
||||
STAT_CALLBACK = Callable[[int], Optional[Awaitable]]
|
||||
|
||||
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
|
||||
VCIO_PATH = "/dev/vcio"
|
||||
STATM_FILE_PATH = "/proc/self/smaps_rollup"
|
||||
NET_DEV_PATH = "/proc/net/dev"
|
||||
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
|
||||
HWMON_ROOT_PATH = "/sys/class/hwmon/"
|
||||
HWMON_PLATFORMS = {
|
||||
"coretemp": "Intel",
|
||||
"k10temp": "AMD",
|
||||
"cpu_thermal": "Raspberry Pi"
|
||||
}
|
||||
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[VCGenCmd] = None
|
||||
if os.path.exists(VC_GEN_CMD_FILE) and os.path.exists(VCIO_PATH):
|
||||
logging.info("Detected 'vcgencmd', throttle checking enabled")
|
||||
self.vcgencmd = VCGenCmd()
|
||||
self.server.register_notification("proc_stats:cpu_throttled")
|
||||
else:
|
||||
logging.info("Unable to find 'vcgencmd', throttle checking "
|
||||
"disabled")
|
||||
self.temp_file = pathlib.Path(self._get_cpu_thermal_file())
|
||||
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", RequestType.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
|
||||
and 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]:
|
||||
ret = {'bits': 0, 'flags': ["?"]}
|
||||
if self.vcgencmd is not None:
|
||||
async with self.throttle_check_lock:
|
||||
try:
|
||||
resp = await self.event_loop.run_in_thread(self.vcgencmd.run)
|
||||
ret["bits"] = tstate = int(resp.strip().split("=")[-1], 16)
|
||||
ret["flags"] = [
|
||||
desc for flag, desc in THROTTLED_FLAGS.items() if flag & tstate
|
||||
]
|
||||
except Exception:
|
||||
pass
|
||||
return ret
|
||||
|
||||
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 _get_cpu_thermal_file(self) -> str:
|
||||
if os.path.isdir(HWMON_ROOT_PATH):
|
||||
for hwmon in os.scandir(HWMON_ROOT_PATH):
|
||||
if not hwmon.is_dir():
|
||||
continue
|
||||
hwmon_name = pathlib.Path(hwmon.path + "/name")
|
||||
try:
|
||||
name = hwmon_name.read_text().strip()
|
||||
if name in HWMON_PLATFORMS:
|
||||
pf = HWMON_PLATFORMS[name]
|
||||
logging.info(f"Monitoring temperature for {pf} CPU")
|
||||
return hwmon.path + "/temp1_input"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
logging.info("Monitoring temperature using default thermal zone")
|
||||
return TEMPERATURE_PATH
|
||||
|
||||
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()
|
||||
|
||||
class VCGenCmd:
|
||||
"""
|
||||
This class uses the BCM2835 Mailbox to directly query the throttled
|
||||
state. This should be less resource intensive than calling "vcgencmd"
|
||||
in a subprocess.
|
||||
"""
|
||||
MAX_STRING_SIZE = 1024
|
||||
GET_RESULT_CMD = 0x00030080
|
||||
UINT_SIZE = struct.calcsize("@I")
|
||||
def __init__(self) -> None:
|
||||
self.cmd_struct = struct.Struct(f"@6I{self.MAX_STRING_SIZE}sI")
|
||||
self.cmd_buf = bytearray(self.cmd_struct.size)
|
||||
self.mailbox_req = ioctl_macros.IOWR(100, 0, "c_char_p")
|
||||
self.err_logged: bool = False
|
||||
|
||||
def run(self, cmd: str = "get_throttled") -> str:
|
||||
try:
|
||||
fd = os.open(VCIO_PATH, os.O_RDWR)
|
||||
self.cmd_struct.pack_into(
|
||||
self.cmd_buf, 0,
|
||||
self.cmd_struct.size,
|
||||
0x00000000,
|
||||
self.GET_RESULT_CMD,
|
||||
self.MAX_STRING_SIZE,
|
||||
0,
|
||||
0,
|
||||
cmd.encode("utf-8"),
|
||||
0x00000000
|
||||
)
|
||||
fcntl.ioctl(fd, self.mailbox_req, self.cmd_buf)
|
||||
except OSError:
|
||||
if not self.err_logged:
|
||||
logging.exception("VCIO vcgencmd failed")
|
||||
self.err_logged = True
|
||||
return ""
|
||||
finally:
|
||||
os.close(fd)
|
||||
result = self.cmd_struct.unpack_from(self.cmd_buf)
|
||||
ret: int = result[5]
|
||||
if ret:
|
||||
logging.info(f"vcgencmd returned {ret}")
|
||||
resp: bytes = result[6]
|
||||
null_index = resp.find(b'\x00')
|
||||
if null_index <= 0:
|
||||
return ""
|
||||
return resp[:null_index].decode()
|
||||
|
||||
def load_component(config: ConfigHelper) -> ProcStats:
|
||||
return ProcStats(config)
|
||||
@@ -0,0 +1,90 @@
|
||||
# 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
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict,
|
||||
Optional,
|
||||
Any
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
|
||||
class Secrets:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
server = config.get_server()
|
||||
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] = {}
|
||||
self.secrets_file = fpath
|
||||
if fpath.is_file():
|
||||
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 get_secrets_file(self) -> pathlib.Path:
|
||||
return self.secrets_file
|
||||
|
||||
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 jsonw.loads(data)
|
||||
except jsonw.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,345 @@
|
||||
# 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 functools import partial
|
||||
from ..common import RequestType, HistoryFieldData
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
Any,
|
||||
DefaultDict,
|
||||
Deque,
|
||||
Dict,
|
||||
List,
|
||||
Optional,
|
||||
Type,
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
Callable
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .mqtt import MQTTClient
|
||||
from .history import History
|
||||
|
||||
SENSOR_UPDATE_TIME = 1.0
|
||||
SENSOR_EVENT_NAME = "sensors:sensor_update"
|
||||
|
||||
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
|
||||
|
||||
|
||||
class BaseSensor:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.error_state: Optional[str] = None
|
||||
self.id = config.get_name().split(maxsplit=1)[-1]
|
||||
self.type = config.get("type")
|
||||
self.name = config.get("name", self.id)
|
||||
self.last_measurements: Dict[str, Union[int, float]] = {}
|
||||
self.last_value: Dict[str, Union[int, float]] = {}
|
||||
store_size = config.getint("sensor_store_size", 1200)
|
||||
self.values: DefaultDict[str, Deque[Union[int, float]]] = defaultdict(
|
||||
lambda: deque(maxlen=store_size)
|
||||
)
|
||||
self.param_info: List[Dict[str, str]] = []
|
||||
history: History = self.server.lookup_component("history")
|
||||
self.field_info: Dict[str, List[HistoryFieldData]] = {}
|
||||
all_opts = list(config.get_options().keys())
|
||||
cfg_name = config.get_name()
|
||||
param_prefix = "parameter_"
|
||||
hist_field_prefix = "history_field_"
|
||||
for opt in all_opts:
|
||||
if opt.startswith(param_prefix):
|
||||
name = opt[len(param_prefix):]
|
||||
data = config.getdict(opt)
|
||||
data["name"] = opt[len(param_prefix):]
|
||||
self.param_info.append(data)
|
||||
continue
|
||||
if not opt.startswith(hist_field_prefix):
|
||||
continue
|
||||
name = opt[len(hist_field_prefix):]
|
||||
field_cfg: Dict[str, str] = config.getdict(opt)
|
||||
ident: Optional[str] = field_cfg.pop("parameter", None)
|
||||
if ident is None:
|
||||
raise config.error(
|
||||
f"[{cfg_name}]: option '{opt}', key 'parameter' must be"
|
||||
f"specified"
|
||||
)
|
||||
do_init: str = field_cfg.pop("init_tracker", "false").lower()
|
||||
reset_cb = self._gen_reset_callback(ident) if do_init == "true" else None
|
||||
excl_paused: str = field_cfg.pop("exclude_paused", "false").lower()
|
||||
report_total: str = field_cfg.pop("report_total", "false").lower()
|
||||
report_max: str = field_cfg.pop("report_maximum", "false").lower()
|
||||
precision: Optional[str] = field_cfg.pop("precision", None)
|
||||
try:
|
||||
fdata = HistoryFieldData(
|
||||
name,
|
||||
cfg_name,
|
||||
field_cfg.pop("desc", f"{ident} tracker"),
|
||||
field_cfg.pop("strategy", "basic"),
|
||||
units=field_cfg.pop("units", None),
|
||||
reset_callback=reset_cb,
|
||||
exclude_paused=excl_paused == "true",
|
||||
report_total=report_total == "true",
|
||||
report_maximum=report_max == "true",
|
||||
precision=int(precision) if precision is not None else None,
|
||||
)
|
||||
except Exception as e:
|
||||
raise config.error(
|
||||
f"[{cfg_name}]: option '{opt}', error encountered during "
|
||||
f"sensor field configuration: {e}"
|
||||
) from e
|
||||
for key in field_cfg.keys():
|
||||
self.server.add_warning(
|
||||
f"[{cfg_name}]: Option '{opt}' contains invalid key '{key}'"
|
||||
)
|
||||
self.field_info.setdefault(ident, []).append(fdata)
|
||||
history.register_auxiliary_field(fdata)
|
||||
|
||||
def _gen_reset_callback(self, param_name: str) -> Callable[[], float]:
|
||||
def on_reset() -> float:
|
||||
return self.last_measurements.get(param_name, 0)
|
||||
return on_reset
|
||||
|
||||
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.name)
|
||||
return True
|
||||
|
||||
def get_sensor_info(self, extended: bool = False) -> Dict[str, Any]:
|
||||
ret: Dict[str, Any] = {
|
||||
"id": self.id,
|
||||
"friendly_name": self.name,
|
||||
"type": self.type,
|
||||
"values": self.last_measurements,
|
||||
}
|
||||
if extended:
|
||||
ret["parameter_info"] = self.param_info
|
||||
history_fields: List[Dict[str, Any]] = []
|
||||
for parameter, field_list in self.field_info.items():
|
||||
for field_data in field_list:
|
||||
field_config = field_data.get_configuration()
|
||||
field_config["parameter"] = parameter
|
||||
history_fields.append(field_config)
|
||||
ret["history_fields"] = history_fields
|
||||
return ret
|
||||
|
||||
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.name
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class MQTTSensor(BaseSensor):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config=config)
|
||||
self.mqtt: MQTTClient = self.server.load_component(config, "mqtt")
|
||||
self.state_topic: str = config.get("state_topic")
|
||||
self.state_response = config.gettemplate("state_response_template")
|
||||
self.qos: Optional[int] = config.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
|
||||
for name, value in measurements.items():
|
||||
fdata_list = self.field_info.get(name)
|
||||
if fdata_list is None:
|
||||
continue
|
||||
for fdata in fdata_list:
|
||||
fdata.tracker.update(value)
|
||||
|
||||
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.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",
|
||||
RequestType.GET,
|
||||
self._handle_sensor_list_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/sensors/info",
|
||||
RequestType.GET,
|
||||
self._handle_sensor_info_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/sensors/measurements",
|
||||
RequestType.GET,
|
||||
self._handle_sensor_measurements_request,
|
||||
)
|
||||
|
||||
# Register notifications
|
||||
self.server.register_notification(SENSOR_EVENT_NAME)
|
||||
prefix_sections = config.get_prefix_sections("sensor ")
|
||||
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(cfg)
|
||||
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}", exc_info=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]]:
|
||||
extended = web_request.get_boolean("extended", False)
|
||||
return {
|
||||
"sensors": {
|
||||
key: sensor.get_sensor_info(extended)
|
||||
for key, sensor in self.sensors.items()
|
||||
}
|
||||
}
|
||||
|
||||
async def _handle_sensor_info_request(
|
||||
self, web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
sensor_name: str = web_request.get_str("sensor")
|
||||
extended = web_request.get_boolean("extended", False)
|
||||
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(extended)
|
||||
|
||||
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:
|
||||
sensor = self.sensors.get(sensor_name, None)
|
||||
if sensor is None:
|
||||
raise self.server.error(f"No valid sensor named {sensor_name}")
|
||||
return {sensor_name: sensor.get_sensor_measurements()}
|
||||
else:
|
||||
return {
|
||||
key: sensor.get_sensor_measurements()
|
||||
for key, sensor in self.sensors.items()
|
||||
}
|
||||
|
||||
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,440 @@
|
||||
# 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,
|
||||
cast
|
||||
)
|
||||
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,
|
||||
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.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:
|
||||
transport = cast(asyncio.SubprocessTransport, transport)
|
||||
self._transport = transport
|
||||
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(msg)
|
||||
if cb is not None:
|
||||
if isinstance(data, str):
|
||||
data = data.encode()
|
||||
lines = cast(bytes, 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.,
|
||||
attempts: 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)
|
||||
attempts = max(1, attempts)
|
||||
stdin: Optional[bytes] = None
|
||||
stdout = stderr = b""
|
||||
if proc_input is not None:
|
||||
stdin = proc_input.encode()
|
||||
while attempts > 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
|
||||
attempts -= 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, 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 asyncio.CancelledError:
|
||||
raise
|
||||
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.eventloop = config.get_server().get_event_loop()
|
||||
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 run_cmd_async(
|
||||
self,
|
||||
cmd: str,
|
||||
callback: OutputCallback = None,
|
||||
std_err_callback: OutputCallback = None,
|
||||
timeout: float = 2.,
|
||||
attempts: int = 1,
|
||||
verbose: bool = True,
|
||||
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[None]:
|
||||
"""
|
||||
Runs a command and processes responses as they are received. Optional
|
||||
callbacks may be provided to handle stdout and stderr.
|
||||
"""
|
||||
scmd = ShellCommand(
|
||||
self, cmd, callback, std_err_callback, env, log_stderr, cwd
|
||||
)
|
||||
attempts = max(1, attempts)
|
||||
|
||||
async def _wrapper() -> None:
|
||||
for _ in range(attempts):
|
||||
if await scmd.run(
|
||||
timeout, verbose, log_complete, sig_idx,
|
||||
proc_input, success_codes
|
||||
):
|
||||
break
|
||||
else:
|
||||
ret_code = scmd.get_return_code()
|
||||
raise ShellCommandError(f"Error running command {cmd}", ret_code)
|
||||
return self.eventloop.create_task(_wrapper())
|
||||
|
||||
def exec_cmd(
|
||||
self,
|
||||
cmd: str,
|
||||
timeout: float = 2.,
|
||||
attempts: 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[str]:
|
||||
"""
|
||||
Executes a command and returns UTF-8 decoded stdout upon completion.
|
||||
"""
|
||||
scmd = ShellCommand(self, cmd, None, None, env,
|
||||
log_stderr, cwd)
|
||||
coro = scmd.run_with_response(
|
||||
timeout, attempts, log_complete, sig_idx,
|
||||
proc_input, success_codes
|
||||
)
|
||||
return self.eventloop.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,427 @@
|
||||
# Integration with Spoolman
|
||||
#
|
||||
# Copyright (C) 2023 Daniel Hultgren <daniel.cf.hultgren@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import contextlib
|
||||
import tornado.websocket as tornado_ws
|
||||
from tornado import version_info as tornado_version
|
||||
from ..common import RequestType, HistoryFieldData
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
List,
|
||||
Dict,
|
||||
Any,
|
||||
Optional,
|
||||
Union,
|
||||
cast
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
from .http_client import HttpClient, HttpResponse
|
||||
from .database import MoonrakerDatabase
|
||||
from .announcements import Announcements
|
||||
from .klippy_apis import KlippyAPI as APIComp
|
||||
from .history import History
|
||||
from tornado.websocket import WebSocketClientConnection
|
||||
|
||||
DB_NAMESPACE = "moonraker"
|
||||
ACTIVE_SPOOL_KEY = "spoolman.spool_id"
|
||||
|
||||
class SpoolManager:
|
||||
def __init__(self, config: ConfigHelper):
|
||||
self.server = config.get_server()
|
||||
self.eventloop = self.server.get_event_loop()
|
||||
self._get_spoolman_urls(config)
|
||||
self.sync_rate_seconds = config.getint("sync_rate", default=5, minval=1)
|
||||
self.report_timer = self.eventloop.register_timer(self.report_extrusion)
|
||||
self.pending_reports: Dict[int, float] = {}
|
||||
self.spoolman_ws: Optional[WebSocketClientConnection] = None
|
||||
self.connection_task: Optional[asyncio.Task] = None
|
||||
self.spool_check_task: Optional[asyncio.Task] = None
|
||||
self.ws_connected: bool = False
|
||||
self.reconnect_delay: float = 2.
|
||||
self.is_closing: bool = False
|
||||
self.spool_id: Optional[int] = None
|
||||
self._error_logged: bool = False
|
||||
self._highest_epos: float = 0
|
||||
self._last_epos: float = 0
|
||||
self._current_extruder: str = "extruder"
|
||||
self.spool_history = HistoryFieldData(
|
||||
"spool_ids", "spoolman", "Spool IDs used", "collect",
|
||||
reset_callback=self._on_history_reset
|
||||
)
|
||||
history: History = self.server.lookup_component("history")
|
||||
history.register_auxiliary_field(self.spool_history)
|
||||
self.klippy_apis: APIComp = self.server.lookup_component("klippy_apis")
|
||||
self.http_client: HttpClient = self.server.lookup_component("http_client")
|
||||
self.database: MoonrakerDatabase = self.server.lookup_component("database")
|
||||
announcements: Announcements = self.server.lookup_component("announcements")
|
||||
announcements.register_feed("spoolman")
|
||||
self._register_notifications()
|
||||
self._register_listeners()
|
||||
self._register_endpoints()
|
||||
self.server.register_remote_method(
|
||||
"spoolman_set_active_spool", self.set_active_spool
|
||||
)
|
||||
|
||||
def _get_spoolman_urls(self, config: ConfigHelper) -> None:
|
||||
orig_url = config.get('server')
|
||||
url_match = re.match(r"(?i:(?P<scheme>https?)://)?(?P<host>.+)", orig_url)
|
||||
if url_match is None:
|
||||
raise config.error(
|
||||
f"Section [spoolman], Option server: {orig_url}: Invalid URL format"
|
||||
)
|
||||
scheme = url_match["scheme"] or "http"
|
||||
host = url_match["host"].rstrip("/")
|
||||
ws_scheme = "wss" if scheme == "https" else "ws"
|
||||
self.spoolman_url = f"{scheme}://{host}/api"
|
||||
self.ws_url = f"{ws_scheme}://{host}/api/v1/spool"
|
||||
|
||||
def _register_notifications(self):
|
||||
self.server.register_notification("spoolman:active_spool_set")
|
||||
self.server.register_notification("spoolman:spoolman_status_changed")
|
||||
|
||||
def _register_listeners(self):
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._handle_klippy_ready
|
||||
)
|
||||
|
||||
def _register_endpoints(self):
|
||||
self.server.register_endpoint(
|
||||
"/server/spoolman/spool_id",
|
||||
RequestType.GET | RequestType.POST,
|
||||
self._handle_spool_id_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/spoolman/proxy",
|
||||
RequestType.POST,
|
||||
self._proxy_spoolman_request,
|
||||
)
|
||||
self.server.register_endpoint(
|
||||
"/server/spoolman/status",
|
||||
RequestType.GET,
|
||||
self._handle_status_request,
|
||||
)
|
||||
|
||||
def _on_history_reset(self) -> List[int]:
|
||||
if self.spool_id is None:
|
||||
return []
|
||||
return [self.spool_id]
|
||||
|
||||
async def component_init(self) -> None:
|
||||
self.spool_id = await self.database.get_item(
|
||||
DB_NAMESPACE, ACTIVE_SPOOL_KEY, None
|
||||
)
|
||||
self.connection_task = self.eventloop.create_task(self._connect_websocket())
|
||||
|
||||
async def _connect_websocket(self) -> None:
|
||||
log_connect: bool = True
|
||||
err_list: List[Exception] = []
|
||||
while not self.is_closing:
|
||||
if log_connect:
|
||||
logging.info(f"Connecting To Spoolman: {self.ws_url}")
|
||||
log_connect = False
|
||||
try:
|
||||
self.spoolman_ws = await tornado_ws.websocket_connect(
|
||||
self.ws_url,
|
||||
connect_timeout=5.,
|
||||
ping_interval=None if tornado_version < (6, 5) else 20.
|
||||
)
|
||||
setattr(self.spoolman_ws, "on_ping", self._on_ws_ping)
|
||||
cur_time = self.eventloop.get_loop_time()
|
||||
self._last_ping_received = cur_time
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
if len(err_list) < 10:
|
||||
# Allow up to 10 unique errors.
|
||||
for err in err_list:
|
||||
if type(err) is type(e) and err.args == e.args:
|
||||
break
|
||||
else:
|
||||
err_list.append(e)
|
||||
verbose = self.server.is_verbose_enabled()
|
||||
if verbose:
|
||||
logging.exception("Failed to connect to Spoolman")
|
||||
self.server.add_log_rollover_item(
|
||||
"spoolman_connect", f"Failed to Connect to spoolman: {e}",
|
||||
not verbose
|
||||
)
|
||||
else:
|
||||
err_list = []
|
||||
self.ws_connected = True
|
||||
self._error_logged = False
|
||||
self.report_timer.start()
|
||||
self.server.add_log_rollover_item(
|
||||
"spoolman_connect", "Connected to Spoolman Spool Manager"
|
||||
)
|
||||
if self.spool_id is not None:
|
||||
self._cancel_spool_check_task()
|
||||
coro = self._check_spool_deleted()
|
||||
self.spool_check_task = self.eventloop.create_task(coro)
|
||||
self._send_status_notification()
|
||||
await self._read_messages()
|
||||
log_connect = True
|
||||
if not self.is_closing:
|
||||
await asyncio.sleep(self.reconnect_delay)
|
||||
|
||||
async def _read_messages(self) -> None:
|
||||
message: Union[str, bytes, None]
|
||||
while self.spoolman_ws is not None:
|
||||
message = await self.spoolman_ws.read_message()
|
||||
if isinstance(message, str):
|
||||
self._decode_message(message)
|
||||
elif message is None:
|
||||
self.report_timer.stop()
|
||||
self.ws_connected = False
|
||||
cur_time = self.eventloop.get_loop_time()
|
||||
ping_time: float = cur_time - self._last_ping_received
|
||||
reason = code = None
|
||||
if self.spoolman_ws is not None:
|
||||
reason = self.spoolman_ws.close_reason
|
||||
code = self.spoolman_ws.close_code
|
||||
logging.info(
|
||||
f"Spoolman Disconnected - Code: {code}, Reason: {reason}, "
|
||||
f"Server Ping Time Elapsed: {ping_time}"
|
||||
)
|
||||
self.spoolman_ws = None
|
||||
if not self.is_closing:
|
||||
self._send_status_notification()
|
||||
break
|
||||
|
||||
def _decode_message(self, message: str) -> None:
|
||||
event: Dict[str, Any] = jsonw.loads(message)
|
||||
if event.get("resource") != "spool":
|
||||
return
|
||||
if self.spool_id is not None and event.get("type") == "deleted":
|
||||
payload: Dict[str, Any] = event.get("payload", {})
|
||||
if payload.get("id") == self.spool_id:
|
||||
self.pending_reports.pop(self.spool_id, None)
|
||||
self.set_active_spool(None)
|
||||
|
||||
def _cancel_spool_check_task(self) -> None:
|
||||
if self.spool_check_task is None or self.spool_check_task.done():
|
||||
return
|
||||
self.spool_check_task.cancel()
|
||||
|
||||
async def _check_spool_deleted(self) -> None:
|
||||
if self.spool_id is not None:
|
||||
response = await self.http_client.get(
|
||||
f"{self.spoolman_url}/v1/spool/{self.spool_id}",
|
||||
connect_timeout=1., request_timeout=2.
|
||||
)
|
||||
if response.status_code == 404:
|
||||
logging.info(f"Spool ID {self.spool_id} not found, setting to None")
|
||||
self.pending_reports.pop(self.spool_id, None)
|
||||
self.set_active_spool(None)
|
||||
elif response.has_error():
|
||||
err_msg = self._get_response_error(response)
|
||||
logging.info(f"Attempt to check spool status failed: {err_msg}")
|
||||
else:
|
||||
logging.info(f"Found Spool ID {self.spool_id} on spoolman instance")
|
||||
self.spool_check_task = None
|
||||
|
||||
def connected(self) -> bool:
|
||||
return self.ws_connected
|
||||
|
||||
def _on_ws_ping(self, data: bytes = b"") -> None:
|
||||
self._last_ping_received = self.eventloop.get_loop_time()
|
||||
|
||||
async def _handle_klippy_ready(self) -> None:
|
||||
result: Dict[str, Dict[str, Any]]
|
||||
result = await self.klippy_apis.subscribe_objects(
|
||||
{"toolhead": ["position", "extruder"]}, self._handle_status_update, {}
|
||||
)
|
||||
toolhead = result.get("toolhead", {})
|
||||
self._current_extruder = toolhead.get("extruder", "extruder")
|
||||
initial_e_pos = toolhead.get("position", [None]*4)[3]
|
||||
logging.debug(f"Initial epos: {initial_e_pos}")
|
||||
if initial_e_pos is not None:
|
||||
self._highest_epos = initial_e_pos
|
||||
else:
|
||||
logging.error("Spoolman integration unable to subscribe to epos")
|
||||
raise self.server.error("Unable to subscribe to e position")
|
||||
|
||||
def _get_response_error(self, response: HttpResponse) -> str:
|
||||
err_msg = f"HTTP error: {response.status_code} {response.error}"
|
||||
with contextlib.suppress(Exception):
|
||||
msg: Optional[str] = cast(dict, response.json())["message"]
|
||||
err_msg += f", Spoolman message: {msg}"
|
||||
return err_msg
|
||||
|
||||
def _handle_status_update(self, status: Dict[str, Any], _: float) -> None:
|
||||
toolhead: Optional[Dict[str, Any]] = status.get("toolhead")
|
||||
if toolhead is None:
|
||||
return
|
||||
epos: float = toolhead.get("position", [0, 0, 0, self._highest_epos])[3]
|
||||
self._last_epos = epos
|
||||
extr = toolhead.get("extruder", self._current_extruder)
|
||||
if extr != self._current_extruder:
|
||||
self._highest_epos = epos
|
||||
self._current_extruder = extr
|
||||
elif epos > self._highest_epos:
|
||||
if self.spool_id is not None:
|
||||
self._add_extrusion(self.spool_id, epos - self._highest_epos)
|
||||
self._highest_epos = epos
|
||||
|
||||
def _add_extrusion(self, spool_id: int, used_length: float) -> None:
|
||||
if spool_id in self.pending_reports:
|
||||
self.pending_reports[spool_id] += used_length
|
||||
else:
|
||||
self.pending_reports[spool_id] = used_length
|
||||
|
||||
def set_active_spool(self, spool_id: Union[int, None]) -> None:
|
||||
assert spool_id is None or isinstance(spool_id, int)
|
||||
if self.spool_id == spool_id:
|
||||
logging.info(f"Spool ID already set to: {spool_id}")
|
||||
return
|
||||
self.spool_history.tracker.update(spool_id)
|
||||
self.spool_id = spool_id
|
||||
self.database.insert_item(DB_NAMESPACE, ACTIVE_SPOOL_KEY, spool_id)
|
||||
self._highest_epos = self._last_epos
|
||||
self.server.send_event(
|
||||
"spoolman:active_spool_set", {"spool_id": spool_id}
|
||||
)
|
||||
logging.info(f"Setting active spool to: {spool_id}")
|
||||
|
||||
async def report_extrusion(self, eventtime: float) -> float:
|
||||
if not self.ws_connected:
|
||||
return eventtime + self.sync_rate_seconds
|
||||
pending_reports = self.pending_reports
|
||||
self.pending_reports = {}
|
||||
for spool_id, used_length in pending_reports.items():
|
||||
if not self.ws_connected:
|
||||
self._add_extrusion(spool_id, used_length)
|
||||
continue
|
||||
logging.debug(
|
||||
f"Sending spool usage: ID: {spool_id}, Length: {used_length:.3f}mm"
|
||||
)
|
||||
response = await self.http_client.request(
|
||||
method="PUT",
|
||||
url=f"{self.spoolman_url}/v1/spool/{spool_id}/use",
|
||||
body={"use_length": used_length}
|
||||
)
|
||||
if response.has_error():
|
||||
if response.status_code == 404:
|
||||
# Since the spool is deleted we can remove any pending reports
|
||||
# added while waiting for the request
|
||||
self.pending_reports.pop(spool_id, None)
|
||||
if spool_id == self.spool_id:
|
||||
logging.info(f"Spool ID {spool_id} not found, setting to None")
|
||||
self.set_active_spool(None)
|
||||
else:
|
||||
if not self._error_logged:
|
||||
error_msg = self._get_response_error(response)
|
||||
self._error_logged = True
|
||||
logging.info(
|
||||
f"Failed to update extrusion for spool id {spool_id}, "
|
||||
f"received {error_msg}"
|
||||
)
|
||||
# Add missed reports back to pending reports for the next cycle
|
||||
self._add_extrusion(spool_id, used_length)
|
||||
continue
|
||||
self._error_logged = False
|
||||
return self.eventloop.get_loop_time() + self.sync_rate_seconds
|
||||
|
||||
async def _handle_spool_id_request(self, web_request: WebRequest):
|
||||
if web_request.get_request_type() == RequestType.POST:
|
||||
spool_id = web_request.get_int("spool_id", None)
|
||||
self.set_active_spool(spool_id)
|
||||
# For GET requests we will simply return the spool_id
|
||||
return {"spool_id": self.spool_id}
|
||||
|
||||
async def _proxy_spoolman_request(self, web_request: WebRequest):
|
||||
method = web_request.get_str("request_method")
|
||||
path = web_request.get_str("path")
|
||||
query = web_request.get_str("query", None)
|
||||
body = web_request.get("body", None)
|
||||
use_v2_response = web_request.get_boolean("use_v2_response", False)
|
||||
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:
|
||||
raise self.server.error(f"Invalid HTTP method: {method}")
|
||||
if body is not None and method == "GET":
|
||||
raise self.server.error("GET requests cannot have a body")
|
||||
if len(path) < 4 or path[:4] != "/v1/":
|
||||
raise self.server.error(
|
||||
"Invalid path, must start with the API version, e.g. /v1"
|
||||
)
|
||||
query = f"?{query}" if query is not None else ""
|
||||
full_url = f"{self.spoolman_url}{path}{query}"
|
||||
if not self.ws_connected:
|
||||
if not use_v2_response:
|
||||
raise self.server.error("Spoolman server not available", 503)
|
||||
return {
|
||||
"response": None,
|
||||
"error": {
|
||||
"status_code": 503,
|
||||
"message": "Spoolman server not available"
|
||||
}
|
||||
}
|
||||
logging.debug(f"Proxying {method} request to {full_url}")
|
||||
response = await self.http_client.request(
|
||||
method=method,
|
||||
url=full_url,
|
||||
body=body,
|
||||
)
|
||||
if not use_v2_response:
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
if response.has_error():
|
||||
msg: str = str(response.error or "")
|
||||
with contextlib.suppress(Exception):
|
||||
spoolman_msg = cast(dict, response.json()).get("message", msg)
|
||||
msg = spoolman_msg
|
||||
return {
|
||||
"response": None,
|
||||
"error": {
|
||||
"status_code": response.status_code,
|
||||
"message": msg
|
||||
}
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"response": response.json(),
|
||||
"response_headers": dict(response.headers.items()),
|
||||
"error": None
|
||||
}
|
||||
|
||||
async def _handle_status_request(self, web_request: WebRequest) -> Dict[str, Any]:
|
||||
pending: List[Dict[str, Any]] = [
|
||||
{"spool_id": sid, "filament_used": used} for sid, used in
|
||||
self.pending_reports.items()
|
||||
]
|
||||
return {
|
||||
"spoolman_connected": self.ws_connected,
|
||||
"pending_reports": pending,
|
||||
"spool_id": self.spool_id
|
||||
}
|
||||
|
||||
def _send_status_notification(self) -> None:
|
||||
self.server.send_event(
|
||||
"spoolman:spoolman_status_changed",
|
||||
{"spoolman_connected": self.ws_connected}
|
||||
)
|
||||
|
||||
async def close(self):
|
||||
self.is_closing = True
|
||||
self.report_timer.stop()
|
||||
if self.spoolman_ws is not None:
|
||||
self.spoolman_ws.close(1001, "Moonraker Shutdown")
|
||||
self._cancel_spool_check_task()
|
||||
if self.connection_task is None or self.connection_task.done():
|
||||
return
|
||||
try:
|
||||
await asyncio.wait_for(self.connection_task, 2.)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
def load_component(config: ConfigHelper) -> SpoolManager:
|
||||
return SpoolManager(config)
|
||||
@@ -0,0 +1,309 @@
|
||||
# Support for interfacing with TD-1 devices to assist in filament changers grabbing TD
|
||||
# and color for all filament loaded.
|
||||
#
|
||||
# Copyright (C) 2025 AJAX3D and Jim Madill <jcmadill1@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
import logging
|
||||
import datetime
|
||||
import contextlib
|
||||
from ..utils import async_serial
|
||||
from ..common import RequestType
|
||||
from typing import Optional, Dict, List, Tuple, Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..confighelper import ConfigHelper
|
||||
from ..common import WebRequest
|
||||
|
||||
|
||||
class TD1Connection:
|
||||
def __init__(
|
||||
self,
|
||||
config: ConfigHelper,
|
||||
serial_number: str,
|
||||
port: str,
|
||||
logger: logging.Logger
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.server = config.get_server()
|
||||
self.port = port
|
||||
self.serial_number = serial_number
|
||||
self.baudrate = config.getint("baudrate", 115200)
|
||||
self.name = f"{config.get_name()}-{self.serial_number}"
|
||||
self.logger = logger
|
||||
self.error_state: bool = False
|
||||
self.enabled: bool = True
|
||||
self.serial = async_serial.AsyncSerialConnection(
|
||||
self.server, self.name, self.port, self.baudrate
|
||||
)
|
||||
self.serial_task: asyncio.Task
|
||||
# Values to return back for td1_data endpoint
|
||||
self._td: Optional[float] = None
|
||||
self._color: Optional[str] = None
|
||||
self._scan_time: str = datetime.datetime.now(
|
||||
tz=datetime.timezone.utc
|
||||
).isoformat() + "Z"
|
||||
self._error: Optional[str] = None
|
||||
self.done_initializing: bool = False
|
||||
|
||||
async def initialize(self) -> None:
|
||||
self.serial_task = self.server.get_event_loop().create_task(self.run_serial())
|
||||
for _ in range(5):
|
||||
await asyncio.sleep(.01)
|
||||
if self.serial.connected:
|
||||
break
|
||||
|
||||
async def readline_with_timeout(self, timeout: float = 5.) -> Optional[bytes]:
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
return await asyncio.wait_for(self.serial.reader.readline(), timeout)
|
||||
return None
|
||||
|
||||
async def run_serial(self) -> None:
|
||||
try:
|
||||
self.serial.open()
|
||||
except (self.serial.error, OSError):
|
||||
self.error_state = True
|
||||
self.logger.exception(
|
||||
f"Error trying to open TD1 serial: {self.serial_number}"
|
||||
)
|
||||
return
|
||||
await self.check_error_file()
|
||||
self.done_initializing = True
|
||||
async for read_line in self.serial.reader:
|
||||
line = read_line.decode("utf-8").rstrip()
|
||||
self._parse_line(line)
|
||||
self.logger.debug(f"{self.serial_number}: {line}")
|
||||
|
||||
def _parse_line(self, line: str) -> None:
|
||||
try:
|
||||
parts = line.split(",")
|
||||
if len(parts) >= 6:
|
||||
self._td = float(parts[4])
|
||||
self._color = parts[5].strip()
|
||||
self._scan_time = datetime.datetime.now(
|
||||
tz=datetime.timezone.utc
|
||||
).isoformat() + "Z"
|
||||
except Exception as e:
|
||||
self.logger.error(f"Parse error from {self.serial_number}: {e}")
|
||||
|
||||
async def check_error_file(self) -> None:
|
||||
"""
|
||||
Requests error file from TD1
|
||||
|
||||
:return: Returns empty string if no error.txt file exists, returns error.txt
|
||||
content if it exists so error can be displayed to user.
|
||||
"""
|
||||
file_name = "errors.txt"
|
||||
# Wait for acknowledgment from the Raspberry Pi Pico
|
||||
ack = None
|
||||
while ack != 'ready' and ack != 'No file named errors.txt' and self.enabled:
|
||||
# Send the file request command
|
||||
if ack is None:
|
||||
self.logger.debug(f"{self.serial_number}: Sending retrieve file")
|
||||
await self.serial.send(b'retrieve file\n')
|
||||
await self.serial.send(f"{file_name}\n".encode('utf-8'))
|
||||
line = await self.readline_with_timeout()
|
||||
if line is not None:
|
||||
ack = line.decode('utf-8').strip()
|
||||
self.logger.debug(f"{self.serial_number}: {ack}")
|
||||
else:
|
||||
self.logger.debug(f"{self.serial_number}: Timed out")
|
||||
ack = None
|
||||
self.logger.debug(f"{self.serial_number}: Done checking for error file")
|
||||
if ack == 'No file named errors.txt':
|
||||
return
|
||||
# Receive file size and block count
|
||||
data = await self.serial.reader.readline()
|
||||
file_size = int(data.decode('utf-8').strip())
|
||||
data = await self.serial.reader.readline()
|
||||
blk_count = int(data.decode('utf-8').strip())
|
||||
self.logger.debug(
|
||||
f"Receiving file: {file_name}, Size: {file_size} bytes, Blocks: {blk_count}"
|
||||
)
|
||||
block_content = ''
|
||||
for _ in range(blk_count):
|
||||
# Receive a block size
|
||||
data = await self.serial.reader.readuntil(b'\n')
|
||||
# Receive the block content
|
||||
data = await self.serial.reader.readuntil(b'\n')
|
||||
block_content += data.decode()
|
||||
# Send acknowledgment to the Raspberry Pi Pico
|
||||
await self.serial.send(b'ready\n')
|
||||
self.logger.info(
|
||||
f"{self.serial_number}: Error file content: {block_content}"
|
||||
)
|
||||
self.logger.info(
|
||||
f"{self.serial_number}: File '{file_name}' received successfully."
|
||||
)
|
||||
self._error = block_content
|
||||
|
||||
async def close(self) -> None:
|
||||
self.enabled = False
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self.serial.close(), 1)
|
||||
if hasattr(self, "serial_task") and not self.serial_task.done():
|
||||
with contextlib.suppress(asyncio.CancelledError, asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self.serial_task, 1)
|
||||
|
||||
async def reboot(self) -> None:
|
||||
self.logger.info(f"Rebooting {self.serial_number}")
|
||||
self.enabled = False
|
||||
self.serial.set_read_callback(None, force=True)
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self.serial_task, 1.)
|
||||
await self.serial.send('change settings\n'.encode('utf-8'))
|
||||
ack = await self.serial.reader.readuntil(b'\n')
|
||||
ack_str = ack.decode('utf-8').strip()
|
||||
if ack_str == 'ready':
|
||||
await self.serial.send(b'RGB_Enabled = True\ndone\n')
|
||||
ack = await self.serial.reader.readuntil(b'\n')
|
||||
ack_str = ack.decode('utf-8').strip()
|
||||
|
||||
def get_data(self) -> Dict[str, Dict[str, Any]]:
|
||||
if not self.done_initializing:
|
||||
# Return empty dictionary until check_error_file has compeleted
|
||||
return {}
|
||||
return {
|
||||
self.serial_number: {
|
||||
"td": self._td,
|
||||
"color": self._color,
|
||||
"scan_time": self._scan_time,
|
||||
"error": self._error
|
||||
}
|
||||
}
|
||||
|
||||
class TD1:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self._config = config
|
||||
self._loop = self.server.get_event_loop()
|
||||
self.logger = logging.getLogger("td1")
|
||||
self._server = config.get_server()
|
||||
self._vid: int = 0xE4B2
|
||||
self._pid: int = 0x0045
|
||||
self._enabled: bool = True
|
||||
self._watch_task: Optional[asyncio.Task] = None
|
||||
self._start_task: Optional[asyncio.Task] = None
|
||||
self.td1_conns: Dict[str, TD1Connection] = {}
|
||||
self._register_endpoints()
|
||||
|
||||
def _register_endpoints(self) -> None:
|
||||
self._server.register_endpoint(
|
||||
"/machine/td1/data", RequestType.GET, self._handle_get_data
|
||||
)
|
||||
self._server.register_endpoint(
|
||||
"/machine/td1/reboot", RequestType.POST, self._handle_reboot
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
# Stop watching for new devices
|
||||
self._enabled = False
|
||||
if self._start_task is not None:
|
||||
with contextlib.suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self._start_task, 1.)
|
||||
if self._watch_task is not None:
|
||||
self._watch_task.cancel()
|
||||
with contextlib.suppress(asyncio.TimeoutError, asyncio.CancelledError):
|
||||
await asyncio.wait_for(self._watch_task, 1.)
|
||||
for td1 in self.td1_conns.values():
|
||||
await td1.close()
|
||||
|
||||
async def component_init(self) -> None:
|
||||
self.logger.debug("Initializing TD1")
|
||||
self._start_task = self._loop.create_task(self._start_all_serial_tasks())
|
||||
self._watch_task = self._loop.create_task(self._watch_for_new_devices())
|
||||
|
||||
async def _start_all_serial_tasks(self) -> None:
|
||||
devices = self._find_td1_devices()
|
||||
if not devices:
|
||||
self.logger.warning("No TD1 devices found.")
|
||||
return
|
||||
for port, serial_number in devices:
|
||||
await self._start_serial_task(port, serial_number)
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
async def _watch_for_new_devices(self) -> None:
|
||||
while self._enabled:
|
||||
await asyncio.sleep(5.) # Scan every 5 seconds
|
||||
# Find currently connected devices
|
||||
current_serials: set[str] = set()
|
||||
for port, serial_number in self._find_td1_devices():
|
||||
current_serials.add(serial_number)
|
||||
if serial_number not in self.td1_conns:
|
||||
self.logger.info(f"Hot-plugged TD1 detected: {serial_number}")
|
||||
try:
|
||||
await self._start_serial_task(port, serial_number)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
continue
|
||||
# Detect disconnected devices
|
||||
known_serials = set(self.td1_conns.keys())
|
||||
disconnected_serials = known_serials - current_serials
|
||||
self.logger.debug(
|
||||
f"Disconnected: {disconnected_serials}, All: {known_serials}"
|
||||
)
|
||||
for serial_number in disconnected_serials:
|
||||
conn = self.td1_conns.pop(serial_number, None)
|
||||
if conn is not None:
|
||||
await conn.close()
|
||||
|
||||
def _find_td1_devices(self) -> List[Tuple[str, str]]:
|
||||
found: List[Tuple[str, str]] = []
|
||||
for port in serial.tools.list_ports.comports():
|
||||
if port.vid == self._vid and port.pid == self._pid:
|
||||
if port.serial_number:
|
||||
found.append((port.device, port.serial_number))
|
||||
return found
|
||||
|
||||
async def _start_serial_task(self, port: str, serial_number: str) -> None:
|
||||
try:
|
||||
conn = TD1Connection(self._config, serial_number, port, self.logger)
|
||||
await conn.initialize()
|
||||
if not conn.error_state:
|
||||
self.td1_conns[serial_number] = conn
|
||||
self.logger.info(f"TD1 listening on {port} (Serial: {serial_number})")
|
||||
else:
|
||||
self.logger.error(
|
||||
f"Failed to open port:{port} for TD1 serial {serial_number}")
|
||||
except serial.SerialException as e:
|
||||
self.logger.error(f"Failed to open serial port {port}: {e}")
|
||||
raise
|
||||
except asyncio.CancelledError as e:
|
||||
self.logger.error(f"Task canceled error {e}")
|
||||
raise
|
||||
|
||||
async def _handle_get_data(self, web_request: WebRequest) -> Dict[str, Any]:
|
||||
latest_data: Dict[str, Any] = {}
|
||||
for task in self.td1_conns.values():
|
||||
latest_data.update(task.get_data())
|
||||
return {
|
||||
"status": "ok",
|
||||
"devices": latest_data
|
||||
}
|
||||
|
||||
async def _handle_reboot(self, web_request: WebRequest) -> Dict[str, str]:
|
||||
"""
|
||||
Reboots TD1 device by serial when requested
|
||||
"""
|
||||
serial_number = web_request.get_str("serial")
|
||||
req_conn = self.td1_conns.get(serial_number, None)
|
||||
if req_conn is None:
|
||||
return {
|
||||
"status": "serial_error"
|
||||
}
|
||||
await req_conn.reboot()
|
||||
await req_conn.close()
|
||||
# Remove serial number from entries if they exist
|
||||
self.td1_conns.pop(serial_number, None)
|
||||
return {
|
||||
"status": "ok"
|
||||
}
|
||||
|
||||
def load_component(config: ConfigHelper) -> TD1:
|
||||
return TD1(config)
|
||||
@@ -0,0 +1,113 @@
|
||||
# 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
|
||||
from ..utils import json_wrapper as jsonw
|
||||
from ..common import RenderableTemplate
|
||||
|
||||
# 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'] = jsonw.loads
|
||||
self.async_env.add_extension("jinja2.ext.do")
|
||||
self.async_env.filters['fromjson'] = jsonw.loads
|
||||
self.ui_env.add_extension("jinja2.ext.do")
|
||||
self.ui_env.filters['fromjson'] = jsonw.loads
|
||||
self.add_environment_global("raise_error", self._raise_error)
|
||||
self.add_environment_global("secrets", secrets)
|
||||
self.add_environment_global("log_debug", logging.debug)
|
||||
|
||||
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(RenderableTemplate):
|
||||
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,470 @@
|
||||
# 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 hashlib
|
||||
import logging
|
||||
import re
|
||||
import asyncio
|
||||
import importlib
|
||||
from datetime import datetime, timezone
|
||||
from .common import AppType, Channel
|
||||
from .base_deploy import BaseDeploy
|
||||
from ...utils import pip_utils
|
||||
from ...utils import json_wrapper as jsonw
|
||||
from ...utils.sysdeps_parser import SysDepsParser
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from ..klippy_connection import KlippyConnection as Klippy
|
||||
from ..machine import Machine
|
||||
from ..file_manager.file_manager import FileManager
|
||||
|
||||
PIPVER_CHECK_DAYS = 30
|
||||
|
||||
class AppDeploy(BaseDeploy):
|
||||
def __init__(self, config: ConfigHelper, prefix: str) -> None:
|
||||
super().__init__(config, prefix=prefix)
|
||||
self.config = config
|
||||
type_choices = {str(t): t for t in AppType.valid_types()}
|
||||
self.type = config.getchoice("type", type_choices)
|
||||
channel_choices = {str(chnl): chnl for chnl in list(Channel)}
|
||||
self.channel = config.getchoice(
|
||||
"channel", channel_choices, str(self.type.default_channel)
|
||||
)
|
||||
self.channel_invalid: bool = False
|
||||
if self.channel not in self.type.supported_channels:
|
||||
str_channels = [str(c) for c in self.type.supported_channels]
|
||||
self.channel_invalid = True
|
||||
invalid_channel = self.channel
|
||||
self.channel = self.type.default_channel
|
||||
self.server.add_warning(
|
||||
f"[{config.get_name()}]: Invalid value '{invalid_channel}' for "
|
||||
f"option 'channel'. Type '{self.type}' supports the following "
|
||||
f"channels: {str_channels}. Falling back to channel '{self.channel}'"
|
||||
)
|
||||
self.report_anomalies = config.getboolean("report_anomalies", True)
|
||||
self._is_valid: bool = False
|
||||
self.virtualenv: Optional[pathlib.Path] = None
|
||||
self.py_exec: Optional[pathlib.Path] = None
|
||||
self.pip_cmd: Optional[str] = None
|
||||
self.pip_version_info: pip_utils.PipVersionInfo | None = None
|
||||
self.pip_ver_date: datetime = datetime.fromtimestamp(0., timezone.utc)
|
||||
self.venv_args: Optional[str] = None
|
||||
self.npm_pkg_json: Optional[pathlib.Path] = None
|
||||
self.python_reqs: Optional[pathlib.Path] = None
|
||||
self.install_script: Optional[pathlib.Path] = None
|
||||
self.system_deps_json: Optional[pathlib.Path] = None
|
||||
self.info_tags: List[str] = config.getlist("info_tags", [])
|
||||
self.managed_services: List[str] = []
|
||||
|
||||
def _configure_path(self, config: ConfigHelper, reserve: bool = True) -> None:
|
||||
self.path = pathlib.Path(config.get('path')).expanduser().resolve()
|
||||
self._verify_path(config, 'path', self.path, check_file=False)
|
||||
if (
|
||||
reserve and 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)
|
||||
|
||||
def _configure_virtualenv(self, config: ConfigHelper) -> None:
|
||||
venv_path: Optional[pathlib.Path] = None
|
||||
if config.has_option("virtualenv"):
|
||||
venv_path = pathlib.Path(config.get("virtualenv")).expanduser()
|
||||
if not venv_path.is_absolute():
|
||||
venv_path = self.path.joinpath(venv_path)
|
||||
self._verify_path(config, 'virtualenv', venv_path, check_file=False)
|
||||
elif config.has_option("env"):
|
||||
# Deprecated
|
||||
if self.name != "klipper":
|
||||
self.log_info("Option 'env' is deprecated, use 'virtualenv' instead.")
|
||||
py_exec = pathlib.Path(config.get("env")).expanduser()
|
||||
self._verify_path(config, 'env', py_exec, check_exe=True)
|
||||
venv_path = py_exec.expanduser().parent.parent.resolve()
|
||||
if venv_path is not None:
|
||||
act_path = venv_path.joinpath("bin/activate")
|
||||
if not act_path.is_file():
|
||||
raise config.error(
|
||||
f"[{config.get_name()}]: Invalid virtualenv at path {venv_path}. "
|
||||
f"Verify that the 'virtualenv' option is set to a valid "
|
||||
"virtualenv path."
|
||||
)
|
||||
self.py_exec = venv_path.joinpath("bin/python")
|
||||
if not (self.py_exec.is_file() and os.access(self.py_exec, os.X_OK)):
|
||||
raise config.error(
|
||||
f"[{config.get_name()}]: Invalid python executable at "
|
||||
f"{self.py_exec}. Verify that the 'virtualenv' option is set "
|
||||
"to a valid virtualenv path."
|
||||
)
|
||||
self.log_info(f"Detected virtualenv: {venv_path}")
|
||||
self.virtualenv = venv_path
|
||||
pip_exe = self.virtualenv.joinpath("bin/pip")
|
||||
if pip_exe.is_file():
|
||||
self.pip_cmd = f"{self.py_exec} -m pip"
|
||||
else:
|
||||
self.log_info("Unable to locate pip executable")
|
||||
self.venv_args = config.get('venv_args', None)
|
||||
self.pip_env_vars = config.getdict("pip_environment_variables", None)
|
||||
|
||||
def _configure_dependencies(
|
||||
self, config: ConfigHelper, node_only: bool = False
|
||||
) -> 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)
|
||||
if node_only:
|
||||
return
|
||||
if self.py_exec is not None:
|
||||
self.python_reqs = self.path.joinpath(config.get("requirements"))
|
||||
self._verify_path(config, 'requirements', self.python_reqs)
|
||||
if not self._configure_sysdeps(config):
|
||||
# Fall back on deprecated "install_script" option if dependencies file
|
||||
# not present
|
||||
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)
|
||||
|
||||
def _configure_sysdeps(self, config: ConfigHelper) -> bool:
|
||||
deps = config.get("system_dependencies", None)
|
||||
if deps is not None:
|
||||
self.system_deps_json = self.path.joinpath(deps).resolve()
|
||||
self._verify_path(config, 'system_dependencies', self.system_deps_json)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _configure_managed_services(self, config: ConfigHelper) -> None:
|
||||
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
|
||||
)
|
||||
if self.name in services:
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
data_path: str = self.server.get_app_args()["data_path"]
|
||||
asvc = pathlib.Path(data_path).joinpath("moonraker.asvc")
|
||||
if not machine.is_service_allowed(self.name):
|
||||
self.server.add_warning(
|
||||
f"[{config.get_name()}]: Moonraker is not permitted to "
|
||||
f"restart service '{self.name}'. To enable management "
|
||||
f"of this service add {self.name} to the bottom of the "
|
||||
f"file {asvc}. To disable management for this service "
|
||||
"set 'is_system_service: False' in the configuration "
|
||||
"for this section."
|
||||
)
|
||||
services.clear()
|
||||
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)
|
||||
self.log_debug(
|
||||
f"Managed services: {self.managed_services}"
|
||||
)
|
||||
|
||||
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")
|
||||
|
||||
async def initialize(self) -> Dict[str, Any]:
|
||||
storage = await super().initialize()
|
||||
pv_info: List[Any] | None = storage.get("pip_version_info", None)
|
||||
if pv_info is not None:
|
||||
self.pip_version_info = pip_utils.PipVersionInfo(*pv_info[:2])
|
||||
self.pip_ver_date = datetime.fromtimestamp(pv_info[2], timezone.utc)
|
||||
self.log_info(
|
||||
f"Pip Version: {pv_info[0]}, Python Version: {pv_info[1]}\n"
|
||||
f"Last checked on {self.pip_ver_date}"
|
||||
)
|
||||
return storage
|
||||
|
||||
def get_configured_type(self) -> AppType:
|
||||
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.py_exec is None:
|
||||
return False
|
||||
try:
|
||||
return (
|
||||
self.path.samefile(app_path) and
|
||||
self.py_exec.samefile(executable)
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def restart_service(self) -> None:
|
||||
if not self.managed_services:
|
||||
return
|
||||
machine: Machine = self.server.lookup_component("machine")
|
||||
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
|
||||
machine.restart_moonraker_service()
|
||||
else:
|
||||
if svc == "klipper":
|
||||
kconn: Klippy = self.server.lookup_component("klippy_connection")
|
||||
svc = kconn.unit_name
|
||||
await machine.do_service_action("restart", svc)
|
||||
|
||||
async def _read_system_dependencies(self) -> List[str]:
|
||||
eventloop = self.server.get_event_loop()
|
||||
if self.system_deps_json is not None:
|
||||
deps_json = self.system_deps_json
|
||||
try:
|
||||
ret = await eventloop.run_in_thread(deps_json.read_bytes)
|
||||
dep_info: Dict[str, List[str]] = jsonw.loads(ret)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception(f"Error reading system deps: {deps_json}")
|
||||
return []
|
||||
parser = SysDepsParser()
|
||||
return parser.parse_dependencies(dep_info)
|
||||
# Fall back on install script if configured
|
||||
if self.install_script is None:
|
||||
return []
|
||||
# Open install file file and read
|
||||
inst_path: pathlib.Path = self.install_script
|
||||
if not inst_path.is_file():
|
||||
self.log_info(f"Failed to open install script: {inst_path}")
|
||||
return []
|
||||
try:
|
||||
data = await eventloop.run_in_thread(inst_path.read_text)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logging.exception(f"Error reading install script: {inst_path}")
|
||||
return []
|
||||
plines: List[str] = re.findall(r'PKGLIST="(.*)"', data)
|
||||
plines = [p.lstrip("${PKGLIST}").strip() for p in plines]
|
||||
packages: List[str] = []
|
||||
for line in plines:
|
||||
packages.extend(line.split())
|
||||
if not packages:
|
||||
self.log_info(f"No packages found in script: {inst_path}")
|
||||
return packages
|
||||
|
||||
async def _read_python_reqs(self) -> List[str]:
|
||||
if self.python_reqs is None:
|
||||
return []
|
||||
pyreqs = self.python_reqs
|
||||
if not pyreqs.is_file():
|
||||
self.log_info(f"Failed to open python requirements file: {pyreqs}")
|
||||
return []
|
||||
eventloop = self.server.get_event_loop()
|
||||
return await eventloop.run_in_thread(
|
||||
pip_utils.read_requirements_file, self.python_reqs
|
||||
)
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'channel': str(self.channel),
|
||||
'debug_enabled': self.server.is_debug_enabled(),
|
||||
'channel_invalid': self.channel_invalid,
|
||||
'is_valid': self._is_valid,
|
||||
'configured_type': str(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
|
||||
pv_info = None
|
||||
if self.pip_version_info is not None:
|
||||
pv_info = [
|
||||
self.pip_version_info.pip_version_string,
|
||||
self.pip_version_info.python_version_string,
|
||||
self.pip_ver_date.timestamp()
|
||||
]
|
||||
storage['pip_version_info'] = pv_info
|
||||
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
|
||||
if self.name == "moonraker":
|
||||
importlib.reload(pip_utils)
|
||||
pip_exec = pip_utils.AsyncPipExecutor(
|
||||
self.pip_cmd, self.server, self.cmd_helper.notify_update_response
|
||||
)
|
||||
# Check and update the pip version
|
||||
await self._update_pip(pip_exec)
|
||||
self.notify_status("Updating python packages...")
|
||||
try:
|
||||
await pip_exec.install_packages(requirements, self.pip_env_vars)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
self.log_exc("Error updating python requirements")
|
||||
|
||||
async def _update_pip(self, pip_exec: pip_utils.AsyncPipExecutor) -> None:
|
||||
self.notify_status("Checking pip version...")
|
||||
check_time = datetime.now(timezone.utc) - self.pip_ver_date
|
||||
if self.pip_version_info is None or check_time.days > PIPVER_CHECK_DAYS:
|
||||
self.pip_version_info = await pip_exec.get_pip_version()
|
||||
self.pip_ver_date = datetime.now(timezone.utc)
|
||||
try:
|
||||
if self.pip_version_info.needs_pip_update:
|
||||
cur_ver = self.pip_version_info.pip_version_string
|
||||
update_ver = self.pip_version_info.max_pip_version_string
|
||||
self.notify_status(
|
||||
f"Updating pip from version {cur_ver} to {update_ver}..."
|
||||
)
|
||||
await pip_exec.update_pip()
|
||||
self.pip_version_info = await pip_exec.get_pip_version()
|
||||
self.pip_ver_date = datetime.now(timezone.utc)
|
||||
else:
|
||||
self.notify_status("Pip version up to date")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
self.notify_status(f"Pip Version Check Error: {e}")
|
||||
self.log_exc("Pip Version Check Error")
|
||||
|
||||
async def _collect_dependency_info(self) -> Dict[str, Any]:
|
||||
pkg_deps = await self._read_system_dependencies()
|
||||
pyreqs = await self._read_python_reqs()
|
||||
npm_hash = await self._get_file_hash(self.npm_pkg_json)
|
||||
logging.debug(
|
||||
f"\nApplication {self.name}: Pre-update dependencies:\n"
|
||||
f"Packages: {pkg_deps}\n"
|
||||
f"Python Requirements: {pyreqs}"
|
||||
)
|
||||
return {
|
||||
"system_packages": pkg_deps,
|
||||
"python_modules": pyreqs,
|
||||
"npm_hash": npm_hash
|
||||
}
|
||||
|
||||
async def _update_dependencies(
|
||||
self, dep_info: Dict[str, Any], force: bool = False
|
||||
) -> None:
|
||||
packages = await self._read_system_dependencies()
|
||||
modules = await self._read_python_reqs()
|
||||
logging.debug(
|
||||
f"\nApplication {self.name}: Post-update dependencies:\n"
|
||||
f"Packages: {packages}\n"
|
||||
f"Python Requirements: {modules}"
|
||||
)
|
||||
if not force:
|
||||
packages = list(set(packages) - set(dep_info["system_packages"]))
|
||||
modules = list(set(modules) - set(dep_info["python_modules"]))
|
||||
logging.debug(
|
||||
f"\nApplication {self.name}: Dependencies to install:\n"
|
||||
f"Packages: {packages}\n"
|
||||
f"Python Requirements: {modules}\n"
|
||||
f"Force All: {force}"
|
||||
)
|
||||
if packages:
|
||||
await self._install_packages(packages)
|
||||
if modules:
|
||||
await self._update_python_requirements(self.python_reqs or modules)
|
||||
npm_hash: Optional[str] = dep_info["npm_hash"]
|
||||
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")
|
||||
@@ -0,0 +1,119 @@
|
||||
# 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 ...utils import pretty_print_time
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any, Optional, Coroutine
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from ...utils import ServerError
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
class BaseDeploy:
|
||||
cmd_helper: CommandHelper
|
||||
def __init__(
|
||||
self,
|
||||
config: ConfigHelper,
|
||||
name: Optional[str] = None,
|
||||
prefix: str = "",
|
||||
cfg_hash: Optional[str] = None
|
||||
) -> None:
|
||||
if name is None:
|
||||
name = self.parse_name(config)
|
||||
self.name = name
|
||||
if prefix:
|
||||
prefix = f"{prefix} {self.name}: "
|
||||
self.prefix = prefix
|
||||
self.server = config.get_server()
|
||||
self.refresh_interval = self.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
|
||||
|
||||
@staticmethod
|
||||
def parse_name(config: ConfigHelper) -> str:
|
||||
name = config.get_name().split(maxsplit=1)[-1]
|
||||
if name.startswith("client "):
|
||||
# allow deprecated [update_manager client app] style names
|
||||
name = name[7:]
|
||||
return name
|
||||
|
||||
@staticmethod
|
||||
def set_command_helper(cmd_helper: CommandHelper) -> None:
|
||||
BaseDeploy.cmd_helper = cmd_helper
|
||||
|
||||
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, log_remaining_time: bool = False) -> bool:
|
||||
next_refresh_time = self.last_refresh_time + self.refresh_interval
|
||||
remaining_time = int(next_refresh_time - time.time() + .5)
|
||||
if self.cfg_hash != self.last_cfg_hash or remaining_time <= 0:
|
||||
return True
|
||||
if log_remaining_time:
|
||||
self.log_info(f"Next refresh in: {pretty_print_time(remaining_time)}")
|
||||
return False
|
||||
|
||||
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
|
||||
|
||||
async def rollback(self) -> bool:
|
||||
raise self.server.error(f"Rollback not available for {self.name}")
|
||||
|
||||
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 log_debug(self, msg: str) -> None:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
logging.debug(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)
|
||||
|
||||
def close(self) -> Optional[Coroutine]:
|
||||
return None
|
||||
@@ -0,0 +1,113 @@
|
||||
# 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 sys
|
||||
import copy
|
||||
import pathlib
|
||||
from ...common import ExtendedEnum
|
||||
from ...utils import source_info
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Dict,
|
||||
Union,
|
||||
List
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ...confighelper import ConfigHelper
|
||||
from ..klippy_connection import KlippyConnection
|
||||
|
||||
BASE_CONFIG: Dict[str, Dict[str, str]] = {
|
||||
"moonraker": {
|
||||
"origin": "https://github.com/arksine/moonraker.git",
|
||||
"requirements": "scripts/moonraker-requirements.txt",
|
||||
"venv_args": "-p python3",
|
||||
"system_dependencies": "scripts/system-dependencies.json",
|
||||
"virtualenv": sys.exec_prefix,
|
||||
"pip_environment_variables": "SKIP_CYTHON=Y",
|
||||
"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 python3",
|
||||
"install_script": "scripts/install-octopi.sh",
|
||||
"managed_services": "klipper"
|
||||
}
|
||||
}
|
||||
|
||||
OPTION_OVERRIDES = ("channel", "pinned_commit", "refresh_interval", "report_anomalies")
|
||||
|
||||
class AppType(ExtendedEnum):
|
||||
NONE = 1
|
||||
WEB = 2
|
||||
GIT_REPO = 3
|
||||
ZIP = 4
|
||||
PYTHON = 5
|
||||
EXECUTABLE = 6
|
||||
|
||||
@classmethod
|
||||
def detect(cls, app_path: Union[str, pathlib.Path, None] = None):
|
||||
# If app path is None, detect Moonraker
|
||||
if isinstance(app_path, str):
|
||||
app_path = pathlib.Path(app_path).expanduser()
|
||||
if source_info.is_git_repo(app_path):
|
||||
return AppType.GIT_REPO
|
||||
elif app_path is None and source_info.is_vitualenv_project():
|
||||
return AppType.PYTHON
|
||||
else:
|
||||
return AppType.NONE
|
||||
|
||||
@classmethod
|
||||
def valid_types(cls) -> List[AppType]:
|
||||
all_types = list(cls)
|
||||
all_types.remove(AppType.NONE)
|
||||
return all_types
|
||||
|
||||
@property
|
||||
def supported_channels(self) -> List[Channel]:
|
||||
if self == AppType.NONE:
|
||||
return []
|
||||
elif self in [AppType.WEB, AppType.ZIP, AppType.EXECUTABLE]:
|
||||
return [Channel.STABLE, Channel.BETA] # type: ignore
|
||||
else:
|
||||
return list(Channel)
|
||||
|
||||
@property
|
||||
def default_channel(self) -> Channel:
|
||||
if self == AppType.GIT_REPO:
|
||||
return Channel.DEV # type: ignore
|
||||
return Channel.STABLE # type: ignore
|
||||
|
||||
class Channel(ExtendedEnum):
|
||||
STABLE = 1
|
||||
BETA = 2
|
||||
DEV = 3
|
||||
|
||||
def get_base_configuration(config: ConfigHelper) -> ConfigHelper:
|
||||
server = config.get_server()
|
||||
base_cfg = copy.deepcopy(BASE_CONFIG)
|
||||
kconn: KlippyConnection = server.lookup_component("klippy_connection")
|
||||
base_cfg["moonraker"]["type"] = str(AppType.detect())
|
||||
base_cfg["klipper"]["path"] = str(kconn.path)
|
||||
base_cfg["klipper"]["env"] = str(kconn.executable)
|
||||
base_cfg["klipper"]["type"] = str(AppType.detect(kconn.path))
|
||||
default_channel = config.get("channel", None)
|
||||
# Check for configuration overrides
|
||||
for app_name in base_cfg.keys():
|
||||
if default_channel is not None:
|
||||
base_cfg[app_name]["channel"] = default_channel
|
||||
override_section = f"update_manager {app_name}"
|
||||
if not config.has_section(override_section):
|
||||
continue
|
||||
app_cfg = config[override_section]
|
||||
for opt in OPTION_OVERRIDES:
|
||||
if app_cfg.has_option(opt):
|
||||
base_cfg[app_name][opt] = app_cfg.get(opt)
|
||||
return config.read_supplemental_dict(base_cfg)
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user