Compare commits
583
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf69c4500d | ||
|
|
c7c6a08748 | ||
|
|
c9c4066331 | ||
|
|
835b973bdc | ||
|
|
bf6a32907c | ||
|
|
2b7885c3f8 | ||
|
|
749af60796 | ||
|
|
87ddcac2fc | ||
|
|
e3383fe4c1 | ||
|
|
292856e1bd | ||
|
|
3dacaaf03a | ||
|
|
6307b765e3 | ||
|
|
eb2561175d | ||
|
|
a30e41f0b4 | ||
|
|
51341f6722 | ||
|
|
fb15751703 | ||
|
|
a0105bcb2f | ||
|
|
103e0796b7 | ||
|
|
363b23d6e3 | ||
|
|
52ad02a08a | ||
|
|
977cf3c383 | ||
|
|
827ea36d72 | ||
|
|
46b0367335 | ||
|
|
596afddfb6 | ||
|
|
68e4fca347 | ||
|
|
256c2dfdbe | ||
|
|
0737ee65bd | ||
|
|
05ac02770b | ||
|
|
25dc81a5d2 | ||
|
|
9e27744a05 | ||
|
|
77df620237 | ||
|
|
8998be66eb | ||
|
|
1180cac147 | ||
|
|
270231a004 | ||
|
|
c2f0f6c7c4 | ||
|
|
c7afae38a8 | ||
|
|
873a825e57 | ||
|
|
dc2318f404 | ||
|
|
699ed1da4d | ||
|
|
d8b95f845c | ||
|
|
014d39c11d | ||
|
|
a544a852f2 | ||
|
|
3311a48e3a | ||
|
|
5ac908afd4 | ||
|
|
12a3e659b1 | ||
|
|
b0780af7fa | ||
|
|
2ec31c7521 | ||
|
|
f2562500a3 | ||
|
|
85a567bdab | ||
|
|
11c415fd17 | ||
|
|
d67ea41032 | ||
|
|
66357ebe7e | ||
|
|
8dbde90a93 | ||
|
|
d2910de121 | ||
|
|
c5be9908c5 | ||
|
|
f7f70108bc | ||
|
|
bd08eadac9 | ||
|
|
a2314a9ab3 | ||
|
|
e1b071c0d8 | ||
|
|
aba8a57fa5 | ||
|
|
5784ab82ef | ||
|
|
636e79672a | ||
|
|
b935e96448 | ||
|
|
56ad5b97b6 | ||
|
|
dcead7361f | ||
|
|
ef314340fa | ||
|
|
a149cdc4f5 | ||
|
|
fc777e69e2 | ||
|
|
2ea1b9df6c | ||
|
|
05e54fa0c6 | ||
|
|
0203e6da31 | ||
|
|
93a852e6ea | ||
|
|
985b0970f1 | ||
|
|
e844d42275 | ||
|
|
a56ddb9ebe | ||
|
|
1957d2bb58 | ||
|
|
e55f11c5b9 | ||
|
|
07133b79e5 | ||
|
|
183a8feed4 | ||
|
|
e3253fce16 | ||
|
|
acd6f729f0 | ||
|
|
ec85cccc75 | ||
|
|
f3f640c24f | ||
|
|
9c2b42caa2 | ||
|
|
a677ffc90e | ||
|
|
254145da22 | ||
|
|
fec51ebc8e | ||
|
|
9d66aea843 | ||
|
|
50895a662a | ||
|
|
048ad78778 | ||
|
|
e9beffc799 | ||
|
|
fe9dd5ef28 | ||
|
|
468e4b6d55 | ||
|
|
b48ac505fd | ||
|
|
a0a6f958d9 | ||
|
|
16d156b530 | ||
|
|
420226b6c0 | ||
|
|
da8e72b0d6 | ||
|
|
ef13cbecfd | ||
|
|
947de33b5a | ||
|
|
4b9cd490ab | ||
|
|
784688a9da | ||
|
|
71bb760ce5 | ||
|
|
98a46e8caa | ||
|
|
5910bba30e | ||
|
|
19ba3b1f99 | ||
|
|
23bc6b8df7 | ||
|
|
69bea0f5b0 | ||
|
|
3c53394f4b | ||
|
|
8741053dfc | ||
|
|
8752f70ff3 | ||
|
|
2b66df39b6 | ||
|
|
17bb0e693d | ||
|
|
94e5b5fdaf | ||
|
|
497ec5c6b2 | ||
|
|
eaeae8d5ec | ||
|
|
3a05a2653b | ||
|
|
0ca63017c7 | ||
|
|
ea3416693c | ||
|
|
dcdbd3652a | ||
|
|
c35b7a66b0 | ||
|
|
6dc56af3fa | ||
|
|
af297c2031 | ||
|
|
024cf81238 | ||
|
|
5ec02e2f18 | ||
|
|
9709b97adf | ||
|
|
3be039b1a9 | ||
|
|
21bd664edf | ||
|
|
a31c422537 | ||
|
|
e5299d96ad | ||
|
|
5675f32a19 | ||
|
|
9d5a500b25 | ||
|
|
4bab1975c8 | ||
|
|
eae4153158 | ||
|
|
c207578f14 | ||
|
|
16801ad3e1 | ||
|
|
a92aa96623 | ||
|
|
ccf0ab3b51 | ||
|
|
7259c1c2ef | ||
|
|
d66675c672 | ||
|
|
38483b0c67 | ||
|
|
25cfed949d | ||
|
|
eacfcab187 | ||
|
|
9e014eba1f | ||
|
|
9692b709aa | ||
|
|
5acb04c180 | ||
|
|
ff96e2e4d6 | ||
|
|
19de4053fe | ||
|
|
2e96fa9e1e | ||
|
|
87234bda05 | ||
|
|
d0ff6d1579 | ||
|
|
105b68c807 | ||
|
|
97a6d8a15e | ||
|
|
26fa3df4aa | ||
|
|
9a336336d7 | ||
|
|
047d7f5046 | ||
|
|
4fc561dab5 | ||
|
|
785ac07de9 | ||
|
|
41c6978880 | ||
|
|
f7ebc4ec11 | ||
|
|
c06e8f47f0 | ||
|
|
dceb5dccd3 | ||
|
|
7a50138ae3 | ||
|
|
ca6364e5d4 | ||
|
|
43cead8249 | ||
|
|
62667de4a8 | ||
|
|
8492944fb5 | ||
|
|
f8955c0d1b | ||
|
|
0aac7813e4 | ||
|
|
44cc9e7db8 | ||
|
|
644329c0b8 | ||
|
|
ff97fba0f0 | ||
|
|
ce67e28f96 | ||
|
|
f7433de2bf | ||
|
|
bbd46fd3a6 | ||
|
|
077486c838 | ||
|
|
baedab5931 | ||
|
|
e149689249 | ||
|
|
b79d5e670a | ||
|
|
c23cb378cd | ||
|
|
a185685f0c | ||
|
|
b4699825d6 | ||
|
|
118a4f7097 | ||
|
|
7acb0657a7 | ||
|
|
021ce44673 | ||
|
|
9a7733c9a3 | ||
|
|
7150f5b536 | ||
|
|
753b9e8d7a | ||
|
|
6e62ecc8c1 | ||
|
|
0ab5369635 | ||
|
|
a274b769bd | ||
|
|
6e4d35777b | ||
|
|
776e6aa498 | ||
|
|
b7a21dd322 | ||
|
|
71d73c6562 | ||
|
|
6732710d6f | ||
|
|
90618723d4 | ||
|
|
084ca956fb | ||
|
|
44109f9d8f | ||
|
|
606efd3da1 | ||
|
|
2d76aa029a | ||
|
|
1acbbbaf6c | ||
|
|
8864884c67 | ||
|
|
a332b71463 | ||
|
|
10d76ae7a4 | ||
|
|
cd973adedf | ||
|
|
af94b770f9 | ||
|
|
62a51bb061 | ||
|
|
01ab61b8b1 | ||
|
|
c55d8c0bdf | ||
|
|
7336ed6eff | ||
|
|
60ca95e9b2 | ||
|
|
89b43a42c4 | ||
|
|
197be925b8 | ||
|
|
d49cd209e1 | ||
|
|
d60ab8cd9e | ||
|
|
7840ff0d7c | ||
|
|
a7144e57e1 | ||
|
|
50eac58493 | ||
|
|
4ef58b56e6 | ||
|
|
c1f0c76d17 | ||
|
|
079116fdf8 | ||
|
|
45e6385963 | ||
|
|
3ca0458d65 | ||
|
|
d5edec2cd0 | ||
|
|
ce9c9bea6a | ||
|
|
36c8f25fd1 | ||
|
|
b3050f1058 | ||
|
|
a04a61f61b | ||
|
|
58204248bb | ||
|
|
a47740ae28 | ||
|
|
604c2a0bdd | ||
|
|
1c19bb4dfc | ||
|
|
858d87a732 | ||
|
|
ea28900913 | ||
|
|
192e606fea | ||
|
|
8e4152e567 | ||
|
|
9e9da5355c | ||
|
|
26e9a17c6b | ||
|
|
fa43600cd9 | ||
|
|
3aca55205e | ||
|
|
3a0aac3c36 | ||
|
|
fe34bdc656 | ||
|
|
e69c1e8e93 | ||
|
|
1c0721f179 | ||
|
|
6f37968670 | ||
|
|
d1c34a9c88 | ||
|
|
65263a8b74 | ||
|
|
5cd6ab9335 | ||
|
|
56b1705df4 | ||
|
|
08e4c05129 | ||
|
|
b5b0ea5980 | ||
|
|
803e17f3a3 | ||
|
|
75017d7ac6 | ||
|
|
80486d644d | ||
|
|
1bdc167f7a | ||
|
|
3f2fdb0b14 | ||
|
|
ac186f89f1 | ||
|
|
fdccfd166f | ||
|
|
272a71f3d5 | ||
|
|
3621879d38 | ||
|
|
4661990cfe | ||
|
|
7db63b10e8 | ||
|
|
428ea89f62 | ||
|
|
60e0ed911e | ||
|
|
e1366ef90f | ||
|
|
85c170712a | ||
|
|
33bf487a1c | ||
|
|
227810db75 | ||
|
|
48d6a27fad | ||
|
|
6171c76199 | ||
|
|
45c1958d83 | ||
|
|
e51d9439c5 | ||
|
|
a48b5deb29 | ||
|
|
212f40cd1a | ||
|
|
18952c57ff | ||
|
|
4296b49570 | ||
|
|
95f084fb36 | ||
|
|
0b237a2469 | ||
|
|
8c34a4fd0a | ||
|
|
f970594c28 | ||
|
|
02c8a1703a | ||
|
|
590d2f2661 | ||
|
|
425f6f7c0b | ||
|
|
c229dc1548 | ||
|
|
e4cc84b771 | ||
|
|
9b3569be50 | ||
|
|
a8e9c5aaf2 | ||
|
|
5ffcd78f27 | ||
|
|
de9dd77b50 | ||
|
|
661302f698 | ||
|
|
854387b2d0 | ||
|
|
7a305b5a5c | ||
|
|
9f463707ee | ||
|
|
e1bcbae975 | ||
|
|
e77efde503 | ||
|
|
4583128c02 | ||
|
|
35b1232b0a | ||
|
|
bc8fe527f7 | ||
|
|
2943343003 | ||
|
|
4e061ef385 | ||
|
|
571cf9c5d9 | ||
|
|
22bde81712 | ||
|
|
a9736b96c0 | ||
|
|
0adbef9696 | ||
|
|
53e52c841b | ||
|
|
b78bb9e970 | ||
|
|
d6959f64c3 | ||
|
|
c5dbc71db3 | ||
|
|
fbd9440711 | ||
|
|
a439dc4cd8 | ||
|
|
fe3a47f2d5 | ||
|
|
9509c8027b | ||
|
|
519429cebb | ||
|
|
4aee779385 | ||
|
|
7903119cb4 | ||
|
|
ef1f96f382 | ||
|
|
af9a6a8a6e | ||
|
|
51c77be7a2 | ||
|
|
f98563cbe9 | ||
|
|
dffa00dc5e | ||
|
|
6c5b32d92b | ||
|
|
7d5c55fc95 | ||
|
|
017654852d | ||
|
|
9e2e616e1b | ||
|
|
0d5d28e4a6 | ||
|
|
90e50db189 | ||
|
|
e9a7cad202 | ||
|
|
60cf0b1099 | ||
|
|
aefb72f7cc | ||
|
|
4d434d36be | ||
|
|
f69abdcc14 | ||
|
|
ee36c31637 | ||
|
|
e0a064a0fa | ||
|
|
568fcbf547 | ||
|
|
7028bbfbfd | ||
|
|
c552e9e9be | ||
|
|
f8e8914f7d | ||
|
|
f195af017e | ||
|
|
6474f25253 | ||
|
|
6d2851e742 | ||
|
|
11fb18f598 | ||
|
|
c026d7d248 | ||
|
|
e0b33799d5 | ||
|
|
17d3d9deb7 | ||
|
|
02212bde21 | ||
|
|
86c6cda79a | ||
|
|
488eb1fac3 | ||
|
|
3eab5503f1 | ||
|
|
61f84302f3 | ||
|
|
5dc0333580 | ||
|
|
f2092ee89c | ||
|
|
d4e7c2e1b1 | ||
|
|
9d69951faa | ||
|
|
2d68b6e589 | ||
|
|
b4af85f405 | ||
|
|
e9ca09da87 | ||
|
|
d770c20b5a | ||
|
|
1ef9c617b3 | ||
|
|
48dc27e106 | ||
|
|
8aab0ee318 | ||
|
|
f9d1086062 | ||
|
|
5e8a04e54d | ||
|
|
32a38af4f7 | ||
|
|
8c8059db30 | ||
|
|
be99c59725 | ||
|
|
f6e2a59008 | ||
|
|
fa586426fa | ||
|
|
60a1bf0d43 | ||
|
|
f7f7d5c4f0 | ||
|
|
85fc2b2666 | ||
|
|
65624ed77e | ||
|
|
6a3241fa0b | ||
|
|
ff22ab0026 | ||
|
|
907f5051e1 | ||
|
|
76a9e94aed | ||
|
|
772ebd198a | ||
|
|
de7808d42b | ||
|
|
55b24c6a45 | ||
|
|
603f667f93 | ||
|
|
18162cf110 | ||
|
|
f693f26ffc | ||
|
|
4cc1dc405f | ||
|
|
12a4cbef46 | ||
|
|
f9a9a405cd | ||
|
|
285f464b43 | ||
|
|
585bfba850 | ||
|
|
fa564c6029 | ||
|
|
fd632fc63b | ||
|
|
d8f1387703 | ||
|
|
522eb40808 | ||
|
|
587053b26c | ||
|
|
fa8d4eff0f | ||
|
|
666a9ef0fa | ||
|
|
014ea3eadc | ||
|
|
f7e1b39af9 | ||
|
|
33005ea243 | ||
|
|
651a9d30ce | ||
|
|
0bd6005cb9 | ||
|
|
3ee745d79c | ||
|
|
a48f194350 | ||
|
|
ec508f5224 | ||
|
|
78f0ec94ea | ||
|
|
44f9e756da | ||
|
|
1b9523f700 | ||
|
|
3d992d56cd | ||
|
|
72f7b4627f | ||
|
|
ee31808522 | ||
|
|
5c1f165079 | ||
|
|
95755ba515 | ||
|
|
7414c921f3 | ||
|
|
791e4e26a9 | ||
|
|
4d61963894 | ||
|
|
d1d6e8e11c | ||
|
|
778f9039fb | ||
|
|
4904c184f7 | ||
|
|
5622a9c565 | ||
|
|
2e5069d5a1 | ||
|
|
4cd692e061 | ||
|
|
cbde819e07 | ||
|
|
3d6cb623f0 | ||
|
|
47cfcd7b12 | ||
|
|
244128c7ed | ||
|
|
9c9b98dde4 | ||
|
|
36d1522f01 | ||
|
|
536e17eac4 | ||
|
|
7bba1dc944 | ||
|
|
59c859fb17 | ||
|
|
887ec45b6b | ||
|
|
faa0521428 | ||
|
|
8886b20c01 | ||
|
|
4810aec10d | ||
|
|
deb1979ea9 | ||
|
|
4739c71ee0 | ||
|
|
216a88c00c | ||
|
|
030ffe6dce | ||
|
|
da19ad7943 | ||
|
|
e7088ef06c | ||
|
|
92c7f886df | ||
|
|
59727875db | ||
|
|
98063422de | ||
|
|
4ce4786a58 | ||
|
|
3eb9714e68 | ||
|
|
ee64dc38f6 | ||
|
|
6146c7e450 | ||
|
|
deb38f8455 | ||
|
|
73f0b9dabd | ||
|
|
9ab4fa608a | ||
|
|
bf9d5efe43 | ||
|
|
7b56b36564 | ||
|
|
6e107e6368 | ||
|
|
1a7a468eb6 | ||
|
|
13e6070dd9 | ||
|
|
8cc8e45afd | ||
|
|
e373cde4f7 | ||
|
|
072079df05 | ||
|
|
22614f09a0 | ||
|
|
c858c8f75b | ||
|
|
eb80aaf96d | ||
|
|
ba7d0a60e4 | ||
|
|
b266dc24d7 | ||
|
|
619fe9a0e7 | ||
|
|
10f1917589 | ||
|
|
50cf776e70 | ||
|
|
64dacc7c70 | ||
|
|
f7c75442e7 | ||
|
|
293611287e | ||
|
|
6a2a1da5f9 | ||
|
|
7ebbf5911c | ||
|
|
254c3814d5 | ||
|
|
44c1920d9b | ||
|
|
109372d10b | ||
|
|
94847b846b | ||
|
|
3746332eb5 | ||
|
|
54b01d30da | ||
|
|
0509eb3f0a | ||
|
|
d7e37cf658 | ||
|
|
b81a4b6d5e | ||
|
|
b3b11174be | ||
|
|
bdade99837 | ||
|
|
29be139803 | ||
|
|
ca8779676c | ||
|
|
ee03d62997 | ||
|
|
e068012cfb | ||
|
|
8fbb30437c | ||
|
|
9396ed765c | ||
|
|
d7f2075b1d | ||
|
|
e5ac94a16f | ||
|
|
2be05d4f9a | ||
|
|
f3ee2d2bfd | ||
|
|
f580acaf70 | ||
|
|
d5e2bf546e | ||
|
|
27322a971f | ||
|
|
8b5d6c9367 | ||
|
|
f09d44d8a0 | ||
|
|
9b031ff9d3 | ||
|
|
de59e8aa56 | ||
|
|
850aa5b797 | ||
|
|
9107fd839b | ||
|
|
89cae22b91 | ||
|
|
82ee48b166 | ||
|
|
17f3c5777e | ||
|
|
2cb787f816 | ||
|
|
feba135cac | ||
|
|
45c9e75e4e | ||
|
|
586a7a85e3 | ||
|
|
f844bd99c7 | ||
|
|
0747336c0f | ||
|
|
ace102e1c1 | ||
|
|
b976461c29 | ||
|
|
ad7243844e | ||
|
|
4a6a458cdd | ||
|
|
197d46b511 | ||
|
|
26f7d6e517 | ||
|
|
cf25d3d7be | ||
|
|
036e0af960 | ||
|
|
b7b2e99ab1 | ||
|
|
b115b6f66c | ||
|
|
592f3dce9a | ||
|
|
bcef0dd2c5 | ||
|
|
3f86272913 | ||
|
|
322834b762 | ||
|
|
04ddf30167 | ||
|
|
1935cc4841 | ||
|
|
bd96571d8a | ||
|
|
aa253bf53e | ||
|
|
b8a59097c2 | ||
|
|
a630b74fa8 | ||
|
|
3f7b222b92 | ||
|
|
f1575f75c7 | ||
|
|
0966b231e8 | ||
|
|
00e1a1962b | ||
|
|
c5c382ade6 | ||
|
|
858873dfa0 | ||
|
|
7231acc236 | ||
|
|
adea84e123 | ||
|
|
565757580b | ||
|
|
620d7de02f | ||
|
|
bba625a68f | ||
|
|
b282a18f6b | ||
|
|
417487e195 | ||
|
|
fba48b1d90 | ||
|
|
78f62847a3 | ||
|
|
3bfaa33c58 | ||
|
|
d0cb119bb0 | ||
|
|
3fc6b1e8cf | ||
|
|
ae06af9bc5 | ||
|
|
260a378e8c | ||
|
|
94e052af83 | ||
|
|
d56ab9b79b | ||
|
|
ad556e7413 | ||
|
|
b9f49a83e0 | ||
|
|
ebec2c95c0 | ||
|
|
d62627c8a5 | ||
|
|
96d2c7fad9 | ||
|
|
3aac75f5b5 | ||
|
|
908d39ad39 | ||
|
|
084ffb0dc1 | ||
|
|
cec2bdb805 | ||
|
|
a0374cb4ea | ||
|
|
538338abfe | ||
|
|
097e398efc | ||
|
|
0fd9b3354a | ||
|
|
765b941472 | ||
|
|
64084bb628 | ||
|
|
df269eb4f7 | ||
|
|
722b03dca8 | ||
|
|
3ddfc93c1b | ||
|
|
5eb70fa57d | ||
|
|
eccc9d6fbd | ||
|
|
049ed723a7 | ||
|
|
b6cdc5803b | ||
|
|
792299537d | ||
|
|
7b01e72a9b | ||
|
|
755549a745 | ||
|
|
1c39555255 | ||
|
|
ff5aba9a51 | ||
|
|
467d012bce | ||
|
|
09bed4e74f | ||
|
|
7a8e71b837 | ||
|
|
90336277a7 | ||
|
|
0b662b7211 | ||
|
|
4581722bbe |
No files matched your search
@@ -0,0 +1 @@
|
||||
src/octoprint/_version.py export-subst
|
||||
+2
-1
@@ -4,7 +4,6 @@
|
||||
*.pyc
|
||||
*.zip
|
||||
*.exe
|
||||
*.gcode
|
||||
*.swp
|
||||
darwin-Cura-*
|
||||
win32-Cura-*
|
||||
@@ -21,3 +20,5 @@ dist
|
||||
pypy
|
||||
OctoPrint.egg-info
|
||||
*.orig
|
||||
|
||||
*.codekit
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
|
||||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
install:
|
||||
- pip install -r requirements.txt
|
||||
script:
|
||||
- nosetests
|
||||
@@ -0,0 +1,8 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
|
||||
[octoprint.messages]
|
||||
file_filter = src/octoprint/translations/<lang>/LC_MESSAGES/messages.po
|
||||
source_file = src/octoprint/translations/messages.pot
|
||||
source_lang = en
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Configuration file for the versioneer lookup, manually mapping tags based on branches
|
||||
#
|
||||
# Format is
|
||||
#
|
||||
# <branch-regex> <tag> <reference commit>
|
||||
#
|
||||
# The file is processed from top to bottom, the first matching line wins. If <tag> or <reference commit> are left out,
|
||||
# the lookup table does not apply to the matched branches
|
||||
|
||||
# master and staging shall not use the lookup table
|
||||
master
|
||||
staging
|
||||
|
||||
# fix/ branches are fixes for master, so we don't handle those either
|
||||
fix/.*
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.2.0-dev for now
|
||||
.* 1.2.0-dev 50cf776e70b9
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.0 (Unreleased)
|
||||
|
||||
### New Features
|
||||
|
||||
* Added internationalization of UI. Translations of OctoPrint are being crowd sourced via [Transifex](https://www.transifex.com/projects/p/octoprint/).
|
||||
The following translations are already available with more in the works:
|
||||
- Dutch (nl)
|
||||
- German (de)
|
||||
- French (fr)
|
||||
- Hebrew (he)
|
||||
- Norwegian (no)
|
||||
- Romanian (ro)
|
||||
* New file list: Pagination is gone, no more (mobile incompatible) pop overs, instead scrollable and with instant
|
||||
search
|
||||
* You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing
|
||||
support is enabled -- STL) files to automatically add.
|
||||
* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its
|
||||
core functionality.
|
||||
* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications
|
||||
* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A
|
||||
connection to a printer will always have a printer profile associated.
|
||||
* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are
|
||||
- `action:pause`: Pauses the current job in OctoPrint
|
||||
- `action:resume`: Resumes the current job in OctoPrint
|
||||
- `action:disconnect`: Disconnects OctoPrint from the printer
|
||||
|
||||
### Improvements
|
||||
|
||||
* Logging is now configurable via config file
|
||||
* Added last print time to additional GCODE file information
|
||||
* Better error handling for capture issues during timelapse creation & more robust handling of missing images during
|
||||
timelapse creation
|
||||
* Start counting the layers at 1 instead of 0 in the GCODE viewer
|
||||
* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1
|
||||
* Better error reporting for timelapse rendering and system commands
|
||||
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
|
||||
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
|
||||
* Slicing has been greatly improved:
|
||||
* It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing
|
||||
job (defining overrides is not yet part of the UI but it's on the roadmap).
|
||||
* A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list
|
||||
as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the
|
||||
sliced GCODE for printing or starting to print it directly)
|
||||
* Slicers themselves are integrated into the system via ``SlicingPlugins``.
|
||||
* The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
|
||||
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
|
||||
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
|
||||
accommodate the new integration.
|
||||
* The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)).
|
||||
* The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI).
|
||||
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
|
||||
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI)
|
||||
* Also interpret lines starting with "!!" as errors
|
||||
* Added deletion of pyc files to the `python setup.py clean` command
|
||||
* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637))
|
||||
* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639))
|
||||
* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558))
|
||||
* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as
|
||||
long as they are in use
|
||||
* Settings in UI get refreshed when opening settings dialog
|
||||
* New event "SettingsUpdated"
|
||||
* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens
|
||||
in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally
|
||||
OctoPrint will use data from prior prints to enhance the initial print time estimation.
|
||||
* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing
|
||||
bug reports
|
||||
* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if
|
||||
it has been changed during runtime by external editing, hence no config settings added manually while the server
|
||||
was running should be overwritten anymore.
|
||||
* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected.
|
||||
* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning
|
||||
message for now.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left)
|
||||
as 0
|
||||
* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder
|
||||
setups under Smoothieware
|
||||
* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without
|
||||
side effects
|
||||
* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers
|
||||
in the parsed multipart data from file uploads
|
||||
* Various fixes of bugs in newly introduced features and improvements:
|
||||
* [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis
|
||||
queue
|
||||
* [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again
|
||||
* [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in
|
||||
printer profiles
|
||||
* [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in
|
||||
printer profiles
|
||||
* Various fixes without tickets:
|
||||
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
|
||||
* Do not deliver the API key on settings API unless user has admin rights
|
||||
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
|
||||
|
||||
## 1.1.2 (Unreleased)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
|
||||
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated
|
||||
by versioneer
|
||||
* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
|
||||
* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url
|
||||
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
|
||||
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
|
||||
introduced by this
|
||||
* Small fixes for timelapse creation:
|
||||
- [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there
|
||||
was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b)
|
||||
and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc))
|
||||
- [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset
|
||||
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
|
||||
image file names
|
||||
|
||||
## 1.1.1 (2014-10-27)
|
||||
|
||||
### Improvements
|
||||
|
||||
* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first
|
||||
server start and written back into ``config.yaml``
|
||||
* Event subscriptions are now enabled by default (it was an accident that they weren't)
|
||||
* Generate the key used for session hashing individually for each server instance
|
||||
* Generate the salt used for hashing user passwords individually for each server instance
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers
|
||||
* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup
|
||||
* [IRC] Also allow downloading .g files via Tornado
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1))
|
||||
|
||||
## 1.1.0 (2014-09-03)
|
||||
|
||||
### New Features
|
||||
|
||||
* New REST API, including User API Keys additionally to the global API key. Please note that **this will break existing
|
||||
API clients** as it replaces the old API (same endpoint). You can find the documentation of the new API at
|
||||
[docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/api/index.html).
|
||||
* New Event structure allows more flexibility regarding payload data, configuration files will be migrated automatically.
|
||||
You can find the documentation of the new event format and its usage at [docs.octoprint.org](http://docs.octoprint.org/en/1.1.0/events/index.html).
|
||||
* Support for multi extruder setups. With this OctoPrint now in theory supports an unlimited amount of extruders, however
|
||||
for now it's artificially limited to 9.
|
||||
* Log files can be accessed from within the browser via the Settings dialog ([#361](https://github.com/foosel/OctoPrint/pull/361))
|
||||
* Timelapses can now have a post-roll duration configured which will be rendered into the video too to not let it
|
||||
end so abruptly ([#384](https://github.com/foosel/OctoPrint/issues/384))
|
||||
* The terminal tab now has a command history ([#388](https://github.com/foosel/OctoPrint/pull/388))
|
||||
|
||||
### Improvements
|
||||
|
||||
* Stopping the application via Ctrl-C produces a less scary message ([#277](https://github.com/foosel/OctoPrint/pull/277))
|
||||
* Webcam stream is disabled when control tab is not in focus, reduces bandwidth ([#316](https://github.com/foosel/OctoPrint/issues/316))
|
||||
* M and G commands entered in Terminal tab are automatically converted to uppercase
|
||||
* GCODE viewer now only loads automatically if GCODE file size is beneath certain threshold (different ones for desktop
|
||||
and mobile devices), only actually loads file if user acknowledges that this might be too much for his browser
|
||||
* Added time needed for printing file to PrintDone event's payload ([#333](https://github.com/foosel/OctoPrint/issues/333))
|
||||
* Also provide the filename (basename without the path) in print events
|
||||
* Support for circular beds in the GCODE viewer ([#407](https://github.com/foosel/OctoPrint/pull/407))
|
||||
* The dimensions of the print bed can now be configured via the Settings ([#396](https://github.com/foosel/OctoPrint/pull/396))
|
||||
* Target temperature reporting format of Repetier Firmware is now supported as well ([360](https://github.com/foosel/OctoPrint/issues/360))
|
||||
* Version tracking now based on git tagging and [versioneer](https://github.com/warner/python-versioneer/). Version number,
|
||||
git commit and branch get reported in the format `<version tag>-<commits since then>-g<commit hash> (<branch> branch)`,
|
||||
e.g. `1.2.0-dev-172-ga48b5de (devel branch)`.
|
||||
* Made "Center viewport on model" and "Zoom in on model" in the GCODE viewer automatically deselect and de-apply if
|
||||
viewport gets manipulated by the user ([#398](https://github.com/foosel/OctoPrint/issues/398))
|
||||
* GCODE viewer now interprets inverted axes for printer control and mirrors print bed accordingly ([#431](https://github.com/foosel/OctoPrint/issues/431))
|
||||
* Added `clean` command to `setup.py`, removes old build artifacts (mostly interesting for developers)
|
||||
* Added version resource on API which reports application and API version
|
||||
* Made the navbar static instead of fixed to improve usability on mobile devices ([#257](https://github.com/foosel/OctoPrint/issues/257))
|
||||
* Switch to password field upon enter in username field, submit login form upon enter in password field
|
||||
* Changed default path to OctoPrint executable in included init-script to `/usr/local/bin/octoprint` (the default when
|
||||
installing via `python setup.py install`)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Properly calculate time deltas (forgot to factor in days)
|
||||
* [#35](https://github.com/foosel/OctoPrint/issues/35) - GCODE viewer has been modularized, options are now functional
|
||||
* [#337](https://github.com/foosel/OctoPrint/issues/337) - Also recognize `--iknowwhatimdoing` when running as daemon
|
||||
* [#357](https://github.com/foosel/OctoPrint/issues/357) - Do not run GCODE analyzer when a print is ongoing
|
||||
* [#381](https://github.com/foosel/OctoPrint/issues/381) - Only list those SD files that have an ASCII filename
|
||||
* Fixed a race condition that could occur when pressing "Print" (File not opened yet, but attempt to read from it)
|
||||
* [#398](https://github.com/foosel/OctoPrint/issues/398) - Fixed interfering options in GCODE viewer
|
||||
* [#399](https://github.com/foosel/OctoPrint/issues/399) & [360](https://github.com/foosel/OctoPrint/issues/360) - Leave
|
||||
bed temperature unset when not detected (instead of dying a horrible death)
|
||||
* [#492](https://github.com/foosel/OctoPrint/issues/492) - Fixed a race condition which could lead to an attempt to read
|
||||
from an already closed serial port, causing an error to be displayed to the user
|
||||
* [#257](https://github.com/foosel/OctoPrint/issues/257) - Logging in on mobile devices should now work
|
||||
* [#476](https://github.com/foosel/OctoPrint/issues/476) - Also update the metadata correctly when an analysis finishes
|
||||
* Various fixes of bugs in newly introduced features and improvements:
|
||||
- [#314](https://github.com/foosel/OctoPrint/issues/314) - Use G28 for homing (G1 was copy and paste error)
|
||||
- [#317](https://github.com/foosel/OctoPrint/issues/317) - Fixed "load and print" function
|
||||
- [#326](https://github.com/foosel/OctoPrint/issues/326) - Fixed refresh of SD file list
|
||||
- [#338](https://github.com/foosel/OctoPrint/issues/338) - Refetch file list when deleting a file
|
||||
- [#339](https://github.com/foosel/OctoPrint/issues/339) - More error resilience when handling temperature offset data from the backend
|
||||
- [#345](https://github.com/foosel/OctoPrint/issues/345) - Also recognize such temperature reports that do not contain a `T:` but a `T0:`
|
||||
- [#377](https://github.com/foosel/OctoPrint/pull/377) - URLs in API examples fixed
|
||||
- [#378](https://github.com/foosel/OctoPrint/pull/378) - Fixed crash of API call when `getStartTime()` returns None
|
||||
- [#379](https://github.com/foosel/OctoPrint/pull/379) - Corrected response code for connection success
|
||||
- [#414](https://github.com/foosel/OctoPrint/pull/414) - Fix style attribute for Actual column header
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0))
|
||||
|
||||
## 1.0.0 (2014-06-22)
|
||||
|
||||
First release with new versioning scheme.
|
||||
@@ -0,0 +1,22 @@
|
||||
Issues, Tickets, however you may call them
|
||||
------------------------------------------
|
||||
|
||||
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly!
|
||||
|
||||
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be treated as if only describing the first purpose, the others will be ignored!
|
||||
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket.
|
||||
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
|
||||
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work), **add [Support] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
|
||||
- If you have a general **question**, **add [Question] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster!
|
||||
- If you have another reason for creating a ticket that doesn't fit any of the above categories, think hard if it might not be something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741). If you are sure it needs to be reported here, **add [Misc] to your issue's title!**
|
||||
|
||||
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
|
||||
|
||||
Pull Requests
|
||||
-------------
|
||||
|
||||
1. Please create all pull requests against the `devel` branch.
|
||||
2. Create **one pull request per feature/bug fix**.
|
||||
3. Create a custom branch for your feature/bug fix and use that as base for your pull request. Pull requests directly against your version of `devel` will be closed.
|
||||
4. In your pull request's description, state what your pull request is doing, as in, what feature does it implement, what bug does it fix.
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
recursive-include src/octoprint/static *
|
||||
recursive-include src/octoprint/templates *
|
||||
include versioneer.py
|
||||
include src/octoprint/_version.py
|
||||
@@ -8,18 +8,10 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
Reporting bugs
|
||||
--------------
|
||||
Contributing
|
||||
------------
|
||||
|
||||
OctoPrint's issue tracker can be found [on Github](https://github.com/foosel/OctoPrint/issues). **Before opening a new
|
||||
ticket please take a look at [this guide on how to file a bug report with OctoPrint](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report).**
|
||||
|
||||
Sending pull requests
|
||||
---------------------
|
||||
|
||||
Please create all pull requests against the [devel branch](https://github.com/foosel/OctoPrint/tree/devel) of OctoPrint, as that one is used for developing new
|
||||
features and then merged against master when those features are deemed mature enough for general consumption. In case
|
||||
of bug fixes I'll take care to cherry pick them against master if the bugs they are fixing are critical.
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
@@ -32,43 +24,50 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are listed in requirements.txt and can be
|
||||
installed using `pip`:
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `setup.py`:
|
||||
|
||||
pip install -r requirements.txt
|
||||
python setup.py install
|
||||
|
||||
You should also do this after pulling from the repository, since the dependencies might have changed.
|
||||
You should also do this every time after pulling from the repository, since the dependencies might have changed.
|
||||
|
||||
OctoPrint currently only supports Python 2.7.
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Just start the server via
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
./run
|
||||
You can start the server via
|
||||
|
||||
octoprint
|
||||
|
||||
By default it binds to all interfaces on port 5000 (so pointing your browser to `http://127.0.0.1:5000`
|
||||
will do the trick). If you want to change that, use the additional command line parameters `host` and `port`,
|
||||
which accept the host ip to bind to and the numeric port number respectively. If for example you want the server
|
||||
to only listen on the local interface on port 8080, the command line would be
|
||||
|
||||
./run --host=127.0.0.1 --port=8080
|
||||
octoprint --host=127.0.0.1 --port=8080
|
||||
|
||||
Alternatively, the host and port on which to bind can be defined via the configuration.
|
||||
|
||||
If you want to run OctoPrint as a daemon (only supported on Linux), use
|
||||
|
||||
./run --daemon {start|stop|restart} [--pid PIDFILE]
|
||||
octoprint --daemon {start|stop|restart} [--pid PIDFILE]
|
||||
|
||||
If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`.
|
||||
|
||||
You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders),
|
||||
e.g.:
|
||||
|
||||
./run --config /path/to/another/config.yaml --basedir /path/to/my/basedir
|
||||
octoprint --config /path/to/another/config.yaml --basedir /path/to/my/basedir
|
||||
|
||||
See `run --help` for further information.
|
||||
See `octoprint --help` for further information.
|
||||
|
||||
OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it
|
||||
takes the same command line arguments as the `octoprint` script.
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
@@ -78,9 +77,5 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration).
|
||||
|
||||
Setup on a Raspberry Pi running Raspbian
|
||||
----------------------------------------
|
||||
|
||||
A comprehensive setup guide can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian).
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
@@ -0,0 +1,6 @@
|
||||
[python: src/octoprint/**.py]
|
||||
[jinja2: src/octoprint/templates/**.jinja2]
|
||||
extensions=jinja2.ext.autoescape, jinja2.ext.with_
|
||||
|
||||
[javascript: src/octoprint/static/js/app/**.js]
|
||||
extract_messages = gettext, ngettext
|
||||
@@ -0,0 +1,170 @@
|
||||
.. _sec-api-apps:
|
||||
|
||||
****
|
||||
Apps
|
||||
****
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-apps-sessionkey:
|
||||
|
||||
Session Keys
|
||||
============
|
||||
|
||||
OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based
|
||||
validity and are generated by OctoPrint for requesting apps.
|
||||
|
||||
Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to
|
||||
be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by
|
||||
installing app specific plugins which implement the ``AppPlugin`` type).
|
||||
|
||||
Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the
|
||||
application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the
|
||||
``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is
|
||||
enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly).
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
api:
|
||||
apps:
|
||||
"com.example.my_octoprint_app:0.9":
|
||||
pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE=
|
||||
enabled: false
|
||||
"com.example.my_octoprint_app:1.0":
|
||||
pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
|
||||
In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having
|
||||
leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys.
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-workflow:
|
||||
|
||||
Workflow
|
||||
--------
|
||||
|
||||
Apps perform the handshake by first requesting a temporary key with very limited validity,
|
||||
then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their
|
||||
private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the
|
||||
key to be used as a fully recognized API key.
|
||||
|
||||
For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below.
|
||||
|
||||
.. _sec-api-apps-sessionkey-get:
|
||||
|
||||
Obtaining a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:get:: /apps/auth
|
||||
|
||||
Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been
|
||||
:ref:`verified <sec-api-apps-sessionkey-verify>`.
|
||||
|
||||
Returns the temporary session key and the timestamp until it's valid.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"unverifiedKey": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416220357.011
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-apps-sessionkey-verify:
|
||||
|
||||
Verifying a temporary session key
|
||||
---------------------------------
|
||||
|
||||
.. http:post:: /apps/auth
|
||||
|
||||
Verify a formerly :ref:`retrieved <sec-api-apps-sessionkey-get>` temporary session key by providing credentials and a
|
||||
cryptographic signature over these credentials and the temporary key.
|
||||
|
||||
Returns the now verified session key and the new validity.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /apps/auth HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"appid": "com.example.my_octoprint_app",
|
||||
"appversion": "1.0",
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"key": "F43A844750F74AD080FE9F438D47B33C",
|
||||
"validUntil": 1416227497.011
|
||||
}
|
||||
|
||||
.. _sec-api-apps-sessionkey-signature:
|
||||
|
||||
Creating the signature
|
||||
----------------------
|
||||
|
||||
The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon),
|
||||
signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines.
|
||||
|
||||
Example for signature generation using Python and the `Python RSA library <https://pypi.python.org/pypi/rsa>`_:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
import base64
|
||||
import rsa
|
||||
|
||||
appid = "com.example.my_octoprint_app"
|
||||
version = "1.0"
|
||||
unverified_key = "F43A844750F74AD080FE9F438D47B33C"
|
||||
message_to_sign = appid + ":" + version + ":" + unverified_key
|
||||
// => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C"
|
||||
|
||||
private_key = rsa.PrivateKey.load_pkcs1("...")
|
||||
signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "")
|
||||
// => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w=="
|
||||
|
||||
|
||||
.. _sec-api-apps-sessionkey-testing:
|
||||
|
||||
Testing your implementation
|
||||
---------------------------
|
||||
|
||||
If you want to use app session keys, here is the key pair with which the above examples were created, in order for you
|
||||
to verify your signature implementation::
|
||||
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va
|
||||
NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy
|
||||
p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW
|
||||
fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u
|
||||
xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf
|
||||
IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa
|
||||
W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0
|
||||
-----END RSA PRIVATE KEY-----
|
||||
|
||||
-----BEGIN RSA PUBLIC KEY-----
|
||||
MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os
|
||||
vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE=
|
||||
-----END RSA PUBLIC KEY-----
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
.. _sec-api-connection:
|
||||
|
||||
*******************
|
||||
Connection handling
|
||||
*******************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-connection-current:
|
||||
|
||||
Get connection settings
|
||||
=======================
|
||||
|
||||
.. http:get:: /api/connection
|
||||
|
||||
Retrieve the current connection settings, including information regarding the available baudrates and
|
||||
serial ports and the current connection state.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"current": {
|
||||
"state": "Operational",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 250000,
|
||||
"printerProfile": "_default"
|
||||
},
|
||||
"options": {
|
||||
"ports": ["/dev/ttyACM0", "VIRTUAL"],
|
||||
"baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600],
|
||||
"printerProfiles": [{"name": "Default", id: "_default"}],
|
||||
"portPreference": "/dev/ttyACM0",
|
||||
"baudratePreference": 250000,
|
||||
"printerProfilePreference": "_default",
|
||||
"autoconnect": true
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-connection-command:
|
||||
|
||||
Issue a connection command
|
||||
==========================
|
||||
|
||||
.. http:post:: /api/connection
|
||||
|
||||
Issue a connection command. Currently available command are:
|
||||
|
||||
connect
|
||||
Instructs OctoPrint to connect to the printer. Additional parameters are:
|
||||
|
||||
* ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if
|
||||
no preference is available auto detection will be attempted.
|
||||
* ``baudrate``: Optional, specific baudrate to connect with. If not set the current ``baudratePreference`` will
|
||||
be used, or if no preference is available auto detection will be attempted.
|
||||
* ``printerProfile`` Optional, specific printer profile to use for connection. If not set the current default printer
|
||||
profile will be used.
|
||||
* ``save``: Optional, whether to save the request's ``port`` and ``baudrate`` settings as new preferences. Defaults
|
||||
to ``false`` if not set.
|
||||
* ``autoconnect``: Optional, whether to automatically connect to the printer on OctoPrint's startup in the future.
|
||||
If not set no changes will be made to the current configuration.
|
||||
|
||||
disconnect
|
||||
Instructs OctoPrint to disconnect from the printer.
|
||||
|
||||
**Example Connect Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "connect",
|
||||
"port": "/dev/ttyACM0",
|
||||
"baudrate": 115200,
|
||||
"printerProfile": "my_printer_profile",
|
||||
"save": true,
|
||||
"autoconnect": true
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Disconnect Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/connection HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "disconnect"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``connect`` or ``disconnect``
|
||||
:json string port: ``connect`` command: The port to connect to. If left out either the existing ``portPreference``
|
||||
will be used, or if that is not available OctoPrint will attempt auto detection. Must be part
|
||||
of the available ports.
|
||||
:json number baudrate: ``connect`` command: The baudrate to connect with. If left out either the existing
|
||||
``baudratePreference`` will be used, or if that is not available OctoPrint will attempt
|
||||
autodetection. Must be part of the available baudrates.
|
||||
:json string printerProfile: ``connect`` command: The id of the printer profile to use for the connection. If left out the current
|
||||
default printer profile will be used. Must be part of the available printer profiles.
|
||||
:json boolean save: ``connect`` command: Whether to save the supplied connection settings as the new preference.
|
||||
Defaults to ``false`` if not set.
|
||||
:json boolean autoconnect: ``connect`` command: Whether to attempt to automatically connect to the printer on server
|
||||
startup. If not set no changes will be made to the current setting.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If the selected `port` or `baudrate` for a ``connect`` command are not part of the available
|
||||
options.
|
||||
@@ -0,0 +1,352 @@
|
||||
.. _sec-api-datamodel:
|
||||
|
||||
*****************
|
||||
Common data model
|
||||
*****************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-datamodel-printer:
|
||||
|
||||
Printer related
|
||||
===============
|
||||
|
||||
.. _sec-api-datamodel-printer-state:
|
||||
|
||||
Printer State
|
||||
-------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``text``
|
||||
- 1
|
||||
- String
|
||||
- A textual representation of the current state of the printer, e.g. "Operational" or "Printing"
|
||||
* - ``flags``
|
||||
- 1
|
||||
- Printer state flags
|
||||
- A couple of boolean printer state flags
|
||||
* - ``flags.operational``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is operational, ``false`` otherwise
|
||||
* - ``flags.paused``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is currently paused, ``false`` otherwise
|
||||
* - ``flags.printing``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is currently printing, ``false`` otherwise
|
||||
* - ``flags.sdReady``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer's SD card is available and initialized, ``false`` otherwise. This is redundant information
|
||||
to :ref:`the SD State <sec-api-printer-datamodel-sdstate>`.
|
||||
* - ``flags.error``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if an unrecoverable error occurred, ``false`` otherwise
|
||||
* - ``flags.ready``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is operational and no data is currently being streamed to SD, so ready to receive instructions
|
||||
* - ``flags.closedOrError``
|
||||
- 1
|
||||
- Boolean
|
||||
- ``true`` if the printer is disconnected (possibly due to an error), ``false`` otherwise
|
||||
|
||||
.. _sec-api-datamodel-printer-tempdata:
|
||||
|
||||
Temperature Data
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``actual``
|
||||
- 1
|
||||
- Number
|
||||
- Current temperature
|
||||
* - ``target``
|
||||
- 1
|
||||
- Number
|
||||
- Target temperature, may be ``null`` if no target temperature is set.
|
||||
* - ``offset``
|
||||
- 0..1
|
||||
- Number
|
||||
- Currently configured temperature offset to apply, will be left out for historic temperature information.
|
||||
|
||||
.. _sec-api-datamodel-printer-temphistory:
|
||||
|
||||
Historic Temperature Data Point
|
||||
-------------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``time``
|
||||
- 1
|
||||
- Unix Timestamp
|
||||
- Timestamp of this data point
|
||||
* - ``tool{n}``
|
||||
- 0..*
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Temperature stats for tool *n*. Enumeration starts at 0 for the first tool. Not included if querying only
|
||||
bed state.
|
||||
* - ``bed``
|
||||
- 0..*
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Temperature stats for the printer's heated bed. Not included if querying only tool state.
|
||||
|
||||
.. _sec-api-datamodel-printer-tempoffset:
|
||||
|
||||
Temperature offset
|
||||
------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``tool{n}``
|
||||
- 0..1
|
||||
- Number
|
||||
- Temperature offset for tool *n*. Enumeration starts at 0 for the first tool.
|
||||
* - ``bed``
|
||||
- 0..1
|
||||
- Number
|
||||
- Temperature offset for the printer's heated bed.
|
||||
|
||||
|
||||
.. _sec-api-datamodel-jobs:
|
||||
|
||||
Job related
|
||||
===========
|
||||
|
||||
.. _sec-api-datamodel-jobs-job:
|
||||
|
||||
Job information
|
||||
---------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``file``
|
||||
- 1
|
||||
- :ref:`File information (abridged) <sec-api-datamodel-files-file>`
|
||||
- The file that is the target of the current print job
|
||||
* - ``estimatedPrintTime``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The estimated print time for the file, in seconds.
|
||||
* - ``lastPrintTime``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The print time of the last print of the file, in seconds.
|
||||
* - ``filament``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the estimated filament usage of the print job
|
||||
* - ``filament.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- Length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- Volume of filament used, in cm³
|
||||
|
||||
.. _sec-api-datamodel-jobs-progress:
|
||||
|
||||
Progress information
|
||||
--------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``completion``
|
||||
- 1
|
||||
- Float
|
||||
- Percentage of completion of the current print job
|
||||
* - ``filepos``
|
||||
- 1
|
||||
- Integer
|
||||
- Current position in the file being printed, in bytes from the beginning
|
||||
* - ``printTime``
|
||||
- 1
|
||||
- Integer
|
||||
- Time already spent printing, in seconds
|
||||
* - ``printTimeLeft``
|
||||
- 1
|
||||
- Integer
|
||||
- Estimate of time left to print, in seconds
|
||||
|
||||
.. _sec-api-datamodel-files:
|
||||
|
||||
File related
|
||||
============
|
||||
|
||||
.. _sec-api-datamodel-files-file:
|
||||
|
||||
File information
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file
|
||||
* - ``size``
|
||||
- 0..1
|
||||
- Number
|
||||
- The size of the file in bytes. Only available for ``local`` files.
|
||||
* - ``date``
|
||||
- 0..1
|
||||
- Unix timestamp
|
||||
- The timestamp when this file was uploaded. Only available for ``local`` files.
|
||||
* - ``origin``
|
||||
- 1
|
||||
- String, either ``local`` or ``sdcard``
|
||||
- The origin of the file, ``local`` when stored in OctoPrint's ``uploads`` folder, ``sdcard`` when stored on the
|
||||
printer's SD card (if available)
|
||||
* - ``refs``
|
||||
- 0..1
|
||||
- :ref:`sec-api-datamodel-files-ref`
|
||||
- References relevant to this file, left out in abridged version
|
||||
* - ``gcodeAnalysis``
|
||||
- 0..1
|
||||
- :ref:`GCODE analysis information <sec-api-datamodel-files-gcodeanalysis>`
|
||||
- Information from the analysis of the GCODE file, if available. Left out in abridged version.
|
||||
* - ``prints``
|
||||
- 0..1
|
||||
- :ref:`Print history <sec-api-datamodel-files-prints>`
|
||||
- Information regarding prints of this file, if available. Left out in abridged version.
|
||||
|
||||
.. _sec-api-datamodel-files-gcodeanalysis:
|
||||
|
||||
GCODE analysis information
|
||||
--------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``estimatedPrintTime``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The estimated print time of the file, in seconds
|
||||
* - ``filament``
|
||||
- 0..1
|
||||
- Object
|
||||
- The estimated usage of filament
|
||||
* - ``filament.length``
|
||||
- 0..1
|
||||
- Integer
|
||||
- The length of filament used, in mm
|
||||
* - ``filament.volume``
|
||||
- 0..1
|
||||
- Float
|
||||
- The volume of filament used, in cm³
|
||||
|
||||
|
||||
.. _sec-api-datamodel-files-prints:
|
||||
|
||||
Print history
|
||||
-------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``failure``
|
||||
- 1
|
||||
- Number
|
||||
- The number of failed prints on record for the file
|
||||
* - ``success``
|
||||
- 1
|
||||
- Number
|
||||
- The number of successful prints on record for the file
|
||||
* - ``last``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information regarding the last print on record for the file
|
||||
* - ``last.date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- Timestamp when this file was printed last
|
||||
* - ``last.success``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the last print on record was a success (``true``) or not (``false``)
|
||||
|
||||
.. _sec-api-datamodel-files-ref:
|
||||
|
||||
References
|
||||
----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``resource``
|
||||
- 1
|
||||
- URL
|
||||
- The resource that represents the file (e.g. for issuing commands to or for deleting)
|
||||
* - ``download``
|
||||
- 0..1
|
||||
- URL
|
||||
- The download URL for the file
|
||||
* - ``model``
|
||||
- 0..1
|
||||
- URL
|
||||
- The model from which this file was generated (e.g. an STL, currently not used)
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
.. _sec-api-fileops:
|
||||
|
||||
***************
|
||||
File operations
|
||||
***************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-fileops-retrieveall:
|
||||
|
||||
Retrieve all files
|
||||
==================
|
||||
|
||||
.. http:get:: /api/files
|
||||
|
||||
Retrieve information regarding all files currently available and regarding the disk space still available
|
||||
locally in the system.
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "whistle_.gco",
|
||||
"origin": "sdcard",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-fileops-retrievelocation:
|
||||
|
||||
Retrieve files from specific location
|
||||
=====================================
|
||||
|
||||
.. http:get:: /api/files/(string:location)
|
||||
|
||||
Retrieve information regarding the files currently available on the selected `location` and -- if targeting
|
||||
the ``local`` location -- regarding the disk space still available locally in the system.
|
||||
|
||||
Returns a :ref:`Retrieve response <sec-api-fileops-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example**:
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files/local HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files": [
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": "3.2GB"
|
||||
}
|
||||
|
||||
:param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are
|
||||
supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard``
|
||||
referring to files stored on the printer's SD card (if available).
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If `location` is neither ``local`` nor ``sdcard``
|
||||
|
||||
.. _sec-api-fileops-uploadfile:
|
||||
|
||||
Upload file
|
||||
===========
|
||||
|
||||
.. http:post:: /api/files/(string:location)
|
||||
|
||||
Upload a file to the selected `location`.
|
||||
|
||||
Other than most of the other requests on OctoPrint's API which are expected as JSON, this request is expected as
|
||||
``Content-Type: multipart/form-data`` due to the included file upload.
|
||||
|
||||
Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded
|
||||
file and an :ref:`Upload Response <sec-api-fileops-datamodel-uploadresponse>` as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/sdcard HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode"
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
;Generated with Cura_SteamEngine 13.11.2
|
||||
M109 T0 S220.000000
|
||||
T0
|
||||
;Sliced at: Wed 11-12-2013 16:53:12
|
||||
;Basic settings: Layer height: 0.2 Walls: 0.8 Fill: 20
|
||||
;Print time: #P_TIME#
|
||||
;Filament used: #F_AMNT#m #F_WGHT#g
|
||||
;Filament cost: #F_COST#
|
||||
;M190 S70 ;Uncomment to add your own bed temperature line
|
||||
;M109 S220 ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
...
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="select"
|
||||
|
||||
true
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC
|
||||
Content-Disposition: form-data; name="print"
|
||||
|
||||
true
|
||||
------WebKitFormBoundaryDeC2E3iWbTv1PwMC--
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
Location: http://example.com/api/files/sdcard/whistle_.gcode
|
||||
|
||||
{
|
||||
"files": {
|
||||
"local": {
|
||||
"name": "whistle_v2.gcode",
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
}
|
||||
},
|
||||
"sdcard": {
|
||||
"name": "whistle_.gco",
|
||||
"origin": "sdcard",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/sdcard/whistle_.gco"
|
||||
}
|
||||
}
|
||||
},
|
||||
"done": true
|
||||
}
|
||||
|
||||
:param location: The target location to which to upload the file. Currently only ``local`` and ``sdcard`` are supported
|
||||
here, with ``local`` referring to OctoPrint's ``uploads`` folder and ``sdcard`` referring to
|
||||
the printer's SD card. If an upload targets the SD card, it will also be stored locally first.
|
||||
:form file: The file to upload, including a valid ``filename``.
|
||||
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
|
||||
to ``false``.
|
||||
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, `select`
|
||||
is implicitely ``true`` as well. Optional, defaults to ``false``.
|
||||
:statuscode 201: No error
|
||||
:statuscode 400: If no `file` is included in the request, or the request is otherwise invalid.
|
||||
:statuscode 404: If `location` is neither ``local`` nor ``sdcard`` or trying to upload to SD card and SD card support
|
||||
is disabled
|
||||
:statuscode 409: If the upload of the file would override the file that is currently being printed or if an upload
|
||||
to SD card was requested and the printer is either not operational or currently busy with a print job.
|
||||
:statuscode 415: If the file is neither a ``gcode`` nor an ``stl`` file (or it is an ``stl`` file but slicing support
|
||||
is disabled)
|
||||
:statuscode 500: If the upload failed internally
|
||||
|
||||
.. _sec-api-fileops-retrievefileinfo:
|
||||
|
||||
Retrieve a specific file's information
|
||||
======================================
|
||||
|
||||
.. http:get:: /api/files/(string:location)/(path:filename)
|
||||
|
||||
Retrieves the selected file's information.
|
||||
|
||||
If the file is unknown, a :http:statuscode:`404` is returned.
|
||||
|
||||
On success, a :http:statuscode:`200` is returned, with a :ref:`file information item <sec-api-datamodel-files-file>`
|
||||
as the response body.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "whistle_v2.gcode",
|
||||
"size": 1468987,
|
||||
"date": 1378847754,
|
||||
"origin": "local",
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/files/local/whistle_v2.gcode",
|
||||
"download": "http://example.com/downloads/files/local/whistle_v2.gcode"
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"estimatedPrintTime": 1188,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"print": {
|
||||
"failure": 4,
|
||||
"success": 23,
|
||||
"last": {
|
||||
"date": 1387144346,
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:param location: The location of the file for which to retrieve the information, either ``local`` or ``sdcard``.
|
||||
:param filename: The filename of the file for which to retrieve the information
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard``, ``sdcard`` but SD card support is disabled or the
|
||||
requested file was not found
|
||||
|
||||
.. _sec-api-fileops-filecommand:
|
||||
|
||||
Issue a file command
|
||||
====================
|
||||
|
||||
.. http:post:: /api/files/(string:target)/(path:filename)
|
||||
|
||||
Issue a file command to an existing file. Currently supported commands are:
|
||||
|
||||
select
|
||||
Selects a file for printing. Additional parameters are:
|
||||
|
||||
* ``print``: Optional, if set to ``true`` the file will start printing directly after selection. If the printer
|
||||
is not operational when this parameter is present and set to ``true``, the request will fail with a response
|
||||
of ``409 Conflict``.
|
||||
|
||||
slice
|
||||
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
|
||||
after the response has been sent back to the client. Additional parameters are:
|
||||
|
||||
* ``slicer``: The slicing engine to use, defaults to ``cura`` if not set, which is also the only supported slicer right now.
|
||||
* ``gcode``: Name of the GCODE file to generated, in the same location as the STL file. Defaults to the STL file name
|
||||
with extension ``.gco`` if not set.
|
||||
* ``position``: Position of the object-to-slice's center on the print bed. A dictionary containing both ``x`` and ``y``
|
||||
coordinate in mm is expected
|
||||
* ``printerProfile``: Name of the printer profile to use, if not set the default printer profile will be used.
|
||||
* ``profile``: Name of the slicing profile to use, if not set the default slicing profile of the slicer will be used.
|
||||
* ``profile.*``: Override parameters, the ``profile.`` prefix will be stripped and the matching profile key will
|
||||
be overridden with the supplied value. Use this if you want to specify things that change often like a different
|
||||
temperature, filament diameter or infill percentage. Profile keys are slicer specific.
|
||||
* ``select``: Optional, if set to ``true`` the file be selected for printing right after the slicing has finished. If the
|
||||
printer is not operational or already printing when this parameter is present and set to ``true``, the request will
|
||||
fail with a response of ``409 Conflict``
|
||||
* ``print``: Optional, if set to ``true`` the file be selected and start printing right after the slicing has finished.
|
||||
If the printer is not operational or already printing when this parameter is present and set to ``true``, the request
|
||||
will fail with a response of ``409 Conflict``. Note that if this parameter is set, the parameter ``select`` does not
|
||||
need to be set, it is automatically assumed to be ``true`` too, otherwise no printing would be possible.
|
||||
|
||||
If consecutive slicing calls are made targeting the same GCODE filename (that also holds true if the default is used),
|
||||
the slicing job already running in the background will be cancelled before the new one is started. Note that this will
|
||||
also mean that if it was supposed to be directly selected and start printing after the slicing finished, this will not
|
||||
take place anymore and whether this will happen with the new sliced file depends entirely on the new request!
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned, unless specified otherwise.
|
||||
|
||||
**Example Select Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "select",
|
||||
"print": true
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Slice Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/files/local/some_model.stl HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "slice",
|
||||
"slicer": "cura",
|
||||
"gcode": "some_model.first_try.gcode",
|
||||
"printerProfile": "my_custom_reprap",
|
||||
"profile": "high_quality",
|
||||
"profile.infill": 75,
|
||||
"profile.fill_density": 15,
|
||||
"position": {"x": 100, "y": 100},
|
||||
"print": true
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 202 Accepted
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"origin": "local",
|
||||
"name": "some_model.first_try.gcode",
|
||||
"refs": {
|
||||
"download": "http://example.com/downloads/files/local/some_model.first_try.gcode",
|
||||
"resource": "http://example.com/api/files/local/some_model.first_try.gcode"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
|
||||
folder) or ``sdcard`` for the printer's SD card (if available)
|
||||
:param filename: The filename of the file for which to issue the command
|
||||
:json string command: The command to issue for the file, currently only ``select`` is supported
|
||||
:json boolean print: ``select`` and ``slice`` command: Optional, whether to start printing the file directly after selection
|
||||
or slicing, defaults to ``false``.
|
||||
:json string slicer: ``slice`` command: The slicer to use, defaults to the default slicer.
|
||||
:json string gcode: ``slice`` command: The name of the gcode file to create, defaults to the targeted stl's file name
|
||||
with its extension changed to ``.gco`` (e.g. "test.stl" will be sliced to "test.gco" if not specified
|
||||
otherwise)
|
||||
:json string profile: ``slice`` command: The slicing profile to use, defaults to the selected slicer's default profile.
|
||||
:json string profile.*: ``slice`` command: Overrides for the selected slicing profile, e.g. to specify a different temperature
|
||||
or filament diameter.
|
||||
:json string printerProfile: ``slice`` command: The printer profile to use, defaults to the default printer profile.
|
||||
:json boolean select: ``slice`` command: Optional, whether to select the file for printing directly after slicing,
|
||||
defaults to ``false``
|
||||
:statuscode 200: No error for a ``select`` command.
|
||||
:statuscode 202: No error for a ``slice`` command.
|
||||
:statuscode 400: If the ``command`` is unknown or the request is otherwise invalid
|
||||
:statuscode 415: If a ``slice`` command was issued against something other than an STL file.
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found
|
||||
:statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational or
|
||||
if a file to be sliced is supposed to be selected or start printing directly but the printer
|
||||
is not operational or already printing.
|
||||
|
||||
.. _sec-api-fileops-delete:
|
||||
|
||||
Delete file
|
||||
===========
|
||||
|
||||
.. http:delete:: /api/files/(string:target)/(path:filename)
|
||||
|
||||
Delete the selected `filename` on the selected `target`.
|
||||
|
||||
If the file to be deleted is currently being printed, a :http:statuscode:`409` will be returned.
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
DELETE /api/files/local/whistle_v2.gcode HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
|
||||
folder) or ``sdcard`` for the printer's SD card (if available)
|
||||
:param filename: The filename of the file to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found
|
||||
:statuscode 409: If the file to be deleted is currently being printed
|
||||
|
||||
.. _sec-api-fileops-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-fileops-datamodel-retrieveresponse:
|
||||
|
||||
Retrieve response
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
|
||||
- The list of requested files. Might be an empty list if no files are available
|
||||
* - ``free``
|
||||
- 0..1
|
||||
- String
|
||||
- The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``uploads`` folder). Only
|
||||
returned if file list was requested for origin ``local`` or all origins.
|
||||
|
||||
.. _sec-api-fileops-datamodel-uploadresponse:
|
||||
|
||||
Upload response
|
||||
---------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 1
|
||||
- Object
|
||||
- Abridged information regarding the file that was just uploaded. If only uploaded to ``local`` this will only
|
||||
contain the ``local`` property. If uploaded to SD card, this will contain both ``local`` and ``sdcard`` properties.
|
||||
* - ``files.local``
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-files-file`
|
||||
- The information regarding the file that was just uploaded to the local storage (only the fields ``name``,
|
||||
``origin`` and ``refs`` will be set).
|
||||
* - ``files.sdcard``
|
||||
- 0..1
|
||||
- :ref:`sec-api-datamodel-files-file`
|
||||
- The information regarding the file that was just uploaded to the printer's SD card (only the fields ``name``,
|
||||
``origin`` and ``refs`` will be set).
|
||||
* - ``done``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the file processing after upload has already finished (``true``) or not, e.g. due to first needing
|
||||
to perform a slicing step (``false``). Clients may use this information to direct progress displays related to
|
||||
the upload.
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
.. _sec-api-general:
|
||||
|
||||
*******************
|
||||
General information
|
||||
*******************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-general-authorization:
|
||||
|
||||
Authorization
|
||||
=============
|
||||
|
||||
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
|
||||
configured one, a user specific one if "Access Control" is enabled or an ref:`App Session Key <sec-api-apps-sessionkey>`.
|
||||
Users are able to generate and revoke their custom API key via the "Change password" dialog.
|
||||
|
||||
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
|
||||
|
||||
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/files?apikey=abcdef... HTTP/1.1
|
||||
Host: example.com
|
||||
|
||||
Please be advised that clients should use the header field variant if at all possible.
|
||||
|
||||
.. _fig-api-general-globalapikey:
|
||||
.. figure:: ../images/settings-global-api-key.png
|
||||
:align: center
|
||||
:alt: Global API key in the API settings
|
||||
|
||||
The global API key can be found in the "API" settings
|
||||
|
||||
.. _fig-api-general-userapikey:
|
||||
.. figure:: ../images/settings-user-api-key.png
|
||||
:align: center
|
||||
:alt: User specific API key location in user list
|
||||
|
||||
The user list in the "Access Control" settings shows the API key for users (if available)
|
||||
|
||||
.. _fig-api-general-changepassword:
|
||||
.. figure:: ../images/change-password-api-key.png
|
||||
:align: center
|
||||
:alt: API key options in "Change password" dialog
|
||||
|
||||
The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here.
|
||||
|
||||
.. note::
|
||||
OctoPrint's web interface uses a custom API key that is freshly generated on every server start. This key is not
|
||||
intended to be used by any other client and would not be very useful in any case, since it basically represents
|
||||
a completely anonymous client.
|
||||
|
||||
.. _sec-api-general-contenttype:
|
||||
|
||||
Content Type
|
||||
============
|
||||
|
||||
If not otherwise stated OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``.
|
||||
|
||||
.. _sec-api-general-encoding:
|
||||
|
||||
Encoding
|
||||
========
|
||||
|
||||
OctoPrint uses UTF-8 as charset.
|
||||
|
||||
.. _sec-api-cross-origin:
|
||||
|
||||
Cross-origin requests
|
||||
=====================
|
||||
|
||||
To make use of the OctoPrint API from websites other than the OctoPrint web interface,
|
||||
cross-origin resource sharing (`CORS <http://en.wikipedia.org/wiki/Cross-origin_resource_sharing>`_) must be enabled.
|
||||
This is the case even when the website in question is served from a different port on the same machine and on localhost.
|
||||
|
||||
To enable this feature, set the ``allowCrossOrigin`` key of the ``api`` section in ``config.yml`` to ``true`` or
|
||||
check the corresponding checkbox in the API settings dialog.
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
api:
|
||||
enabled: true
|
||||
key: ...
|
||||
allowCrossOrigin: true
|
||||
|
||||
.. _fig-api-general-apicors:
|
||||
.. figure:: ../images/settings-api-cors.png
|
||||
:align: center
|
||||
:alt: CORS configuration in the API settings
|
||||
|
||||
Support for CORS can be enabled in the "API" settings
|
||||
|
||||
.. note::
|
||||
This means any browser page can send requests to the OctoPrint API. Authorization is still required however.
|
||||
|
||||
If CORS is not enabled you will get errors like the following::
|
||||
|
||||
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
|
||||
header is present on the requested resource.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
.. _sec-api:
|
||||
|
||||
#################
|
||||
API Documentation
|
||||
#################
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
general.rst
|
||||
version.rst
|
||||
apps.rst
|
||||
fileops.rst
|
||||
connection.rst
|
||||
printer.rst
|
||||
printerprofiles.rst
|
||||
job.rst
|
||||
logs.rst
|
||||
slicing.rst
|
||||
push.rst
|
||||
datamodel.rst
|
||||
@@ -0,0 +1,183 @@
|
||||
.. _sec-api-jobs:
|
||||
|
||||
**************
|
||||
Job operations
|
||||
**************
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-jobs-command:
|
||||
|
||||
Issue a job command
|
||||
===================
|
||||
|
||||
.. http:post:: /api/job
|
||||
|
||||
Job commands allow starting, pausing and cancelling print jobs. Available commands are:
|
||||
|
||||
start
|
||||
Starts the print of the currently selected file. For selecting a file, see :ref:`Issue a file command <sec-api-fileops-filecommand>`.
|
||||
If a print job is already active, a :http:statuscode:`409` will be returned.
|
||||
|
||||
restart
|
||||
Restart the print of the currently selected file from the beginning. There must be an active print job for this to work
|
||||
and the print job must currently be paused. If either is not the case, a :http:statuscode:`409` will be returned.
|
||||
|
||||
pause
|
||||
Pauses/unpauses the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
|
||||
will be returned.
|
||||
|
||||
cancel
|
||||
Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409`
|
||||
will be returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Start Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "start"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Restart Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "restart"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Pause Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "pause"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Cancel Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "cancel"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``start``, ``restart``, ``pause`` or ``cancel``
|
||||
:statuscode 204: No error
|
||||
:statuscode 409: If the printer is not operational or the current print job state does not match the preconditions
|
||||
for the command.
|
||||
|
||||
.. _sec-api-job-information:
|
||||
|
||||
Retrieve information about the current job
|
||||
==========================================
|
||||
|
||||
.. http:get:: /api/job
|
||||
|
||||
Retrieve information about the current job (if there is one).
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"job": {
|
||||
"file": {
|
||||
"name": "whistle_v2.gcode",
|
||||
"origin": "local",
|
||||
"size": 1468987,
|
||||
"date": 1378847754
|
||||
},
|
||||
"estimatedPrintTime": 8811,
|
||||
"filament": {
|
||||
"length": 810,
|
||||
"volume": 5.36
|
||||
}
|
||||
},
|
||||
"progress": {
|
||||
"completion": 0.2298468264184775,
|
||||
"filepos": 337942,
|
||||
"printTime": 276,
|
||||
"printTimeLeft": 912
|
||||
}
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-job-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-job-datamodel-response:
|
||||
|
||||
Job information response
|
||||
------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``job``
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-jobs-job`
|
||||
- Information regarding the target of the current print job
|
||||
* - ``progress``
|
||||
- 1
|
||||
- :ref:`sec-api-datamodel-jobs-progress`
|
||||
- Information regarding the progress of the current print job
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
.. _sec-api-logs:
|
||||
|
||||
*******************
|
||||
Log file management
|
||||
*******************
|
||||
|
||||
.. note::
|
||||
|
||||
All log file management operations require admin rights.
|
||||
|
||||
.. contents::
|
||||
|
||||
.. _sec-api-logs-list:
|
||||
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:post:: /api/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
Returns a :ref:`Logfile Retrieve response <sec-api-logs-datamodel-retrieveresponse>`.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/logs HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"files" : [
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "octoprint.log",
|
||||
"size" : 43712,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/octoprint.log",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1392628936,
|
||||
"name" : "octoprint.log.2014-02-17",
|
||||
"size" : 13205,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/octoprint.log.2014-02-17",
|
||||
"download": "http://example.com/downloads/logs/octoprint.log.2014-02-17"
|
||||
}
|
||||
},
|
||||
{
|
||||
"date" : 1393158814,
|
||||
"name" : "serial.log",
|
||||
"size" : 1798419,
|
||||
"refs": {
|
||||
"resource": "http://example.com/api/logs/serial.log",
|
||||
"download": "http://example.com/downloads/logs/serial.log"
|
||||
}
|
||||
}
|
||||
],
|
||||
"free": 12237201408
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
|
||||
.. _sec-api-logs-delete:
|
||||
|
||||
Delete a specific logfile
|
||||
=========================
|
||||
|
||||
.. http:delete:: /api/logs/(path:filename)
|
||||
|
||||
Delete the selected log file with name `filename`.
|
||||
|
||||
Returns a :http:statuscode:`204` after successful deletion.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
DELETE /api/logs/octoprint.log.2014-02-17 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
:param filename: The filename of the log file to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 403: If the given API token did not have admin rights associated with it
|
||||
:statuscode 404: If the file was not found
|
||||
|
||||
.. _sec-api-logs-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-logs-datamodel-retrieveresponse:
|
||||
|
||||
Logfile Retrieve Response
|
||||
-------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``files``
|
||||
- 0..*
|
||||
- Array of :ref:`File information items <sec-api-logs-datamodel-fileinfo>`
|
||||
- The list of requested files. Might be an empty list if no files are available
|
||||
* - ``free``
|
||||
- 1
|
||||
- String
|
||||
- The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder).
|
||||
|
||||
.. _sec-api-logs-datamodel-fileinfo:
|
||||
|
||||
File information
|
||||
----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``name``
|
||||
- 1
|
||||
- String
|
||||
- The name of the file
|
||||
* - ``size``
|
||||
- 1
|
||||
- Number
|
||||
- The size of the file in bytes.
|
||||
* - ``date``
|
||||
- 1
|
||||
- Unix timestamp
|
||||
- The timestamp when this file was last modified.
|
||||
* - ``refs``
|
||||
- 1
|
||||
- :ref:`sec-api-logs-datamodel-ref`
|
||||
- References relevant to this file
|
||||
|
||||
.. _sec-api-logs-datamodel-ref:
|
||||
|
||||
References
|
||||
----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``resource``
|
||||
- 1
|
||||
- URL
|
||||
- The resource that represents the file (e.g. for deleting)
|
||||
* - ``download``
|
||||
- 1
|
||||
- URL
|
||||
- The download URL for the file
|
||||
@@ -0,0 +1,909 @@
|
||||
.. _sec-api-printer:
|
||||
|
||||
******************
|
||||
Printer operations
|
||||
******************
|
||||
|
||||
.. warning::
|
||||
|
||||
This part of the API is still heavily in development, especially anything that has to do with temperature control.
|
||||
If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when
|
||||
something changes.
|
||||
|
||||
.. contents::
|
||||
|
||||
Printer control is mostly achieved through the use of commands, issued to resources reflecting components of the
|
||||
printer. OctoPrint currently knows the following components:
|
||||
|
||||
Print head
|
||||
Print head commands allow jogging and homing the print head in all three axes. Querying the resource is currently
|
||||
not supported.
|
||||
See :ref:`sec-api-printer-printheadcommand`.
|
||||
Tool
|
||||
Tool commands allow setting the temperature and temperature offsets for the printer's hotends/tools. Querying the
|
||||
corresponding resource returns temperature information including an optional history.
|
||||
See :ref:`sec-api-printer-toolcommand`.
|
||||
Bed
|
||||
Bed commands allow setting the temperature and temperature offset for the printer's heated bed. Querying the
|
||||
corresponding resource returns temperature information including an optional history.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
corresponding resource returns the current SD card state.
|
||||
See :ref:`sec-api-printer-sdcommand`.
|
||||
|
||||
Besides that, OctoPrint also provides a :ref:`full state report of the printer <sec-api-printer-state>`.
|
||||
|
||||
.. _sec-api-printer-state:
|
||||
|
||||
Retrieve the current printer state
|
||||
==================================
|
||||
|
||||
.. http:get:: /api/printer
|
||||
|
||||
Retrieves the current state of the printer. Returned information includes:
|
||||
|
||||
* temperature information (see also :ref:`Retrieve the current tool state <sec-api-printer-toolstate>` and
|
||||
:ref:`Retrieve the current bed state <sec-api-printer-bedstate>`)
|
||||
* sd state (if available, see also :ref:`Retrieve the current SD state <sec-api-printer-sdstate>`)
|
||||
* general printer state
|
||||
|
||||
Temperature information can also be made to include the printer's temperature history by supplying the ``history``
|
||||
query parameter. The amount of data points to return here can be limited using the ``limit`` query parameter.
|
||||
|
||||
Clients can specific a list of attributes to not return in the response (e.g. if they don't need it) via the
|
||||
``exclude`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a :ref:`Full State Response <sec-api-printer-datamodel-fullstate>` in the
|
||||
body upon success.
|
||||
|
||||
**Example 1**
|
||||
|
||||
Include temperature history data, but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"temperature": {
|
||||
"tool0": {
|
||||
"actual": 214.8821,
|
||||
"target": 220.0,
|
||||
"offset": 0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.3,
|
||||
"target": null,
|
||||
"offset": 0
|
||||
},
|
||||
"bed": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0,
|
||||
"offset": 5
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"tool0": {
|
||||
"actual": 214.8821,
|
||||
"target": 220.0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.3,
|
||||
"target": null
|
||||
},
|
||||
"bed": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"tool0": {
|
||||
"actual": 212.32,
|
||||
"target": 220.0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.1,
|
||||
"target": null
|
||||
},
|
||||
"bed": {
|
||||
"actual": 49.1123,
|
||||
"target": 70.0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"sd": {
|
||||
"ready": true
|
||||
},
|
||||
"state": {
|
||||
"text": "Operational",
|
||||
"flags": {
|
||||
"operational": true,
|
||||
"paused": false,
|
||||
"printing": false,
|
||||
"sdReady": true,
|
||||
"error": false,
|
||||
"ready": true,
|
||||
"closedOrError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
**Example 2**
|
||||
|
||||
Exclude temperature and sd data.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer?exclude=temperature,sd HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"state": {
|
||||
"text": "Operational",
|
||||
"flags": {
|
||||
"operational": true,
|
||||
"paused": false,
|
||||
"printing": false,
|
||||
"sdReady": true,
|
||||
"error": false,
|
||||
"ready": true,
|
||||
"closedOrError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:query exclude: An optional comma-separated list of fields to exclude from the response (e.g. if not needed by
|
||||
the client). Valid values to supply here are ``temperature``, ``sd`` and ``state``.
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational.
|
||||
|
||||
.. _sec-api-printer-printheadcommand:
|
||||
|
||||
Issue a print head command
|
||||
==========================
|
||||
|
||||
.. http:post:: /api/printer/printhead
|
||||
|
||||
Print head commands allow jogging and homing the print head in all three axes. Available commands are:
|
||||
|
||||
jog
|
||||
Jogs the print head (relatively) by a defined amount in one or more axes. Additional parameters are:
|
||||
|
||||
* ``x``: Optional. Amount to jog print head on x axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
* ``y``: Optional. Amount to jog print head on y axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
* ``z``: Optional. Amount to jog print head on z axis, must be a valid number corresponding to the distance to travel in mm.
|
||||
|
||||
home
|
||||
Homes the print head in all of the given axes. Additional parameters are:
|
||||
|
||||
* ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a
|
||||
:http:statuscode:`409` is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Jog Request**
|
||||
|
||||
Jog the print head by 10mm in X, -5mm in Y and 0.02mm in Z.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "jog",
|
||||
"x": 10,
|
||||
"y": -5,
|
||||
"z": 0.02
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Home Request**
|
||||
|
||||
Home the X and Y axes.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/printhead HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "home",
|
||||
"axes": ["x", "y"]
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``jog`` or ``home``.
|
||||
:json number x: ``jog`` command: The amount to travel on the X axis in mm.
|
||||
:json number y: ``jog`` command: The amount to travel on the Y axis in mm.
|
||||
:json number z: ``jog`` command: The amount to travel on the Z axis in mm.
|
||||
:json array axes: ``home`` command: The axes which to home, valid values are one or more of ``x``, ``y`` and ``z``.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid
|
||||
request.
|
||||
:statuscode 409: If the printer is not operational or currently printing.
|
||||
|
||||
.. _sec-api-printer-toolcommand:
|
||||
|
||||
Issue a tool command
|
||||
====================
|
||||
|
||||
.. http:post:: /api/printer/tool
|
||||
|
||||
Tool commands allow setting the temperature and temperature offsets for the printer's tools (hotends), selecting
|
||||
the current tool and extruding/retracting from the currently selected tool. Available commands are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
|
||||
* ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the
|
||||
tool's index starting with 0.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
|
||||
* ``offsets``: Offset(s) to set, properties must match the format ``tool{n}`` with ``n`` being the tool's index
|
||||
starting with 0.
|
||||
|
||||
select
|
||||
Selects the printer's current tool. Additional parameters:
|
||||
|
||||
* ``tool``: Tool to select, format ``tool{n}`` with ``n`` being the tool's index starting with 0.
|
||||
|
||||
extrude
|
||||
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
|
||||
|
||||
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
|
||||
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and
|
||||
``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's first hotend to 220°C and the printer's second extruder to 205°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "target",
|
||||
"targets": {
|
||||
"tool0": 220,
|
||||
"tool1": 205
|
||||
}
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the offset for temperatures on ``tool0`` to +10°C and on ``tool1`` to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offsets": {
|
||||
"tool0": 10,
|
||||
"tool1": -5
|
||||
}
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Tool Select Request**
|
||||
|
||||
Select the second hotend of the printer for any following ``extrude`` commands.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "select",
|
||||
"tool": "tool1"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Extrude Request**
|
||||
|
||||
Extrude 5mm on the currently selected tool.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "extrude",
|
||||
"amount": 5
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Retract Request**
|
||||
|
||||
Retract 3mm of filament on the currently selected tool.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/tool HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "extrude",
|
||||
"amount": -3
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``.
|
||||
:json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``.
|
||||
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``.
|
||||
:json object tool: ``select`` command: The tool to select, value has to match the format ``tool{n}``.
|
||||
:json object amount: ``extrude`` command: The amount of filament to extrude from the currently selected tool.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``targets`` or ``offsets`` contains a property or ``tool`` contains a value not matching the format
|
||||
``tool{n}``, the target/offset temperature or extrusion amount is not a valid number or outside of
|
||||
the supported range, or if the request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational or -- in case of ``select`` or ``extrude`` -- currently printing.
|
||||
|
||||
.. _sec-api-printer-toolstate:
|
||||
|
||||
Retrieve the current tool state
|
||||
===============================
|
||||
|
||||
.. http:get:: /api/printer/tool
|
||||
|
||||
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
|
||||
timestamp) for all of the printer's available tools.
|
||||
|
||||
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
|
||||
amount of returned history data points can be limited using the ``limit`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Query the tool temperature data and also include the temperature history but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/tool?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"tool0": {
|
||||
"actual": 214.8821,
|
||||
"target": 220.0,
|
||||
"offset": 0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.3,
|
||||
"target": null,
|
||||
"offset": 0
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"tool0": {
|
||||
"actual": 214.8821,
|
||||
"target": 220.0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.3,
|
||||
"target": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"tool0": {
|
||||
"actual": 212.32,
|
||||
"target": 220.0
|
||||
},
|
||||
"tool1": {
|
||||
"actual": 25.1
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational.
|
||||
|
||||
.. _sec-api-printer-bedcommand:
|
||||
|
||||
Issue a bed command
|
||||
===================
|
||||
|
||||
.. http:post:: /api/printer/bed
|
||||
|
||||
Bed commands allow setting the temperature and temperature offsets for the printer's heated bed. Available commands
|
||||
are:
|
||||
|
||||
target
|
||||
Sets the given target temperature on the printer's tools. Additional parameters:
|
||||
|
||||
* ``target``: Target temperature to set.
|
||||
|
||||
offset
|
||||
Sets the given temperature offset on the printer's tools. Additional parameters:
|
||||
|
||||
* ``offset``: Offset to set.
|
||||
|
||||
All of these commands may only be sent if the printer is currently operational. Otherwise a :http:statuscode:`409`
|
||||
is returned.
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated bed to 75°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/bed HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "target",
|
||||
"target": 75
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Offset Temperature Request**
|
||||
|
||||
Set the temperature offset for the heated bed to -5°C.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/bed HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "offset",
|
||||
"offset": -5
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``target`` or ``offset``.
|
||||
:json object target: ``target`` command: The target temperature to set.
|
||||
:json object offset: ``offset`` command: The offset temperature to set.
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational.
|
||||
|
||||
.. _sec-api-printer-bedstate:
|
||||
|
||||
Retrieve the current bed state
|
||||
==============================
|
||||
|
||||
.. http:get:: /api/printer/bed
|
||||
|
||||
Retrieves the current temperature data (actual, target and offset) plus optionally a (limited) history (actual, target,
|
||||
timestamp) for the printer's heated bed.
|
||||
|
||||
It's also possible to retrieve the temperature history by supplying the ``history`` query parameter set to ``true``. The
|
||||
amount of returned history data points can be limited using the ``limit`` query parameter.
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
|
||||
**Example**
|
||||
|
||||
Query the bed temperature data and also include the temperature history but limit it to two entries.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/bed?history=true&limit=2 HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"bed": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0,
|
||||
"offset": 5
|
||||
},
|
||||
"history": [
|
||||
{
|
||||
"time": 1395651928,
|
||||
"bed": {
|
||||
"actual": 50.221,
|
||||
"target": 70.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"time": 1395651926,
|
||||
"bed": {
|
||||
"actual": 49.1123,
|
||||
"target": 70.0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
:query history: If set to ``true`` (or: ``yes``, ``y``, ``1``), history information will be included in the response
|
||||
too. If no ``limit`` parameter is given, all available temperature history data will be returned.
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
Issue an SD command
|
||||
===================
|
||||
|
||||
.. http:post:: /api/printer/sd
|
||||
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available).
|
||||
|
||||
Available commands are:
|
||||
|
||||
init
|
||||
Initializes the printer's SD card, making it available for use. This also includes an initial retrieval of the
|
||||
list of files currently stored on the SD card, so after issueing that command a :ref:`retrieval of the files
|
||||
on SD card <sec-api-fileops-retrievelocation>` will return a successful result.
|
||||
|
||||
.. note::
|
||||
If OctoPrint detects the availability of a SD card on the printer during connection, it will automatically attempt
|
||||
to initialize it.
|
||||
|
||||
refresh
|
||||
Refreshes the list of files stored on the printer's SD card. Will return a :http:statuscode:`409` if the card
|
||||
has not been initialized yet (see the ``init`` command and :ref:`SD state <sec-api-printer-sdstate>`).
|
||||
|
||||
release
|
||||
Releases the SD card from the printer. The reverse operation to ``init``. After issuing this command, the SD
|
||||
card won't be available anymore, hence and operations targeting files stored on it will fail. Will return a :http:statuscode:`409`
|
||||
if the card has not been initialized yet (see the ``init`` command and :ref:`SD state <sec-api-printer-sdstate>`).
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
**Example Init Request**
|
||||
|
||||
Initialize the SD card.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "init"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Refresh Request**
|
||||
|
||||
Refresh the file list of the SD card
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "refresh"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example Release Request**
|
||||
|
||||
Release the SD card
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "release"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: The command to issue, either ``init``, ``refresh`` or ``release``.
|
||||
:statuscode 204: No error
|
||||
:statuscode 409: If a ``refresh`` or ``release`` command is issued but the SD card has not been initialized (e.g.
|
||||
via ``init``.
|
||||
|
||||
.. _sec-api-printer-sdstate:
|
||||
|
||||
Retrieve the current SD state
|
||||
=============================
|
||||
|
||||
.. http:get:: /api/printer/sd
|
||||
|
||||
Retrieves the current state of the printer's SD card. For this request no authentication is needed.
|
||||
|
||||
If SD support has been disabled in OctoPrint's settings, a :http:statuscode:`404` is returned.
|
||||
|
||||
Returns a :http:statuscode:`200` with an :ref:`SD State Response <sec-api-printer-datamodel-sdstate>` in the body
|
||||
upon success.
|
||||
|
||||
**Example**
|
||||
|
||||
Read the current state of the SD card.
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/printer/sd HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"ready": true
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If SD support has been disabled in OctoPrint's config.
|
||||
|
||||
.. _sec-api-printer-arbcommand:
|
||||
|
||||
Send an arbitrary command to the printer
|
||||
========================================
|
||||
|
||||
.. http:post:: /api/printer/command
|
||||
|
||||
Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with
|
||||
or even stop a running print job.
|
||||
|
||||
Expects a :ref:`Arbitrary Command Request <sec-api-printer-datamodel-arbcommand>` as the request's body.
|
||||
|
||||
If successful returns a :http:statuscode:`204` and an empty body.
|
||||
|
||||
**Example for sending a single command**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/command HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"command": "M106"
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
**Example for sending multiple commands**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/printer/command HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
{
|
||||
"commands": [
|
||||
"M18",
|
||||
"M106 S0"
|
||||
]
|
||||
}
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
|
||||
.. _sec-api-printer-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-printer-datamodel-fullstate:
|
||||
|
||||
Full State Response
|
||||
-------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``temperature``
|
||||
- 0..1
|
||||
- :ref:`Temperature State <sec-api-printer-datamodel-temps>`
|
||||
- The printer's temperature state data
|
||||
* - ``sd``
|
||||
- 0..1
|
||||
- :ref:`SD State <sec-api-printer-datamodel-sdstate>`
|
||||
- The printer's sd state data
|
||||
* - ``state``
|
||||
- 0..1
|
||||
- :ref:`Printer State <sec-api-datamodel-printer-state>`
|
||||
- The printer's general state
|
||||
|
||||
.. _sec-api-printer-datamodel-temps:
|
||||
|
||||
Temperature State
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``tool{n}``
|
||||
- 0..*
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Current temperature stats for tool *n*. Enumeration starts at 0 for the first tool. Not included if querying
|
||||
only bed state.
|
||||
* - ``bed``
|
||||
- 0..1
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Current temperature stats for the printer's heated bed. Not included if querying only tool state.
|
||||
* - ``history``
|
||||
- 0..1
|
||||
- List of :ref:`Historic Temperature Datapoint <sec-api-datamodel-printer-temphistory>`
|
||||
- Temperature history
|
||||
|
||||
.. _sec-api-printer-datamodel-sdstate:
|
||||
|
||||
SD State
|
||||
--------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``ready``
|
||||
- 1
|
||||
- Boolean
|
||||
- Whether the SD card has been initialized (``true``) or not (``false``).
|
||||
|
||||
.. _sec-api-printer-datamodel-arbcommand:
|
||||
|
||||
Arbitrary Command Request
|
||||
-------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``command``
|
||||
- 0..1
|
||||
- String
|
||||
- Single command to send to the printer, mutually exclusive with ``commands``.
|
||||
* - ``commands``
|
||||
- 0..*
|
||||
- Array of String
|
||||
- Multiple commands to send to the printer (in the given order), mutually exclusive with ``command``.
|
||||
@@ -0,0 +1,190 @@
|
||||
.. _sec-api-printerprofiles:
|
||||
|
||||
**************************
|
||||
Printer profile operations
|
||||
**************************
|
||||
|
||||
.. contents::
|
||||
|
||||
OctoPrint allows the management of Printer profiles that define a printer's physical properties (such as print volume,
|
||||
whether a heated bed is available, maximum speeds on its axes etc). The data stored within these profiles is used
|
||||
for both slicing and gcode visualization.
|
||||
|
||||
.. _sec-api-printerprofiles-retrieve:
|
||||
|
||||
Retrieve all printer profiles
|
||||
=============================
|
||||
|
||||
.. http:get:: /api/printerprofiles
|
||||
|
||||
.. _sec-api-printerprofiles-add:
|
||||
|
||||
Add a new printer profile
|
||||
=========================
|
||||
|
||||
.. http:post:: /api/printerprofiles
|
||||
|
||||
.. _sec-api-printerporfiles-update:
|
||||
|
||||
Update an existing printer profile
|
||||
==================================
|
||||
|
||||
.. http:patch:: /api/printerprofiles/(string:profile)
|
||||
|
||||
.. _sec-api-printerprofiles-delete:
|
||||
|
||||
Remove an existing printer profile
|
||||
==================================
|
||||
|
||||
.. http:delete:: /api/printerprofiles/(string:profile)
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-printerprofiles-datamodel-profilelist:
|
||||
|
||||
Profile list
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``profiles``
|
||||
- 1
|
||||
- Object
|
||||
- Collection of all printer profiles available in the system
|
||||
* - ``profiles.<profile id>``
|
||||
- 0..1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about a profile stored in the system.
|
||||
|
||||
.. _sec-api-slicing-datamodel-update:
|
||||
|
||||
Add or update request
|
||||
---------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``profiles``
|
||||
- 1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about the profile being added/updated. For adding new profiles, all fields must be populated. For updating
|
||||
and existing profile, only the values to be overwritten need to be supplied.
|
||||
|
||||
.. _sec-api-slicing-datamodel-profile:
|
||||
|
||||
Profile
|
||||
-------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Identifier of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``name``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``color``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The color to associate with this profile (used in the UI's title bar). Valid values are "default", "red", "orange",
|
||||
"yellow", "green", "blue", "black". Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``model``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Printer model of the profile. Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the default profile to be used with new connections (``true``) or not (``false``). Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``current``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the profile currently active. Will always be returned in responses but ignored in save/update
|
||||
requests.
|
||||
* - ``resource``
|
||||
- 0..1
|
||||
- ``URL``
|
||||
- Resource URL of the profile, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``volume``
|
||||
- 0..1
|
||||
- Object
|
||||
- The print volume, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``volume.formFactor``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- The form factor of the printer's bed, valid values are "rectangular" and "circular"
|
||||
* - ``volume.width``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The width of the print volume
|
||||
* - ``volume.depth``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The depth of the print volume
|
||||
* - ``volume.height``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The height of the print volume
|
||||
* - ``heatedBed``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the printer has a heated bed (``true``) or not (``false``)
|
||||
* - ``axes``
|
||||
- 0..1
|
||||
- Object
|
||||
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed
|
||||
and whether this axis is inverted or not.
|
||||
* - ``axes.{axis}.speed``
|
||||
- 0..1
|
||||
- ``int``
|
||||
- Maximum speed of the axis in mm/s.
|
||||
* - ``axes.{axis}.inverted``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether the axis is inverted or not.
|
||||
* - ``extruder``
|
||||
- 0..1
|
||||
- Object
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- 0..1
|
||||
- ``float``
|
||||
- The diameter of the printer's nozzle(s) in mm.
|
||||
* - ``extruder.count``
|
||||
- 0..1
|
||||
- ``int``
|
||||
- Count of extruders on the printer (defaults to 1)
|
||||
* - ``extruder.offsets``
|
||||
- 0..1
|
||||
- Array of ``float`` tuples
|
||||
- Tuple of (x, y) values describing the offsets of the other extruders relative to the first extruder. E.g. for a
|
||||
printer with two extruders, if the second extruder is offset by 20mm in the X and 25mm in the Y direction, this
|
||||
array will read ``[ [0.0, 0.0], [20.0, 25.0] ]``
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
.. _sec-api-push:
|
||||
|
||||
************
|
||||
Push updates
|
||||
************
|
||||
|
||||
.. warning::
|
||||
|
||||
The interface documented here is the status quo that might be changed while the interfaces are streamlined for
|
||||
a more general consumption. If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when
|
||||
something changes.
|
||||
|
||||
.. contents::
|
||||
|
||||
To enable real time information exchange between client and server, OctoPrint uses
|
||||
`SockJS <https://github.com/sockjs/sockjs-protocol>`_ to push
|
||||
status updates, temperature changes etc to connected web interface instances.
|
||||
|
||||
Each pushed message consists of a simple JSON object that follows this basic structure:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"<type>": <payload>
|
||||
}
|
||||
|
||||
``type`` indicates the type of message being pushed to the client, the attached ``payload`` is message specific. The
|
||||
following message types are currently available for usage by 3rd party clients:
|
||||
|
||||
* ``current``: Rate limited general state update, payload contains information about the printer's state, job progress,
|
||||
accumulated temperature points and log lines since last update. OctoPrint will send these updates when new information
|
||||
is available, but not more often than twice per second in order to not flood the client with messages (e.g.
|
||||
during printing). See :ref:`the payload data model <sec-api-push-datamodel-currentandhistory>`.
|
||||
* ``history``: Current state, temperature and log history, sent upon initial connect to get the client up to date. Same
|
||||
payload data model as ``current``, see :ref:`below <sec-api-push-datamodel-currentandhistory>`.
|
||||
* ``event``: Events triggered within OctoPrint, such as e.g. ``PrintFailed`` or ``MovieRenderDone``. Payload is the event
|
||||
type and payload, see :ref:`below <sec-api-push-datamodel-event>`. Sent when an event is triggered internally.
|
||||
* ``slicingProgress``: Progress updates from an active slicing background job, payload contains information about the
|
||||
model being sliced, the target file, the slicer being used and the progress as a percentage.
|
||||
See :ref:`the payload data model <sec-api-push-datamodel-slicingprogress>`.
|
||||
|
||||
Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-push-datamodel-currentandhistory:
|
||||
|
||||
``current`` and ``history`` payload
|
||||
-----------------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``state``
|
||||
- 1
|
||||
- :ref:`State information <sec-api-datamodel-printer-state>`
|
||||
- Information about the current machine state
|
||||
* - ``job``
|
||||
- 1
|
||||
- :ref:`Job information <sec-api-datamodel-jobs-job>`
|
||||
- Information about the currently active print job
|
||||
* - ``progress``
|
||||
- 1
|
||||
- :ref:`Progress information <sec-api-datamodel-jobs-progress>`
|
||||
- Information about the current print/streaming progress
|
||||
* - ``currentZ``
|
||||
- 1
|
||||
- Float
|
||||
- Current height of the Z-Axis (= current height of model) during printing from a local file
|
||||
* - ``offsets``
|
||||
- 0..1
|
||||
- :ref:`Temperature offsets <sec-api-datamodel-printer-tempoffset>`
|
||||
- Currently configured temperature offsets
|
||||
* - ``temps``
|
||||
- 0..*
|
||||
- List of :ref:`Temperature Data Points <sec-api-datamodel-printer-temphistory>`
|
||||
- Temperature data points for plotting
|
||||
* - ``logs``
|
||||
- 0..*
|
||||
- List of String
|
||||
- Lines for the serial communication log (send/receive)
|
||||
* - ``messages``
|
||||
- 0..*
|
||||
- List of String
|
||||
- Lines for the serial communication log (special messages)
|
||||
|
||||
.. _sec-api-push-datamodel-event:
|
||||
|
||||
``event`` payload
|
||||
-----------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``type``
|
||||
- 1
|
||||
- String
|
||||
- Name of the event
|
||||
* - ``payload``
|
||||
- 1
|
||||
- Object
|
||||
- Payload associated with the event
|
||||
|
||||
.. _sec-api-push-datamodel-slicingprogress:
|
||||
|
||||
``slicingProgress`` payload
|
||||
---------------------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``slicer``
|
||||
- 1
|
||||
- String
|
||||
- Name of the slicer used
|
||||
* - ``source_location``
|
||||
- 1
|
||||
- String
|
||||
- Location of the source file being sliced, at the moment either ``local`` or ``sdcard``
|
||||
* - ``source_path``
|
||||
- 1
|
||||
- String
|
||||
- Path of the source file being sliced (e.g. an STL file)
|
||||
* - ``dest_location``
|
||||
- 1
|
||||
- String
|
||||
- Location of the destination file being created, at the moment either ``local`` or ``sdcard``
|
||||
* - ``dest_path``
|
||||
- 1
|
||||
- String
|
||||
- Path of the destination file being sliced (e.g. a GCODE file)
|
||||
* - ``progress``
|
||||
- 1
|
||||
- Number (Float)
|
||||
- Percentage of slicing job already completed
|
||||
@@ -0,0 +1,336 @@
|
||||
.. _sec-api-slicing:
|
||||
|
||||
*******
|
||||
Slicing
|
||||
*******
|
||||
|
||||
.. warning::
|
||||
|
||||
The interface documented here is the status quo that might be changed while the interfaces are streamlined for
|
||||
a more general consumption. If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when
|
||||
something changes.
|
||||
|
||||
.. contents::
|
||||
|
||||
The Slicing API on one hand offers methods for managing slicing profiles stored within OctoPrint, on the other hand
|
||||
it will be extended in the future to also allow for multi extruder slicing (which currently is not possible with the
|
||||
``slice`` command of the :ref:`File operations API <sec-api-fileops-filecommand>` and other things.
|
||||
|
||||
.. _sec-api-slicing-listall:
|
||||
|
||||
List All Slicers and Slicing Profiles
|
||||
=====================================
|
||||
|
||||
.. http:get:: /api/slicing
|
||||
|
||||
Returns a list of all available slicing profiles for all registered slicers in the system.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"cura": {
|
||||
"key": "cura",
|
||||
"displayName": "CuraEngine",
|
||||
"default": true,
|
||||
"profiles": {
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
|
||||
.. _sec-api-slicing-list:
|
||||
|
||||
List Slicing Profiles of a Specific Slicer
|
||||
==========================================
|
||||
|
||||
.. http:get:: /api/slicing/(string:slicer)/profiles
|
||||
|
||||
Returns a list of all available slicing profiles for the requested slicer.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"high_quality": {
|
||||
"key": "high_quality",
|
||||
"displayName": "High Quality",
|
||||
"default": false,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
|
||||
},
|
||||
"medium_quality": {
|
||||
"key": "medium_quality",
|
||||
"displayName": "Medium Quality",
|
||||
"default": true,
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-listspecific:
|
||||
|
||||
Retrieve Specific Profile
|
||||
=========================
|
||||
|
||||
.. http:get:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Retrieves the specified profile from the system.
|
||||
|
||||
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
|
||||
as the body upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
|
||||
"data": {
|
||||
"bottom_layer_speed": 20.0,
|
||||
"bottom_thickness": 0.3,
|
||||
"brim_line_count": 20,
|
||||
"cool_head_lift": false,
|
||||
"cool_min_feedrate": 10.0,
|
||||
"cool_min_layer_time": 5.0,
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to list the available profiles.
|
||||
:param name: The identifying key of the profile to retrieve
|
||||
:statuscode 200: No error
|
||||
:statuscode 404: If the ``slicer`` or the profile was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-add:
|
||||
|
||||
Add Slicing Profile
|
||||
===================
|
||||
|
||||
.. http:put:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Adds a new slicing profile for the given ``slicer`` to the system. If the profile identified by ``key`` already exists,
|
||||
it will be overwritten.
|
||||
|
||||
Expects a :ref:`Profile <sec-api-slicing-datamodel-profile>` as body.
|
||||
|
||||
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
|
||||
upon successful completion.
|
||||
|
||||
**Example**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"data": {
|
||||
"layer_height": 0.2,
|
||||
"skirt_line_count": 3
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 201 Created
|
||||
Content-Type: application/json
|
||||
Location: http://example.com/api/slicing/cura/profiles/quick_test
|
||||
|
||||
{
|
||||
"displayName": "Just a test",
|
||||
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
|
||||
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
|
||||
}
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to add the profile
|
||||
:param key: The identifying key of the new profile
|
||||
:statuscode 201: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-delete:
|
||||
|
||||
Delete Slicing Profile
|
||||
======================
|
||||
|
||||
.. http:delete:: /api/slicing/(string:slicer)/profiles/(string:key)
|
||||
|
||||
Delete the slicing profile identified by ``key`` for the slicer ``slicer``.
|
||||
|
||||
:param slicer: The identifying key of the slicer for which to delete the profile
|
||||
:param key: The identifying key of the profile to delete
|
||||
:statuscode 204: No error
|
||||
:statuscode 404: If the ``slicer`` was unknown to the system.
|
||||
|
||||
.. _sec-api-slicing-datamodel:
|
||||
|
||||
Datamodel
|
||||
=========
|
||||
|
||||
.. _sec-api-slicing-datamodel-slicerlist:
|
||||
|
||||
Slicer list
|
||||
-----------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``<slicer key>``
|
||||
- 0..*
|
||||
- :ref:`Slicer <sec-api-slicing-datamodel-slicer>`
|
||||
- Information about a slicer registered in the system, incl. stored profiles without ``data``.
|
||||
|
||||
.. _sec-api-slicing-datamodel-slicer:
|
||||
|
||||
Slicer
|
||||
------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- ``string``
|
||||
- Identifier of the slicer
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the slicer
|
||||
* - ``default``
|
||||
- 1
|
||||
- ``boolean``
|
||||
- Whether the slicer is the default slicer to use (``true``) or not (``false``).
|
||||
* - ``profiles``
|
||||
- 0..*
|
||||
- :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
|
||||
- Slicing profiles available for this slicer, mapped by their ``key``
|
||||
|
||||
.. _sec-api-slicing-datamodel-profilelist:
|
||||
|
||||
Profile list
|
||||
------------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``<profile key>``
|
||||
- 0..1
|
||||
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
|
||||
- Information about a profile stored in the system, ``data`` field will be left out.
|
||||
|
||||
.. _sec-api-slicing-datamodel-profile:
|
||||
|
||||
Profile
|
||||
-------
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Multiplicity
|
||||
- Type
|
||||
- Description
|
||||
* - ``key``
|
||||
- 1
|
||||
- ``string``
|
||||
- Identifier of the profile
|
||||
* - ``displayName``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Display name of the profile
|
||||
* - ``description``
|
||||
- 0..1
|
||||
- ``string``
|
||||
- Description of the profile
|
||||
* - ``default``
|
||||
- 0..1
|
||||
- ``boolean``
|
||||
- Whether this is the default profile to be used with this slicer (``true``) or not (``false``). Will always be
|
||||
returned in responses but can be left out of save/update requests.
|
||||
* - ``resource``
|
||||
- 0..1
|
||||
- ``URL``
|
||||
- Resource URL of the profile, will always be returned in responses but can be left out of save/update requests.
|
||||
* - ``data``
|
||||
- 0..1
|
||||
- Object
|
||||
- The actual profile data, including any default values if the profile was retrieved from the server. May contain
|
||||
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
|
||||
specific. Will be left out for list responses.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
.. _sec-api-version:
|
||||
|
||||
*******************
|
||||
Version information
|
||||
*******************
|
||||
|
||||
.. http:get:: /api/version
|
||||
|
||||
Retrieve information regarding server and API version. Returns a JSON object with two keys, ``api`` containing
|
||||
the API version, ``server`` containing the server version.
|
||||
|
||||
**Example Request**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
GET /api/version HTTP/1.1
|
||||
Host: example.com
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
**Example Response**
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"api": "0.1",
|
||||
"server": "1.1.0"
|
||||
}
|
||||
|
||||
:statuscode 200: No error
|
||||
+21
-6
@@ -16,7 +16,13 @@ import sys, os
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
sys.path.insert(0, os.path.abspath('../src/'))
|
||||
|
||||
import octoprint._version
|
||||
from datetime import date
|
||||
|
||||
year_since = 2013
|
||||
year_current = date.today().year
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
@@ -25,7 +31,8 @@ import sys, os
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.todo']
|
||||
extensions = ['sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
@@ -41,14 +48,14 @@ master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'OctoPrint'
|
||||
copyright = u'2013, Gina Häußge'
|
||||
copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = open("../VERSION").read().strip()
|
||||
version = octoprint._version.get_versions()["version"]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = version
|
||||
|
||||
@@ -92,9 +99,17 @@ pygments_style = 'sphinx'
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
|
||||
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
|
||||
|
||||
if not on_rtd: # only import and set the theme if we're building docs locally
|
||||
import sphinx_rtd_theme
|
||||
html_theme = 'sphinx_rtd_theme'
|
||||
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
#html_theme = "sphinx_rtd_theme"
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
@@ -102,7 +117,7 @@ html_theme = 'default'
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
.. _sec-events:
|
||||
|
||||
####################
|
||||
Events Documentation
|
||||
####################
|
||||
|
||||
.. contents::
|
||||
|
||||
With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events.
|
||||
Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to
|
||||
accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer
|
||||
separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed
|
||||
to indicate what to do with the command contained.
|
||||
|
||||
.. _sec-events-configuration:
|
||||
|
||||
Configuration
|
||||
=============
|
||||
|
||||
Event hooks are configured via OctoPrint's configuration file ``config.yaml``. There they are contained in a
|
||||
``subscriptions`` list located directly under the ``events`` node. The ``command`` node accepts either a single string
|
||||
or a list of strings so that multiple commands can be executed in one go. Each hook carries an additional node type that
|
||||
must be either ``gcode`` (for GCODE commands to be sent to the printer based on the event) or ``system`` (for commands to be
|
||||
executed on the system OctoPrint is running on).
|
||||
|
||||
All event hooks can be disabled completely by setting ``event > enabled`` to ``false``. You can also disable individual
|
||||
hooks by setting the (optional) node ``enabled`` to false, see the example below.
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
.. sourcecode:: yaml
|
||||
|
||||
events:
|
||||
enabled: True
|
||||
subscriptions:
|
||||
- event: Disconnected
|
||||
command: python ~/growl.py -t mygrowlserver -d "Lost connection to printer" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
enabled: false
|
||||
- event: PrintStarted
|
||||
command: python ~/growl.py -t mygrowlserver -d "Starting {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: PrintDone
|
||||
command: python ~/growl.py -t mygrowlserver -d "Completed {file}" -a OctoPrint -i http://raspi/Octoprint_logo.png
|
||||
type: system
|
||||
- event: Connected
|
||||
command:
|
||||
- M115
|
||||
- M117 printer connected!
|
||||
- G28
|
||||
type: gcode
|
||||
|
||||
.. _sec-events-placeholders:
|
||||
|
||||
Placeholders
|
||||
============
|
||||
|
||||
You can use the following generic placeholders in your events:
|
||||
|
||||
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
|
||||
* ``{__filename}``: filename of the currently selected file, "NO FILE" if not available
|
||||
* ``{__progress}``: the progress of the print in percent, 0 if not available
|
||||
* ``{__data}``: a string representation of the payload
|
||||
* ``{__now}``: the date and time of the event in ISO 8601
|
||||
|
||||
Additionally, all data from the payload can be accessed by its key. Example: If the payload happens to be defined
|
||||
something like this:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
then you'll be able to access the filename via the placeholder ``{file}`` and the origin via the placeholder ``{origin}``.
|
||||
|
||||
|
||||
.. _sec-events-available_events:
|
||||
|
||||
Available Events
|
||||
================
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
Startup
|
||||
The server has started
|
||||
|
||||
ClientOpened
|
||||
A client has connected to the web server.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that connected
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
ClientClosed
|
||||
A client has disconnected from the webserver
|
||||
|
||||
Payload:
|
||||
|
||||
* ``remoteAddress``: the remote address (IP) of the client that disconnected
|
||||
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
Connected
|
||||
The server has connected to the printer.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``port``: the connected serial port
|
||||
* ``baudrate``: the baud rate
|
||||
|
||||
Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
Error
|
||||
An error has occurred in the printer communication.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``error``: the error string
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
Upload
|
||||
A file has been uploaded.
|
||||
|
||||
Payload:
|
||||
* ``file``: the file's name
|
||||
* ``target``: the target to which the file was uploaded, either ``local`` or ``sdcard``
|
||||
|
||||
UpdatedFiles
|
||||
A file list was modified.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
|
||||
|
||||
.. note::
|
||||
|
||||
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
|
||||
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
|
||||
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
|
||||
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
|
||||
|
||||
MetadataAnalysisStarted
|
||||
The metadata analysis of a GCODE file has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
|
||||
MetadataAnalaysisFinished
|
||||
The metadata analysis of a GCODE file has finished.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``result``: the analysis result -- this is a python object currently only available for internal use
|
||||
|
||||
FileSelected
|
||||
A GCODE file has been selected for printing.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
FileDeselected
|
||||
No file is selected any more for printing.
|
||||
|
||||
TransferStarted
|
||||
A GCODE file transfer to SD has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
**Note:** Name changed in version 1.1.0
|
||||
|
||||
TransferDone
|
||||
A GCODE file transfer to SD has finished.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``time``: the time it took for the transfer to complete in seconds
|
||||
* ``local``: the file's name as stored locally
|
||||
* ``remote``: the file's name as stored on SD
|
||||
|
||||
Printing
|
||||
--------
|
||||
|
||||
PrintStarted
|
||||
A print has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintFailed
|
||||
A print failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintDone
|
||||
A print completed successfully.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
* ``time``: the time needed for the print, in seconds (float)
|
||||
|
||||
PrintCancelled
|
||||
The print has been cancelled via the cancel button.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintPaused
|
||||
The print has been paused.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
PrintResumed
|
||||
The print has been resumed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the file's name
|
||||
* ``origin``: the origin of the file, either ``local`` or ``sdcard``
|
||||
|
||||
GCODE processing
|
||||
----------------
|
||||
|
||||
PowerOn
|
||||
The GCode has turned on the printer power via M80
|
||||
|
||||
PowerOff
|
||||
The GCODE has turned on the printer power via M81
|
||||
|
||||
Home
|
||||
The head has gone home via G28
|
||||
|
||||
ZChange
|
||||
The printer's Z-Height has changed (new layer)
|
||||
|
||||
Paused
|
||||
The print has been paused
|
||||
|
||||
Waiting
|
||||
The print is paused due to a gcode wait command
|
||||
|
||||
Cooling
|
||||
The GCODE has enabled the platform cooler via M245
|
||||
|
||||
Alert
|
||||
The GCODE has issued a user alert (beep) via M300
|
||||
|
||||
Conveyor
|
||||
The GCODE has enabled the conveyor belt via M240
|
||||
|
||||
Eject
|
||||
The GCODE has enabled the part ejector via M40
|
||||
|
||||
EStop
|
||||
The GCODE has issued a panic stop via M112
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
CaptureStart
|
||||
A timelapse image has started to be captured.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``file``: the name of the image file to be saved
|
||||
|
||||
CaptureDone
|
||||
A timelapse image has completed being captured.
|
||||
|
||||
Payload:
|
||||
* ``file``: the name of the image file that was saved
|
||||
|
||||
MovieRendering
|
||||
The timelapse movie has started rendering.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that is being created (full path)
|
||||
* ``movie_basename``: the movie file that is being created (only the file name without the path)
|
||||
|
||||
MovieDone
|
||||
The timelapse movie is completed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that has been created (full path)
|
||||
* ``movie_basename``: the movie file that has been created (only the file name without the path)
|
||||
|
||||
MovieFailed
|
||||
There was an error while rendering the timelapse movie.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``gcode``: the GCODE file for which the timelapse would have been created (only the filename without the path)
|
||||
* ``movie``: the movie file that would have been created (full path)
|
||||
* ``movie_basename``: the movie file that would have been created (only the file name without the path)
|
||||
* ``returncode``: the return code of ``ffmpeg`` that indicates the error that occurred
|
||||
|
||||
Slicing
|
||||
-------
|
||||
|
||||
SlicingStarted
|
||||
The slicing of a file has started.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``progressAvailable``: true if progress information via the ``slicingProgress`` push update will be available, false if not
|
||||
|
||||
SlicingDone
|
||||
The slicing of a file has completed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``time``: the time needed for slicing, in seconds (float)
|
||||
|
||||
SlicingCancelled
|
||||
The slicing of a file has been cancelled. This will happen if a second slicing job
|
||||
targeting the same GCODE file has been started by the user.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
|
||||
SlicingFailed
|
||||
The slicing of a file has failed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``stl``: the STL's filename
|
||||
* ``gcode``: the sliced GCODE's filename
|
||||
* ``reason``: the reason for the slicing having failed
|
||||
|
||||
Settings
|
||||
--------
|
||||
|
||||
SettingsUpdated
|
||||
The internal settings were updated.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
+15
-15
@@ -1,22 +1,22 @@
|
||||
.. OctoPrint documentation master file, created by
|
||||
sphinx-quickstart on Mon Dec 02 17:08:50 2013.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
#####################################
|
||||
Welcome to OctoPrint's documentation!
|
||||
=====================================
|
||||
#####################################
|
||||
|
||||
Contents:
|
||||
.. image:: images/octoprint-logo.png
|
||||
:alt: The OctoPrint Logo
|
||||
:align: right
|
||||
|
||||
This is a work in progress. The goal is to document OctoPrint's REST API, event system, configuration etc in a way that
|
||||
allows different documentation per development branch in Git, which so far did not scale well with the Github-Wiki-based
|
||||
approach.
|
||||
|
||||
Contents
|
||||
========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
api/index.rst
|
||||
events/index.rst
|
||||
plugins/index.rst
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
.. _sec-plugins-developing:
|
||||
|
||||
******************
|
||||
Developing Plugins
|
||||
******************
|
||||
|
||||
.. todo::
|
||||
|
||||
A section on how to develop plugins yourself, including a tutorial creating an exemplary plugin as well as
|
||||
a documentation of the plugin API, will be added in the near future.
|
||||
|
||||
.. _sec-plugins-developing-types:
|
||||
|
||||
Available plugin types
|
||||
======================
|
||||
|
||||
.. automodule:: octoprint.plugin.types
|
||||
:members:
|
||||
:undoc-members:
|
||||
@@ -0,0 +1,60 @@
|
||||
.. _sec-plugins:
|
||||
|
||||
#####################
|
||||
Plugins Documentation
|
||||
#####################
|
||||
|
||||
Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually
|
||||
extend OctoPrint's functionality.
|
||||
|
||||
Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and
|
||||
shutdown, to provide custom (API) endpoints with special functionality, to react on system events or to add support for
|
||||
additional slicers. More plugin types are planned for the future.
|
||||
|
||||
.. _sec-plugins-installation:
|
||||
|
||||
Installing Plugins
|
||||
==================
|
||||
|
||||
Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are
|
||||
``<octoprint-root>/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``.
|
||||
Please refer to the documentation of the plugin for installations instructions.
|
||||
|
||||
The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed
|
||||
this way.
|
||||
|
||||
For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install <plugin_name>
|
||||
|
||||
For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to
|
||||
a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip
|
||||
|
||||
See `the pip install documentation <http://pip.readthedocs.org/en/latest/reference/pip_install.html>`_ for what URL
|
||||
types are possible.
|
||||
|
||||
.. _sec-plugins-available:
|
||||
|
||||
Available Plugins
|
||||
=================
|
||||
|
||||
Currently there's no such thing as a centralized plugin repository for available plugins.
|
||||
|
||||
Plugins may be found in the lists provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
|
||||
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
|
||||
|
||||
Developing Plugins
|
||||
==================
|
||||
|
||||
Please see the following sub topics for information on how to develop your own OctoPrint plugins.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
developing.rst
|
||||
@@ -0,0 +1,2 @@
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -8,3 +8,8 @@ Flask-Principal==0.3.5
|
||||
netaddr>=0.7.10
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
watchdog
|
||||
sarge
|
||||
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
@@ -0,0 +1,6 @@
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
sphinxcontrib-httpdomain
|
||||
sphinx_rtd_theme
|
||||
po2json
|
||||
ddt
|
||||
+9
-5
@@ -1,11 +1,15 @@
|
||||
flask==0.9
|
||||
werkzeug==0.8.3
|
||||
tornado==3.0.2
|
||||
tornado==4.0.1
|
||||
sockjs-tornado>=1.0.0
|
||||
PyYAML==3.10
|
||||
Flask-Login==0.2.2
|
||||
Flask-Principal==0.3.5
|
||||
pyserial>=2.6
|
||||
netaddr>=0.7.10
|
||||
mock>=1.0.1
|
||||
nose>=1.3.0
|
||||
Flask-Babel==0.9
|
||||
pyserial
|
||||
netaddr
|
||||
watchdog
|
||||
sarge
|
||||
netifaces
|
||||
pylru
|
||||
rsa
|
||||
@@ -1,13 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
print """
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
!!! You are using an old startup method for OctoPrint. !!!
|
||||
!!! Please perform 'sudo python setup.py install' and !!!
|
||||
!!! use the 'octoprint' executable instead. !!!
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -24,7 +16,7 @@ I don't know anything about).
|
||||
"""
|
||||
os.rename(old, os.path.join(basedir, "octoprint.backup"))
|
||||
|
||||
sys.path.append(os.path.join(basedir, "src"))
|
||||
sys.path.insert(0, os.path.join(basedir, "src"))
|
||||
|
||||
import octoprint
|
||||
octoprint.main()
|
||||
@@ -18,7 +18,8 @@
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||
DESC="Octoprint Daemon"
|
||||
NAME="Octoprint"
|
||||
DAEMON=/usr/bin/octoprint
|
||||
DAEMON=/usr/local/bin/octoprint
|
||||
NICE=-10
|
||||
PIDFILE=/var/run/$NAME.pid
|
||||
PKGNAME=octoprint
|
||||
SCRIPTNAME=/etc/init.d/$PKGNAME
|
||||
@@ -72,7 +73,7 @@ do_start()
|
||||
RETVAL="$?"
|
||||
|
||||
if [ $RETVAL != 0 ]; then
|
||||
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
|
||||
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile --nicelevel $NICE\
|
||||
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK -- $DAEMON_ARGS
|
||||
RETVAL="$?"
|
||||
fi
|
||||
|
||||
@@ -1,13 +1,260 @@
|
||||
# coding=utf-8
|
||||
#!/usr/bin/env python
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
import versioneer
|
||||
versioneer.VCS = 'git'
|
||||
versioneer.versionfile_source = 'src/octoprint/_version.py'
|
||||
versioneer.versionfile_build = 'octoprint/_version.py'
|
||||
versioneer.tag_prefix = ''
|
||||
versioneer.parentdir_prefix = ''
|
||||
versioneer.lookupfile = '.versioneer-lookup'
|
||||
|
||||
from setuptools import setup, find_packages, Command
|
||||
import os
|
||||
import shutil
|
||||
import glob
|
||||
|
||||
I18N_MAPPING_FILE = "babel.cfg"
|
||||
I18N_DOMAIN = "messages"
|
||||
I18N_INPUT_DIRS = "."
|
||||
I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations")
|
||||
I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n")
|
||||
I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot")
|
||||
|
||||
def package_data_dirs(source, sub_folders):
|
||||
dirs = []
|
||||
|
||||
for d in sub_folders:
|
||||
for dirname, _, files in os.walk(os.path.join(source, d)):
|
||||
dirname = os.path.relpath(dirname, source)
|
||||
for f in files:
|
||||
dirs.append(os.path.join(dirname, f))
|
||||
|
||||
return dirs
|
||||
|
||||
|
||||
def _recursively_handle_files(directory, file_matcher, folder_handler=None, file_handler=None):
|
||||
applied_handler = False
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
path = os.path.join(directory, filename)
|
||||
|
||||
if file_handler is not None and file_matcher(filename):
|
||||
file_handler(path)
|
||||
applied_handler = True
|
||||
|
||||
elif os.path.isdir(path):
|
||||
sub_applied_handler = _recursively_handle_files(path, file_matcher, folder_handler=folder_handler, file_handler=file_handler)
|
||||
if sub_applied_handler:
|
||||
applied_handler = True
|
||||
|
||||
if folder_handler is not None:
|
||||
folder_handler(path, sub_applied_handler)
|
||||
|
||||
return applied_handler
|
||||
|
||||
class CleanCommand(Command):
|
||||
description = "clean build artifacts"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
def initialize_options(self):
|
||||
pass
|
||||
|
||||
def finalize_options(self):
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
# build folder
|
||||
if os.path.exists('build'):
|
||||
print "Deleting build directory"
|
||||
shutil.rmtree('build')
|
||||
|
||||
# eggs
|
||||
eggs = glob.glob('OctoPrint*.egg-info')
|
||||
for egg in eggs:
|
||||
print "Deleting %s directory" % egg
|
||||
shutil.rmtree(egg)
|
||||
|
||||
# pyc files
|
||||
def delete_folder_if_empty(path, applied_handler):
|
||||
if not applied_handler:
|
||||
return
|
||||
if len(os.listdir(path)) == 0:
|
||||
shutil.rmtree(path)
|
||||
print "Deleted %s since it was empty" % path
|
||||
|
||||
def delete_file(path):
|
||||
os.remove(path)
|
||||
print "Deleted %s" % path
|
||||
|
||||
import fnmatch
|
||||
_recursively_handle_files(
|
||||
os.path.abspath("src"),
|
||||
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
|
||||
folder_handler=delete_folder_if_empty,
|
||||
file_handler=delete_file
|
||||
)
|
||||
|
||||
# pyc files
|
||||
def delete_folder_if_empty(path, applied_handler):
|
||||
if not applied_handler:
|
||||
return
|
||||
if len(os.listdir(path)) == 0:
|
||||
shutil.rmtree(path)
|
||||
print "Deleted %s since it was empty" % path
|
||||
|
||||
def delete_file(path):
|
||||
os.remove(path)
|
||||
print "Deleted %s" % path
|
||||
|
||||
import fnmatch
|
||||
_recursively_handle_files(
|
||||
os.path.abspath("src"),
|
||||
lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"),
|
||||
folder_handler=delete_folder_if_empty,
|
||||
file_handler=delete_file
|
||||
)
|
||||
|
||||
|
||||
class NewTranslation(Command):
|
||||
description = "create a new translation"
|
||||
user_options = [
|
||||
('locale=', 'l', 'locale for the new translation'),
|
||||
]
|
||||
boolean_options = []
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
self.babel_init_messages = babel.init_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
self.babel_init_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_init_messages.locale = self.locale
|
||||
self.babel_init_messages.input_file = I18N_POT_FILE
|
||||
self.babel_init_messages.output_dir = I18N_OUTPUT_DIR_PY
|
||||
self.babel_init_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_init_messages.run()
|
||||
|
||||
|
||||
class ExtractTranslation(Command):
|
||||
description = "extract translations"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
self.babel_extract_messages = babel.extract_messages(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.babel_extract_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_extract_messages.mapping_file = I18N_MAPPING_FILE
|
||||
self.babel_extract_messages.output_file = I18N_POT_FILE
|
||||
self.babel_extract_messages.input_dirs = I18N_INPUT_DIRS
|
||||
self.babel_extract_messages.msgid_bugs_address = "i18n@octoprint.org"
|
||||
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
|
||||
self.babel_extract_messages.finalize_options()
|
||||
|
||||
def run(self):
|
||||
self.babel_extract_messages.run()
|
||||
|
||||
|
||||
class RefreshTranslation(Command):
|
||||
description = "refresh translations"
|
||||
user_options = [
|
||||
('locale=', 'l', 'locale for the translation to refresh'),
|
||||
]
|
||||
boolean_options = []
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
self.babel_extract_messages = babel.extract_messages(dist)
|
||||
self.babel_update_messages = babel.update_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.locale = None
|
||||
self.babel_extract_messages.initialize_options()
|
||||
self.babel_update_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_extract_messages.mapping_file = I18N_MAPPING_FILE
|
||||
self.babel_extract_messages.output_file = I18N_POT_FILE
|
||||
self.babel_extract_messages.input_dirs = I18N_INPUT_DIRS
|
||||
self.babel_extract_messages.msgid_bugs_address = "i18n@octoprint.org"
|
||||
self.babel_extract_messages.copyright_holder = "The OctoPrint Project"
|
||||
self.babel_extract_messages.finalize_options()
|
||||
|
||||
self.babel_update_messages.input_file = I18N_MAPPING_FILE
|
||||
self.babel_update_messages.output_dir = I18N_OUTPUT_DIR_PY
|
||||
self.babel_update_messages.locale = self.locale
|
||||
|
||||
def run(self):
|
||||
self.babel_extract_messages.run()
|
||||
self.babel_update_messages.run()
|
||||
|
||||
|
||||
class CompileTranslation(Command):
|
||||
description = "compile translations"
|
||||
user_options = []
|
||||
boolean_options = []
|
||||
|
||||
def __init__(self, dist, **kw):
|
||||
from babel.messages import frontend as babel
|
||||
self.babel_compile_messages = babel.compile_catalog(dist)
|
||||
Command.__init__(self, dist, **kw)
|
||||
|
||||
def initialize_options(self):
|
||||
self.babel_compile_messages.initialize_options()
|
||||
|
||||
def finalize_options(self):
|
||||
self.babel_compile_messages.directory = I18N_OUTPUT_DIR_PY
|
||||
|
||||
def run(self):
|
||||
self.babel_compile_messages.run()
|
||||
|
||||
import po2json
|
||||
|
||||
for lang_code in os.listdir(I18N_OUTPUT_DIR_PY):
|
||||
full_path = os.path.join(I18N_OUTPUT_DIR_PY, lang_code)
|
||||
|
||||
if os.path.isdir(full_path):
|
||||
client_po_dir = os.path.join(full_path, "LC_MESSAGES")
|
||||
|
||||
po2json.update_js_file(
|
||||
"%s/%s.po" % (client_po_dir, I18N_DOMAIN),
|
||||
lang_code,
|
||||
I18N_OUTPUT_DIR_JS,
|
||||
I18N_DOMAIN
|
||||
)
|
||||
|
||||
|
||||
def get_cmdclass():
|
||||
cmdclass = versioneer.get_cmdclass()
|
||||
cmdclass.update({
|
||||
'clean': CleanCommand,
|
||||
'babel_new': NewTranslation,
|
||||
'babel_extract': ExtractTranslation,
|
||||
'babel_refresh': RefreshTranslation,
|
||||
'babel_compile': CompileTranslation
|
||||
})
|
||||
return cmdclass
|
||||
|
||||
VERSION = open("VERSION").read().strip()
|
||||
|
||||
def params():
|
||||
name = "OctoPrint"
|
||||
version = VERSION
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A responsive web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
classifiers = [
|
||||
@@ -36,6 +283,7 @@ def params():
|
||||
|
||||
packages = find_packages(where="src")
|
||||
package_dir = {"octoprint": "src/octoprint"}
|
||||
package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])}
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
|
||||
@@ -3,8 +3,16 @@ import sys
|
||||
from octoprint.daemon import Daemon
|
||||
from octoprint.server import Server
|
||||
|
||||
#~~ version
|
||||
|
||||
from ._version import get_versions
|
||||
__version__ = get_versions()['version']
|
||||
del get_versions
|
||||
|
||||
#~~ main class
|
||||
|
||||
class Main(Daemon):
|
||||
def __init__(self, pidfile, configfile, basedir, host, port, debug):
|
||||
def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot, logConf):
|
||||
Daemon.__init__(self, pidfile)
|
||||
|
||||
self._configfile = configfile
|
||||
@@ -12,9 +20,11 @@ class Main(Daemon):
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allowRoot = allowRoot
|
||||
self._logConf = logConf
|
||||
|
||||
def run(self):
|
||||
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug)
|
||||
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
|
||||
octoprint.run()
|
||||
|
||||
def main():
|
||||
@@ -22,6 +32,9 @@ def main():
|
||||
|
||||
parser = argparse.ArgumentParser(prog="run")
|
||||
|
||||
parser.add_argument("-v", "--version", action="store_true", dest="version",
|
||||
help="Output OctoPrint's version and exit")
|
||||
|
||||
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
|
||||
help="Enable debug mode")
|
||||
|
||||
@@ -34,6 +47,8 @@ def main():
|
||||
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
|
||||
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
|
||||
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
|
||||
parser.add_argument("--logging", action="store", dest="logConf",
|
||||
help="Specify the config file to use for configuring logging. Defaults to ~/.octoprint/logging.yaml")
|
||||
|
||||
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
|
||||
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
|
||||
@@ -45,12 +60,16 @@ def main():
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.version:
|
||||
print "OctoPrint version %s" % __version__
|
||||
sys.exit(0)
|
||||
|
||||
if args.daemon:
|
||||
if sys.platform == "darwin" or sys.platform == "win32":
|
||||
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
|
||||
sys.exit(2)
|
||||
|
||||
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug)
|
||||
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
|
||||
if "start" == args.daemon:
|
||||
daemon.start()
|
||||
elif "stop" == args.daemon:
|
||||
@@ -58,9 +77,8 @@ def main():
|
||||
elif "restart" == args.daemon:
|
||||
daemon.restart()
|
||||
else:
|
||||
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot)
|
||||
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
|
||||
octoprint.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
# feature). Distribution tarballs (build by setup.py sdist) and build
|
||||
# directories (produced by setup.py build) will contain a much shorter file
|
||||
# that just contains the computed version number.
|
||||
|
||||
# This file is released into the public domain. Generated by
|
||||
# versioneer-0.10 (https://github.com/warner/python-versioneer)
|
||||
|
||||
# these strings will be replaced by git during git-archive
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import errno
|
||||
|
||||
|
||||
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
assert isinstance(commands, list)
|
||||
p = None
|
||||
for c in commands:
|
||||
try:
|
||||
# remember shell=False, so use git.cmd on windows, not just git
|
||||
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
|
||||
stderr=(subprocess.PIPE if hide_stderr
|
||||
else None))
|
||||
break
|
||||
except EnvironmentError:
|
||||
e = sys.exc_info()[1]
|
||||
if e.errno == errno.ENOENT:
|
||||
continue
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print(e)
|
||||
return None
|
||||
else:
|
||||
if verbose:
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version >= '3':
|
||||
stdout = stdout.decode()
|
||||
if p.returncode != 0:
|
||||
if verbose:
|
||||
print("unable to run %s (error)" % args[0])
|
||||
return None
|
||||
return stdout
|
||||
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os.path
|
||||
|
||||
def get_gits(root, verbose=False):
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
if verbose:
|
||||
print("no .git in %s" % root)
|
||||
return None
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
return GITS
|
||||
|
||||
|
||||
def get_expanded_variables(versionfile_abs):
|
||||
# the code embedded in _version.py can just fetch the value of these
|
||||
# variables. When used from setup.py, we don't want to import
|
||||
# _version.py, so we do it with a regexp instead. This function is not
|
||||
# used from _version.py.
|
||||
variables = {}
|
||||
try:
|
||||
f = open(versionfile_abs,"r")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["refnames"] = mo.group(1)
|
||||
if line.strip().startswith("git_full ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["full"] = mo.group(1)
|
||||
f.close()
|
||||
except EnvironmentError:
|
||||
pass
|
||||
return variables
|
||||
|
||||
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
refnames = variables["refnames"].strip()
|
||||
if refnames.startswith("$Format"):
|
||||
if verbose:
|
||||
print("variables are unexpanded, not using")
|
||||
return {} # unexpanded, so not in an unpacked git-archive tarball
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
TAG = "tag: "
|
||||
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
|
||||
if not tags:
|
||||
# Either we're using git < 1.8.3, or there really are no tags. We use
|
||||
# a heuristic: assume all version tags have a digit. The old git %d
|
||||
# expansion behaves like git log --decorate=short and strips out the
|
||||
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
|
||||
# between branches and tags. By ignoring refnames without digits, we
|
||||
# filter out many common branch names like "release" and
|
||||
# "stabilization", as well as "HEAD" and "master".
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
if verbose:
|
||||
print("likely tags: %s" % ",".join(sorted(tags)))
|
||||
for ref in sorted(tags):
|
||||
# sorting will prefer e.g. "2.0" over "2.0rc1"
|
||||
if ref.startswith(tag_prefix):
|
||||
r = ref[len(tag_prefix):]
|
||||
if verbose:
|
||||
print("picking %s" % r)
|
||||
return { "version": r,
|
||||
"full": variables["full"].strip() }
|
||||
# no suitable tags, so we use the full revision id
|
||||
if verbose:
|
||||
print("no suitable tags, using full revision id")
|
||||
return { "version": variables["full"].strip(),
|
||||
"full": variables["full"].strip() }
|
||||
|
||||
def versions_from_lookup(lookup, root, verbose=False):
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
num_commits = stdout.strip()
|
||||
|
||||
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
|
||||
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
|
||||
if dirty:
|
||||
version += "-dirty"
|
||||
full += "-dirty"
|
||||
return {"version": version, "full": full, "branch": current_branch}
|
||||
|
||||
return {}
|
||||
|
||||
def versions_from_vcs(tag_prefix, root, verbose=False):
|
||||
# this runs 'git' from the root of the source tree. This only gets called
|
||||
# if the git-archive 'subst' variables were *not* expanded, and
|
||||
# _version.py hasn't already been rewritten with a short version string,
|
||||
# meaning we're inside a checked out source tree.
|
||||
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
if not stdout.startswith(tag_prefix):
|
||||
if verbose:
|
||||
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
|
||||
return {}
|
||||
tag = stdout[len(tag_prefix):]
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
if tag.endswith("-dirty"):
|
||||
full += "-dirty"
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
branch = None
|
||||
else:
|
||||
branch = stdout.strip()
|
||||
return {"version": tag, "full": full, "branch": branch}
|
||||
|
||||
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
# Source tarballs conventionally unpack into a directory that includes
|
||||
# both the project name and a version string.
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
|
||||
(root, dirname, parentdir_prefix))
|
||||
return None
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
versionfile_source = "src/octoprint/_version.py"
|
||||
lookupfile = ".versioneer-lookup"
|
||||
|
||||
def parse_lookup_file(root, lookup_path=None):
|
||||
if not lookup_path:
|
||||
lookup_path = lookupfile
|
||||
if not lookup_path:
|
||||
return []
|
||||
|
||||
path = os.path.join(root, lookup_path)
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(os.path.join(root, lookup_path), "r") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex('#')]
|
||||
line = line.strip()
|
||||
try:
|
||||
split_line = line.split()
|
||||
if len(split_line) == 3:
|
||||
pattern, tag, ref_commit = split_line
|
||||
lookup.append([re.compile(pattern), tag, ref_commit])
|
||||
elif len(split_line) >= 1:
|
||||
lookup.append([re.compile(split_line[0]), None, None])
|
||||
except:
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False):
|
||||
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
|
||||
# __file__, we can work backwards from there to the root. Some
|
||||
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
|
||||
# case we can only use expanded variables.
|
||||
|
||||
variables = { "refnames": git_refnames, "full": git_full }
|
||||
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
|
||||
if ver:
|
||||
return ver
|
||||
|
||||
try:
|
||||
root = os.path.abspath(__file__)
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree (where the .git directory might live) to this file. Invert
|
||||
# this to find the root from __file__.
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
root = os.path.dirname(root)
|
||||
except NameError:
|
||||
return default
|
||||
|
||||
lookup = parse_lookup_file(root, lookup_path=lookup_path)
|
||||
return (versions_from_lookup(lookup, root, verbose)
|
||||
or versions_from_vcs(tag_prefix, root, verbose)
|
||||
or versions_from_parentdir(parentdir_prefix, root, verbose)
|
||||
or default)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.comm.transport import MessageReceiver, StateReceiver, LogReceiver, State as TransportState
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings
|
||||
|
||||
|
||||
class Protocol(MessageReceiver, StateReceiver, LogReceiver):
|
||||
|
||||
def __init__(self, transport_factory, protocol_listener=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._transport = transport_factory(self, self, self)
|
||||
self._transport_properties = self._transport.get_properties()
|
||||
|
||||
self._protocol_listener = protocol_listener
|
||||
self._state = State.OFFLINE
|
||||
|
||||
self._heatup_start_time = None
|
||||
self._heatup_time_lost = 0.0
|
||||
|
||||
self._pause_start_time = None
|
||||
self._pause_time_lost = 0.0
|
||||
|
||||
self._current_file = None
|
||||
|
||||
self._current_z = 0.0
|
||||
|
||||
self._sd_available = False
|
||||
self._sd_files = []
|
||||
|
||||
self._current_temperature = {}
|
||||
self._temperature_offsets = {}
|
||||
|
||||
self._error = None
|
||||
|
||||
def _reset(self):
|
||||
self._heatup_start_time = None
|
||||
self._heatup_time_lost = 0.0
|
||||
|
||||
self._current_file = None
|
||||
|
||||
self._current_z = 0.0
|
||||
|
||||
self._sd_available = False
|
||||
self._sd_files = []
|
||||
|
||||
self._current_temperature = {}
|
||||
self._temperature_offsets = {}
|
||||
|
||||
self._error = None
|
||||
|
||||
##~~ public
|
||||
|
||||
def connect(self, protocol_options, transport_options):
|
||||
self._transport.connect(transport_options)
|
||||
|
||||
def disconnect(self, on_error=False):
|
||||
if self.is_printing():
|
||||
payload = None
|
||||
if self._current_file is not None:
|
||||
payload = {
|
||||
"file": self._current_file.getFilename(),
|
||||
"filename": os.path.basename(self._current_file.getFilename()),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
}
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
self._transport.disconnect(on_error)
|
||||
|
||||
def send_manually(self, command, high_priority=False):
|
||||
pass
|
||||
|
||||
def select_file(self, filename, origin):
|
||||
pass
|
||||
|
||||
def deselect_file(self):
|
||||
pass
|
||||
|
||||
def start_print(self):
|
||||
if self._current_file is None:
|
||||
raise ValueError("No file selected for printing")
|
||||
|
||||
self._heatup_start_time = None
|
||||
self._heatup_time_lost = 0.0
|
||||
|
||||
self._current_file.start()
|
||||
self._changeState(State.PRINTING)
|
||||
eventManager().fire(Events.PRINT_STARTED, {
|
||||
"file": self._current_file.getFilename(),
|
||||
"filename": os.path.basename(self._current_file.getFilename()),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
})
|
||||
|
||||
def pause_print(self, only_pause=None, only_resume=None):
|
||||
payload = {
|
||||
"file": self._current_file.getFilename(),
|
||||
"filename": os.path.basename(self._current_file.getFilename()),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
}
|
||||
|
||||
if self._state == State.PRINTING and not only_resume:
|
||||
self._pause_start_time = time.time()
|
||||
|
||||
self._changeState(State.PAUSED)
|
||||
eventManager().fire(Events.PRINT_PAUSED, payload)
|
||||
|
||||
elif self._state == State.PAUSED and not only_pause:
|
||||
if self._pause_start_time:
|
||||
self._pause_time_lost += time.time() - self._pause_start_time
|
||||
self._pause_start_time = None
|
||||
|
||||
self._changeState(State.PRINTING)
|
||||
eventManager().fire(Events.PRINT_RESUMED, payload)
|
||||
|
||||
def cancel_print(self):
|
||||
eventManager().fire(Events.PRINT_CANCELLED, {
|
||||
"file": self._current_file.getFilename(),
|
||||
"filename": os.path.basename(self._current_file.getFilename()),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
})
|
||||
self._changeState(State.OPERATIONAL)
|
||||
self._print_cancelled()
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onPrintjobCancelled(self)
|
||||
|
||||
def _print_cancelled(self):
|
||||
pass
|
||||
|
||||
def init_sd(self):
|
||||
pass
|
||||
|
||||
def release_sd(self):
|
||||
pass
|
||||
|
||||
def refresh_sd_files(self):
|
||||
pass
|
||||
|
||||
def add_sd_file(self, path, local, remote):
|
||||
pass
|
||||
|
||||
def remove_sd_file(self, filename):
|
||||
pass
|
||||
|
||||
def get_state(self):
|
||||
return self._state
|
||||
|
||||
def get_current_temperatures(self):
|
||||
return self._current_temperature
|
||||
|
||||
def get_temperature_offsets(self):
|
||||
result = {}
|
||||
result.update(self._temperature_offsets)
|
||||
return result
|
||||
|
||||
def set_temperature_offsets(self, new_temperature_offsets):
|
||||
offsets = {}
|
||||
offsets.update(new_temperature_offsets)
|
||||
self._temperature_offsets = offsets
|
||||
|
||||
def get_sd_files(self):
|
||||
return self._sd_files
|
||||
|
||||
def get_print_time(self):
|
||||
if self._current_file is None or self._current_file.getStartTime() is None:
|
||||
return None
|
||||
else:
|
||||
return max(int(time.time() - self._current_file.getStartTime() - self._heatup_time_lost - self._pause_time_lost), 0)
|
||||
|
||||
def get_connection_options(self):
|
||||
return self._transport.get_connection_options()
|
||||
|
||||
def get_current_connection(self):
|
||||
return self._transport.get_current_connection()
|
||||
|
||||
##~~ granular state detection for implementations
|
||||
|
||||
def is_heating_up(self):
|
||||
return self._heatup_start_time is not None
|
||||
|
||||
def is_printing(self):
|
||||
return self._state == State.PRINTING or self._state == State.PAUSED
|
||||
|
||||
def is_sd_printing(self):
|
||||
return isinstance(self._current_file, PrintingSdFileInformation) and self.is_busy()
|
||||
|
||||
def is_streaming(self):
|
||||
return self._state == State.STREAMING
|
||||
|
||||
def is_busy(self):
|
||||
return self.is_printing() or self.is_streaming()
|
||||
|
||||
def is_operational(self):
|
||||
return self._state == State.OPERATIONAL
|
||||
|
||||
def is_sd_ready(self):
|
||||
return self._sd_available
|
||||
|
||||
##~~ state tracking and reporting to protocol listener
|
||||
|
||||
def _changeState(self, newState):
|
||||
oldState = self._state
|
||||
self._state = newState
|
||||
self._stateChanged(newState)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onStateChange(self, oldState, newState)
|
||||
|
||||
def _stateChanged(self, newState):
|
||||
pass
|
||||
|
||||
def _updateTemperature(self, temperatureData):
|
||||
self._current_temperature = temperatureData
|
||||
self._temperatureUpdated(temperatureData)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onTemperatureUpdate(self, temperatureData)
|
||||
|
||||
def _temperatureUpdated(self, temperatureData):
|
||||
pass
|
||||
|
||||
def _reportProgress(self, completion=None, filepos=None):
|
||||
if completion is None:
|
||||
completion = self._getPrintCompletion()
|
||||
if filepos is None:
|
||||
filepos = self._getPrintFilepos()
|
||||
|
||||
progress = {
|
||||
"completion": completion,
|
||||
"filepos": filepos,
|
||||
"printTime": self.get_print_time()
|
||||
}
|
||||
|
||||
self._progressReported(progress)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onProgress(self, progress)
|
||||
|
||||
def _progressReported(self, progress):
|
||||
pass
|
||||
|
||||
def _reportZChange(self, z):
|
||||
old_z = self._current_z
|
||||
self._current_z = z
|
||||
|
||||
self._zChangeReported(z)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onZChange(self, old_z, z)
|
||||
|
||||
def _zChangeReported(self, newZ):
|
||||
pass
|
||||
|
||||
def _changeSdState(self, sdAvailable):
|
||||
self._sd_available = sdAvailable
|
||||
self._sdStateChanged(sdAvailable)
|
||||
if self._sd_available:
|
||||
self.refresh_sd_files()
|
||||
else:
|
||||
self._sd_files = []
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onSdStateChange(self, sdAvailable)
|
||||
|
||||
def _sdStateChanged(self, sdAvailable):
|
||||
pass
|
||||
|
||||
def _selectFile(self, currentFile):
|
||||
self._current_file = currentFile
|
||||
self._fileSelected(currentFile)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onFileSelected(self, currentFile.getFilename(), currentFile.getFilesize(), currentFile.getFileLocation())
|
||||
eventManager().fire(Events.FILE_SELECTED, {
|
||||
"file": self._current_file.getFilename(),
|
||||
"origin": self._current_file.getFileLocation()
|
||||
})
|
||||
|
||||
def _fileSelected(self, currentFile):
|
||||
pass
|
||||
|
||||
def _sendSdFiles(self):
|
||||
self._sdFilesSent()
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onSdFiles(self, self._sd_files)
|
||||
|
||||
def _sdFilesSent(self):
|
||||
pass
|
||||
|
||||
def _finishPrintjob(self):
|
||||
self._reportProgress(completion=100, filepos=self._current_file.getFilesize())
|
||||
self._changeState(State.OPERATIONAL)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onPrintjobDone(self)
|
||||
eventManager().fire(Events.PRINT_DONE, {
|
||||
"file": self._current_file.getFilename(),
|
||||
"filename": os.path.basename(self._current_file.getFilename()),
|
||||
"origin": self._current_file.getFileLocation(),
|
||||
"time": time.time() - self._current_file.getStartTime() if self._current_file.getStartTime() is not None else None
|
||||
})
|
||||
self._printJobFinished()
|
||||
|
||||
def _printJobFinished(self):
|
||||
pass
|
||||
|
||||
def _startFileTransfer(self, filename, filesize):
|
||||
self._fileTransferStarted(filename, filesize)
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onFileTransferStarted(self, filename, filesize)
|
||||
|
||||
def _fileTransferStarted(self, filename, filesize):
|
||||
pass
|
||||
|
||||
def _finishFileTransfer(self):
|
||||
self._changeState(State.OPERATIONAL)
|
||||
|
||||
current_file = self._current_file
|
||||
self._current_file = None
|
||||
|
||||
self._fileTransferFinished(current_file)
|
||||
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onFileTransferDone(self)
|
||||
|
||||
def _fileTransferFinished(self, current_file):
|
||||
pass
|
||||
|
||||
def _addSdFile(self, filename, filesize):
|
||||
"""
|
||||
Adds a file to the SD file list
|
||||
|
||||
:param filename: the filename to add to the list
|
||||
:param filesize: the filesize to add to the list, may be None
|
||||
"""
|
||||
self._sd_files.append((filename, filesize))
|
||||
self._sdFileAdded(filename, filesize)
|
||||
|
||||
def _sdFileAdded(self, filename, filesize):
|
||||
"""
|
||||
Called when a file has been added to the SD file list, can be used by the underyling protocol implementation
|
||||
to react to that.
|
||||
|
||||
:param filename: the filename to add to the list
|
||||
:param filesize: the filesize to add to the list, may be None
|
||||
"""
|
||||
pass
|
||||
|
||||
def _addSdFiles(self, files):
|
||||
"""
|
||||
Adds a list of files to the SD file list
|
||||
|
||||
:param files: the list of file tuples (name, size) to add to the list, size may be None
|
||||
"""
|
||||
for f in files:
|
||||
self._sd_files.append(f)
|
||||
self._sdFilesAdded(files)
|
||||
|
||||
def _sdFilesAdded(self, files):
|
||||
"""
|
||||
Called when a list of files has been added to the SD file list, can be used by the underlying protocol
|
||||
implementation to react to that.
|
||||
|
||||
:param files: the file tuples (name, size) added to the list, size may be None
|
||||
"""
|
||||
pass
|
||||
|
||||
def _resetSdFiles(self):
|
||||
"""
|
||||
Resets the SD file list
|
||||
"""
|
||||
self._sd_files = []
|
||||
self._sdFilesReset()
|
||||
|
||||
def _sdFilesReset(self):
|
||||
"""
|
||||
Called when the list of SD files has been reset, can be used in the underlying protocol implementation to
|
||||
react to that
|
||||
"""
|
||||
pass
|
||||
|
||||
def _heatupDetected(self):
|
||||
"""
|
||||
Called when the underlying protocol detects the beginning of a heat-up interval.
|
||||
"""
|
||||
self._heatup_start_time = time.time()
|
||||
|
||||
def _heatupDone(self):
|
||||
"""
|
||||
Called when the underlying protocol detects the end of a heat-up interval.
|
||||
"""
|
||||
if self._heatup_start_time is not None:
|
||||
self._heatup_time_lost += time.time() - self._heatup_start_time
|
||||
self._heatup_start_time = None
|
||||
|
||||
def _log_error(self, error):
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onLogError(self, error)
|
||||
|
||||
##~~ StateReceiver
|
||||
|
||||
def onStateChangeReceived(self, source, oldState, newState):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if newState == TransportState.DETECTING_CONNECTION or newState == TransportState.OPENING_CONNECTION:
|
||||
self._changeState(State.CONNECTING)
|
||||
elif newState == TransportState.CONNECTED:
|
||||
self._changeState(State.CONNECTED)
|
||||
elif newState == TransportState.DISCONNECTED:
|
||||
self._changeState(State.OFFLINE)
|
||||
elif newState == TransportState.DISCONNECTED_WITH_ERROR or newState == TransportState.ERROR:
|
||||
self.onError(self._transport.getError())
|
||||
try:
|
||||
self._transport.disconnect()
|
||||
except:
|
||||
# TODO do we need to handle that?
|
||||
pass
|
||||
|
||||
##~~ MessageReceiver
|
||||
|
||||
def onError(self, error):
|
||||
self._changeState(State.ERROR)
|
||||
self._error = error
|
||||
eventManager().fire(Events.ERROR, {"error": error})
|
||||
|
||||
##~~ LogReceiver
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onLogRx(self, rx)
|
||||
|
||||
def onLogTx(self, source, tx):
|
||||
if self._transport != source:
|
||||
return
|
||||
|
||||
if self._protocol_listener is not None:
|
||||
self._protocol_listener.onLogTx(self, tx)
|
||||
|
||||
def onLogError(self, source, error):
|
||||
if self._transport != source:
|
||||
return
|
||||
self._log_error(error)
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def _getPrintCompletion(self):
|
||||
if self._current_file is None:
|
||||
return None
|
||||
return self._current_file.getProgress() * 100
|
||||
|
||||
def _getPrintFilepos(self):
|
||||
if self._current_file is None:
|
||||
return None
|
||||
return self._current_file.getFilepos()
|
||||
|
||||
|
||||
class ProtocolListener(object):
|
||||
def onStateChange(self, source, oldState, newState):
|
||||
pass
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
pass
|
||||
|
||||
def onProgress(self, source, progress):
|
||||
pass
|
||||
|
||||
def onZChange(self, source, oldZ, newZ):
|
||||
pass
|
||||
|
||||
def onFileSelected(self, source, filename, filesize, origin):
|
||||
pass
|
||||
|
||||
def onPrintjobStarted(self, source):
|
||||
pass
|
||||
|
||||
def onPrintjobDone(self, source):
|
||||
pass
|
||||
|
||||
def onPrintjobCancelled(self, source):
|
||||
pass
|
||||
|
||||
def onFileTransferStarted(self, source, filename, filesize):
|
||||
pass
|
||||
|
||||
def onFileTransferDone(self, source):
|
||||
pass
|
||||
|
||||
def onSdStateChange(self, source, sdAvailable):
|
||||
pass
|
||||
|
||||
def onSdFiles(self, source, files):
|
||||
pass
|
||||
|
||||
def onLogTx(self, source, tx):
|
||||
pass
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
pass
|
||||
|
||||
def onLogError(self, source, error):
|
||||
pass
|
||||
|
||||
|
||||
class State(object):
|
||||
|
||||
OFFLINE = "Offline"
|
||||
CONNECTING = "Connecting"
|
||||
CONNECTED = "Connected"
|
||||
OPERATIONAL = "Operational"
|
||||
PRINTING = "Printing"
|
||||
STREAMING = "Streaming"
|
||||
PAUSED = "Paused"
|
||||
ERROR = "Error"
|
||||
|
||||
|
||||
### Printing file information classes ##################################################################################
|
||||
|
||||
class PrintingFileInformation(object):
|
||||
"""
|
||||
Encapsulates information regarding the current file being printed: file name, current position, total size and
|
||||
time the print started.
|
||||
Allows to reset the current file position to 0 and to calculate the current progress as a floating point
|
||||
value between 0 and 1.
|
||||
"""
|
||||
|
||||
def __init__(self, filename):
|
||||
self._filename = filename
|
||||
self._filepos = 0
|
||||
self._filesize = None
|
||||
self._startTime = None
|
||||
|
||||
def getStartTime(self):
|
||||
return self._startTime
|
||||
|
||||
def getFilename(self):
|
||||
return self._filename
|
||||
|
||||
def getFilesize(self):
|
||||
return self._filesize
|
||||
|
||||
def getFilepos(self):
|
||||
return self._filepos
|
||||
|
||||
def getFileLocation(self):
|
||||
return FileDestinations.LOCAL
|
||||
|
||||
def getProgress(self):
|
||||
"""
|
||||
The current progress of the file, calculated as relation between file position and absolute size. Returns -1
|
||||
if file size is None or < 1.
|
||||
"""
|
||||
if self._filesize is None or not self._filesize > 0:
|
||||
return -1
|
||||
return float(self._filepos) / float(self._filesize)
|
||||
|
||||
def reset(self):
|
||||
"""
|
||||
Resets the current file position to 0.
|
||||
"""
|
||||
self._filepos = 0
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Marks the print job as started and remembers the start time.
|
||||
"""
|
||||
self._startTime = time.time()
|
||||
|
||||
|
||||
class PrintingSdFileInformation(PrintingFileInformation):
|
||||
"""
|
||||
Encapsulates information regarding an ongoing print from SD.
|
||||
"""
|
||||
|
||||
def __init__(self, filename, filesize):
|
||||
PrintingFileInformation.__init__(self, filename)
|
||||
self._filesize = filesize
|
||||
|
||||
def setFilepos(self, filepos):
|
||||
"""
|
||||
Sets the current file position.
|
||||
"""
|
||||
self._filepos = filepos
|
||||
|
||||
def getFileLocation(self):
|
||||
return FileDestinations.SDCARD
|
||||
@@ -0,0 +1,59 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
from octoprint.comm.protocol.reprap import RepRapProtocol
|
||||
|
||||
|
||||
class RepetierTextualProtocol(RepRapProtocol):
|
||||
|
||||
__protocolinfo__ = ("repetier", "RepRap (Repetier Flavor)", False)
|
||||
|
||||
MESSAGE_TARGET_TEMPERATURE = staticmethod(lambda line: "TargetExtr" in line or "TargetBed" in line)
|
||||
MESSAGE_TEMPERATURE = staticmethod(lambda line: RepRapProtocol.MESSAGE_TEMPERATURE(line) or RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line))
|
||||
|
||||
REGEX_POSITIVE_FLOAT = "[+]?[0-9]*\.?[0-9]+"
|
||||
REGEX_TARGET_EXTRUDER_TEMPERATURE = re.compile("TargetExtr([0-9]+):(%s)" % REGEX_POSITIVE_FLOAT)
|
||||
REGEX_TARGET_BED_TEMPERATURE = re.compile("TargetBed:(%s)" % REGEX_POSITIVE_FLOAT)
|
||||
|
||||
def __init__(self, transport_factory, protocol_listener=None):
|
||||
RepRapProtocol.__init__(self, transport_factory, protocol_listener)
|
||||
self._sd_available = True
|
||||
|
||||
def _reset(self, from_start=False):
|
||||
RepRapProtocol._reset(self, from_start=from_start)
|
||||
self._sd_available = True
|
||||
|
||||
def _process_temperatures(self, line):
|
||||
if RepetierTextualProtocol.MESSAGE_TARGET_TEMPERATURE(line):
|
||||
match_extr = RepetierTextualProtocol.REGEX_TARGET_EXTRUDER_TEMPERATURE.match(line)
|
||||
match_bed = RepetierTextualProtocol.REGEX_TARGET_BED_TEMPERATURE.match(line)
|
||||
|
||||
current_temperatures = self.get_current_temperatures()
|
||||
key = None
|
||||
target = None
|
||||
try:
|
||||
if match_extr is not None:
|
||||
tool_num = int(match_extr.group(1))
|
||||
key = "tool%d" % tool_num
|
||||
target = float(match_extr.group(2))
|
||||
elif match_bed is not None:
|
||||
key = "bed"
|
||||
target = float(match_bed.group(1))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if key is None:
|
||||
return False
|
||||
|
||||
if key in current_temperatures and current_temperatures[key] is not None and isinstance(current_temperatures[key], tuple):
|
||||
(actual, old_target) = current_temperatures[key]
|
||||
current_temperatures[key] = (actual, target)
|
||||
else:
|
||||
current_temperatures[key] = (None, target)
|
||||
self._updateTemperature(current_temperatures)
|
||||
else:
|
||||
RepRapProtocol._process_temperatures(self, line)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,377 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
import Queue
|
||||
import re
|
||||
import heapq
|
||||
import os
|
||||
import time
|
||||
import itertools
|
||||
|
||||
from octoprint.comm.protocol import PrintingFileInformation
|
||||
|
||||
|
||||
class GcodeCommand(object):
|
||||
|
||||
KNOWN_FLOAT_ATTRIBUTES = ("x", "y", "z", "e", "s", "p", "r")
|
||||
KNOWN_INT_ATTRIBUTES = ("f", "t", "n")
|
||||
KNOWN_ATTRIBUTES = KNOWN_FLOAT_ATTRIBUTES + KNOWN_INT_ATTRIBUTES
|
||||
|
||||
COMMAND_REGEX = re.compile("^([GMT])(\d+)")
|
||||
ARGUMENT_REGEX = re.compile("\s+([%s][-+]?\d*\.?\d+|[%s][-+]?\d+)" % ("".join(map(lambda x: x.upper(), KNOWN_FLOAT_ATTRIBUTES)), "".join(map(lambda x: x.upper(), KNOWN_INT_ATTRIBUTES))))
|
||||
PARAM_REGEX = re.compile("^[GMT]\d+\s+(.*?)$")
|
||||
|
||||
@staticmethod
|
||||
def from_line(line):
|
||||
line = line.strip()
|
||||
command = ""
|
||||
args = {"original": line}
|
||||
match = GcodeCommand.COMMAND_REGEX.match(line)
|
||||
if match is None:
|
||||
args["unknown"] = True
|
||||
else:
|
||||
commandType = match.group(1)
|
||||
commandNumber = int(match.group(2))
|
||||
command = "%s%d" % (commandType, commandNumber)
|
||||
|
||||
|
||||
if commandType == "T":
|
||||
args["tool"] = commandNumber
|
||||
else:
|
||||
matchedArgs = GcodeCommand.ARGUMENT_REGEX.findall(line)
|
||||
if len(matchedArgs) == 0:
|
||||
paramMatch = GcodeCommand.PARAM_REGEX.match(line)
|
||||
if paramMatch is not None:
|
||||
args["param"] = paramMatch.group(1)
|
||||
else:
|
||||
for arg in matchedArgs:
|
||||
key = arg[0].lower()
|
||||
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
|
||||
value = int(arg[1:])
|
||||
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
|
||||
value = float(arg[1:])
|
||||
else:
|
||||
value = str(arg[1:])
|
||||
args[key] = value
|
||||
|
||||
return GcodeCommand(command, **args)
|
||||
|
||||
def __init__(self, command, **kwargs):
|
||||
self.command = command
|
||||
self.x = None
|
||||
self.y = None
|
||||
self.z = None
|
||||
self.e = None
|
||||
self.s = None
|
||||
self.p = None
|
||||
self.r = None
|
||||
self.f = None
|
||||
self.t = None
|
||||
self.n = None
|
||||
|
||||
self.tool = None
|
||||
self.original = None
|
||||
self.param = None
|
||||
|
||||
self.progress = None
|
||||
self.callback = None
|
||||
|
||||
self.unknown = False
|
||||
|
||||
for key, value in kwargs.iteritems():
|
||||
if key in GcodeCommand.KNOWN_ATTRIBUTES + ("tool", "original", "param", "progress", "callback", "unknown"):
|
||||
self.__setattr__(key, value)
|
||||
|
||||
def isGetTemperatureCommand(self):
|
||||
return self.command == "M105"
|
||||
|
||||
def isSetTemperatureCommand(self):
|
||||
return self.command in ("M104", "M140", "M109", "M190")
|
||||
|
||||
def isSelectToolCommand(self):
|
||||
return self.command.startswith("T")
|
||||
|
||||
def __repr__(self):
|
||||
return "GcodeCommand(\"{str}\",progress={progress})".format(str=str(self), progress=self.progress)
|
||||
|
||||
def __str__(self):
|
||||
if self.original is not None:
|
||||
return self.original
|
||||
else:
|
||||
attr = []
|
||||
for key in GcodeCommand.KNOWN_ATTRIBUTES:
|
||||
value = self.__getattribute__(key)
|
||||
if value is not None:
|
||||
if key in GcodeCommand.KNOWN_INT_ATTRIBUTES:
|
||||
attr.append("%s%d" % (key.upper(), value))
|
||||
elif key in GcodeCommand.KNOWN_FLOAT_ATTRIBUTES:
|
||||
attr.append("%s%f" % (key.upper(), value))
|
||||
else:
|
||||
attr.append("%s%r" % (key.upper(), value))
|
||||
attributeStr = " ".join(attr)
|
||||
return "%s%s%s" % (self.command.upper(), " " + attributeStr if attributeStr else "", " " + self.param if self.param else "")
|
||||
|
||||
|
||||
class CommandQueueEntry(object):
|
||||
PRIORITY_RESEND = 1
|
||||
PRIORITY_HIGH = 2
|
||||
PRIORITY_NORMAL = 3
|
||||
|
||||
def __init__(self, priority, command, line_number=None, command_type=None, prepared=None):
|
||||
self.priority = priority
|
||||
self.command = command
|
||||
self.line_number = line_number
|
||||
self.command_type = command_type
|
||||
self._prepared = prepared
|
||||
self._size = 0
|
||||
|
||||
@property
|
||||
def prepared(self):
|
||||
return self._prepared
|
||||
|
||||
@prepared.setter
|
||||
def prepared(self, prepared):
|
||||
self._prepared = prepared
|
||||
self._size = (len(prepared) + 1) if prepared is not None else 0
|
||||
|
||||
@property
|
||||
def size(self):
|
||||
return self._size
|
||||
|
||||
def __radd__(self, other):
|
||||
return other + self._size
|
||||
|
||||
def __repr__(self):
|
||||
return "CommandQueueEntry({command},prepared={prepared})".format(command=repr(self.command), prepared=self.prepared)
|
||||
|
||||
|
||||
class SpecialCommandQueueEntry(CommandQueueEntry):
|
||||
TYPE_JOBDONE = "JobDone"
|
||||
TYPE_JOBCANCELLED = "JobCancelled"
|
||||
|
||||
def __init__(self, type):
|
||||
CommandQueueEntry.__init__(self, CommandQueueEntry.PRIORITY_NORMAL, None)
|
||||
self.type = type
|
||||
|
||||
def __repr__(self):
|
||||
return "SpecialCommandQueueEntry(type={type})".format(type=self.type)
|
||||
|
||||
|
||||
class CommandQueue(Queue.Queue):
|
||||
'''Variant of Queue that retrieves open entries in priority order (lowest first, followed by addition order).
|
||||
|
||||
Entries need to be of the form (priority, command). An optional third argument commandType may be given:
|
||||
(priority, command, commandType), the queue will ensure that only one command of a given commandType will ever
|
||||
be in the queue.
|
||||
'''
|
||||
|
||||
def _init(self, maxsize):
|
||||
self.queue = []
|
||||
self.lookup = {}
|
||||
self.counter = itertools.count()
|
||||
|
||||
import threading
|
||||
self.clearlock = threading.RLock()
|
||||
|
||||
def _qsize(self, len=len):
|
||||
return len(self.queue)
|
||||
|
||||
def _put(self, item, heappush=heapq.heappush):
|
||||
if not isinstance(item, CommandQueueEntry):
|
||||
raise ValueError("queue can only take CommandQueueEntries, can't accept %r" % item)
|
||||
|
||||
command_type = item.command_type
|
||||
if command_type is not None:
|
||||
if command_type not in self.lookup:
|
||||
self.lookup[command_type] = item
|
||||
else:
|
||||
raise TypeAlreadyInQueue()
|
||||
|
||||
heappush(self.queue, (item.priority, next(self.counter), item))
|
||||
|
||||
def _get(self, heappop=heapq.heappop):
|
||||
priority, counter, item = heappop(self.queue)
|
||||
if item.command_type in self.lookup:
|
||||
del self.lookup[item.command_type]
|
||||
return item
|
||||
|
||||
def _entry_at(self, index):
|
||||
try:
|
||||
return self.queue[index]
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
def _del(self, entry, heapify=True):
|
||||
item = entry[2]
|
||||
try:
|
||||
self.queue.remove(entry)
|
||||
if heapify:
|
||||
heapq.heapify(self.queue)
|
||||
except ValueError:
|
||||
# that's ok, the entry probably just got removed already e.g. by print cancelling
|
||||
pass
|
||||
|
||||
if item.command_type in self.lookup:
|
||||
del self.lookup[item.command_type]
|
||||
|
||||
def peek(self):
|
||||
"""
|
||||
Returns the left most entry, result is either a tuple (priority, counter, CommandQueueEntry) or None (if queue
|
||||
was empty).
|
||||
"""
|
||||
|
||||
with self.mutex:
|
||||
entry = self._entry_at(0)
|
||||
return entry[2] if entry is not None else None, entry
|
||||
|
||||
def remove(self, entry):
|
||||
with self.mutex:
|
||||
self._del(entry)
|
||||
|
||||
def clear(self, matcher=None):
|
||||
if matcher is None:
|
||||
matcher = lambda x: True
|
||||
|
||||
cleared = []
|
||||
with self.clearlock:
|
||||
for entry in self.queue[:]:
|
||||
priority, counter, item = entry
|
||||
if matcher(item):
|
||||
self._del(entry, heapify=False)
|
||||
cleared.append(entry)
|
||||
heapq.heapify(self.queue)
|
||||
return cleared
|
||||
|
||||
def __repr__(self):
|
||||
return repr(self.queue)
|
||||
|
||||
class TypeAlreadyInQueue(Exception):
|
||||
pass
|
||||
|
||||
class PrintingGcodeFileInformation(PrintingFileInformation):
|
||||
"""
|
||||
Encapsulates information regarding an ongoing direct print. Takes care of the needed file handle and ensures
|
||||
that the file is closed in case of an error.
|
||||
"""
|
||||
|
||||
def __init__(self, filename, offsetCallback):
|
||||
PrintingFileInformation.__init__(self, filename)
|
||||
self._lineCount = None
|
||||
self._firstLine = None
|
||||
self._currentTool = 0
|
||||
|
||||
self._offsetCallback = offsetCallback
|
||||
|
||||
self._fileHandle = None
|
||||
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
|
||||
raise IOError("File %s does not exist" % self._filename)
|
||||
self._filesize = os.stat(self._filename).st_size
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Opens the file for reading and determines the file size. Start time won't be recorded until 100 lines in
|
||||
"""
|
||||
self._filehandle = open(self._filename, "r")
|
||||
self._lineCount = None
|
||||
self._startTime = None
|
||||
|
||||
def getNext(self):
|
||||
"""
|
||||
Retrieves the next line for printing.
|
||||
"""
|
||||
if self._filehandle is None:
|
||||
raise ValueError("File %s is not open for reading" % self._filename)
|
||||
|
||||
if self._lineCount is None:
|
||||
self._lineCount = 0
|
||||
self._startTime = time.time()
|
||||
return GcodeCommand.from_line("M110 N0")
|
||||
|
||||
try:
|
||||
command = None
|
||||
while command is None:
|
||||
if self._filehandle is None:
|
||||
# file got closed just now
|
||||
return None
|
||||
line = self._filehandle.readline()
|
||||
if not line:
|
||||
self._filehandle.close()
|
||||
self._filehandle = None
|
||||
command = self._process_command(line)
|
||||
self._lineCount += 1
|
||||
self._filepos = self._filehandle.tell()
|
||||
|
||||
return command
|
||||
except Exception as (e):
|
||||
if self._filehandle is not None:
|
||||
self._filehandle.close()
|
||||
self._filehandle = None
|
||||
raise e
|
||||
|
||||
def _process_command(self, line):
|
||||
# remove all comments and trim the line
|
||||
if ";" in line:
|
||||
line = line[0:line.find(";")]
|
||||
line = line.strip()
|
||||
|
||||
if len(line) > 0:
|
||||
# we still got something left => parse the command
|
||||
command = GcodeCommand.from_line(line)
|
||||
if command is None:
|
||||
return None
|
||||
|
||||
if command.isSelectToolCommand():
|
||||
# track tool changes
|
||||
self._currentTool = command.tool
|
||||
|
||||
elif command.isSetTemperatureCommand() and self._offsetCallback is not None:
|
||||
# if we have a temperature command and an offset callback, retrieve current offsets
|
||||
offsets = self._offsetCallback()
|
||||
|
||||
# extruder temperature, determine which one and retrieve corresponding offset
|
||||
if command.command == "M104" or command.command == "M109":
|
||||
tool_num = self._currentTool
|
||||
if command.t is not None:
|
||||
tool_num = command.t
|
||||
|
||||
key = "tool%d" % tool_num
|
||||
|
||||
# bed temperature
|
||||
elif command.command == "M140" or command.command == "M190":
|
||||
key = "bed"
|
||||
|
||||
# unknown, should never happen
|
||||
else:
|
||||
key = None
|
||||
|
||||
if key is not None and key in offsets:
|
||||
offset = offsets[key]
|
||||
command.s = command.s + offset
|
||||
if command.original is not None:
|
||||
command.original = None
|
||||
|
||||
# finally return the processed command
|
||||
return command
|
||||
else:
|
||||
# no command, return None
|
||||
return None
|
||||
|
||||
|
||||
class StreamingGcodeFileInformation(PrintingGcodeFileInformation):
|
||||
def __init__(self, path, localFilename, remoteFilename):
|
||||
PrintingGcodeFileInformation.__init__(self, path, None)
|
||||
self._localFilename = localFilename
|
||||
self._remoteFilename = remoteFilename
|
||||
|
||||
def start(self):
|
||||
PrintingGcodeFileInformation.start(self)
|
||||
self._startTime = time.time()
|
||||
|
||||
def getLocalFilename(self):
|
||||
return self._localFilename
|
||||
|
||||
def getRemoteFilename(self):
|
||||
return self._remoteFilename
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
class TransportError(Exception):
|
||||
pass
|
||||
|
||||
class SendTimeout(Exception):
|
||||
pass
|
||||
|
||||
class Transport(object):
|
||||
|
||||
def __init__(self, messageReceiver=None, stateReceiver=None, logReceiver=None):
|
||||
self._transport_logger = logging.getLogger("TRANSPORT")
|
||||
|
||||
self._messageReceiver = messageReceiver
|
||||
self._stateReceiver = stateReceiver
|
||||
self._logReceiver = logReceiver
|
||||
self._state = State.DISCONNECTED
|
||||
self._error = None
|
||||
self._opt = {}
|
||||
|
||||
def get_properties(self):
|
||||
raise NotImplemented()
|
||||
|
||||
def get_connection_options(self):
|
||||
return []
|
||||
|
||||
def get_current_connection(self):
|
||||
return self._opt
|
||||
|
||||
def connect(self, opt):
|
||||
self._opt = opt
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
if onError:
|
||||
self.changeState(State.DISCONNECTED_WITH_ERROR)
|
||||
else:
|
||||
self.changeState(State.DISCONNECTED)
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
def send(self, command):
|
||||
pass
|
||||
|
||||
def receive(self):
|
||||
pass
|
||||
|
||||
def changeState(self, newState):
|
||||
oldState = self._state
|
||||
self._state = newState
|
||||
if self._stateReceiver is not None:
|
||||
self._stateReceiver.onStateChangeReceived(self, oldState, newState)
|
||||
|
||||
def onError(self, error):
|
||||
self.changeState(State.ERROR)
|
||||
self._error = error
|
||||
|
||||
def onTimeout(self):
|
||||
if self._messageReceiver is not None:
|
||||
self._messageReceiver.onTimeoutReceived(self)
|
||||
|
||||
def getError(self):
|
||||
return self._error
|
||||
|
||||
def logTx(self, tx):
|
||||
if self._logReceiver is not None:
|
||||
self._logReceiver.onLogTx(self, tx)
|
||||
|
||||
def logRx(self, rx):
|
||||
if self._logReceiver is not None:
|
||||
self._logReceiver.onLogRx(self, rx)
|
||||
|
||||
def logError(self, error):
|
||||
if self._logReceiver is not None:
|
||||
self._logReceiver.onLogError(self, error)
|
||||
|
||||
def onMessageReceived(self, message):
|
||||
if self._messageReceiver is not None:
|
||||
self._messageReceiver.onMessageReceived(self, message)
|
||||
|
||||
|
||||
class TransportProperties(object):
|
||||
|
||||
FLOWCONTROL = "flowControl"
|
||||
|
||||
|
||||
class State(object):
|
||||
OPENING_CONNECTION = "Opening connection"
|
||||
DETECTING_CONNECTION = "Detecting connection"
|
||||
CONNECTED = "Connected"
|
||||
DISCONNECTED = "Disconnected"
|
||||
DISCONNECTED_WITH_ERROR = "Disconnected with error"
|
||||
ERROR = "Error"
|
||||
|
||||
|
||||
class MessageReceiver(object):
|
||||
def onMessageReceived(self, source, message):
|
||||
pass
|
||||
|
||||
def onTimeoutReceived(self, source):
|
||||
pass
|
||||
|
||||
|
||||
class StateReceiver(object):
|
||||
def onStateChangeReceived(self, source, oldState, newState):
|
||||
pass
|
||||
|
||||
|
||||
class LogReceiver(object):
|
||||
def onLogTx(self, source, tx):
|
||||
pass
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
pass
|
||||
|
||||
def onLogError(self, source, error):
|
||||
pass
|
||||
@@ -0,0 +1,192 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 Gina Häußge - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
import glob
|
||||
import threading
|
||||
import serial
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
except:
|
||||
pass
|
||||
|
||||
from . import Transport, TransportProperties, State, SendTimeout, TransportError
|
||||
from octoprint.util import getExceptionString
|
||||
from octoprint.util.virtual import VirtualPrinter
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
class SerialTransport(Transport):
|
||||
|
||||
__transportinfo__ = ("serial", "Serial", False)
|
||||
|
||||
def __init__(self, messageReceiver, stateReceiver, logReceiver):
|
||||
Transport.__init__(self, messageReceiver, stateReceiver, logReceiver)
|
||||
|
||||
self._serial = None
|
||||
self._port = None
|
||||
self._baudrate = None
|
||||
self._connectionTimeout = None
|
||||
self._writeTimeout = None
|
||||
self._readTimeout = None
|
||||
|
||||
self._timeoutCounter = 0
|
||||
self._maxTimeouts = 20
|
||||
|
||||
self._thread = None
|
||||
|
||||
def get_properties(self):
|
||||
return {
|
||||
TransportProperties.FLOWCONTROL: False
|
||||
}
|
||||
|
||||
def get_connection_options(self):
|
||||
return {
|
||||
"port": self.__getSerialList(),
|
||||
"baudrate": self.__getBaudrateList()
|
||||
}
|
||||
|
||||
def connect(self, opt):
|
||||
Transport.connect(self, opt)
|
||||
|
||||
self._port = opt["port"] if "port" in opt else None
|
||||
self._baudrate = opt["baudrate"] if "baudrate" in opt else None
|
||||
|
||||
self._readTimeout = opt["timeout"]["read"] if "timeout" in opt and "read" in opt["timeout"] else 5.0
|
||||
self._writeTimeout = opt["timeout"]["write"] if "timeout" in opt and "write" in opt["timeout"] else 0.5
|
||||
|
||||
if self._connect():
|
||||
self._thread = threading.Thread(target=self._monitor, name="SerialTransportMonitor")
|
||||
self._thread.daemon = True
|
||||
self._thread.start()
|
||||
|
||||
def disconnect(self, onError=False):
|
||||
try:
|
||||
if self._serial is not None:
|
||||
self._serial.close()
|
||||
finally:
|
||||
self._serial = None
|
||||
self._thread = None
|
||||
Transport.disconnect(self, onError)
|
||||
|
||||
def send(self, command):
|
||||
commandToSend = command + "\n"
|
||||
try:
|
||||
self._serial.write(commandToSend)
|
||||
self._transport_logger.info("Send: %s" % command)
|
||||
self.logTx(command)
|
||||
except serial.SerialTimeoutException:
|
||||
self._transport_logger.warn("Timeout while sending: %s" % command)
|
||||
self.logError("Serial timeout while writing to serial port, try again later.")
|
||||
raise SendTimeout()
|
||||
except:
|
||||
exceptionString = getExceptionString()
|
||||
self.logError("Unexpected error while writing serial port: %s" % exceptionString)
|
||||
self.onError(exceptionString)
|
||||
self.disconnect(True)
|
||||
raise TransportError()
|
||||
|
||||
def receive(self):
|
||||
return self._readline()
|
||||
|
||||
def _monitor(self):
|
||||
error = None
|
||||
while True:
|
||||
line = self._readline()
|
||||
if line is None:
|
||||
error = "Serial connection closed unexpectedly"
|
||||
break
|
||||
if line == "":
|
||||
self._timeoutCounter += 1
|
||||
self.onTimeout()
|
||||
if self._maxTimeouts and self._timeoutCounter > self._maxTimeouts:
|
||||
error = "Printer did not respond at all over %d retries, considering it dead" % self._maxTimeouts
|
||||
break
|
||||
else:
|
||||
self._timeoutCounter = 0
|
||||
self.onMessageReceived(line.strip())
|
||||
|
||||
if error is not None:
|
||||
self._transport_logger.error(error)
|
||||
self.logError(error)
|
||||
self.onError(error)
|
||||
# TODO further error handling
|
||||
|
||||
def _connect(self):
|
||||
self.changeState(State.OPENING_CONNECTION)
|
||||
if self._port == "VIRTUAL":
|
||||
self._serial = VirtualPrinter(read_timeout=self._readTimeout, write_timeout=self._writeTimeout)
|
||||
self.changeState(State.CONNECTED)
|
||||
self._transport_logger.debug("Connected to %s" % self._serial)
|
||||
else:
|
||||
try:
|
||||
self._serial = serial.Serial(self._port, self._baudrate, timeout=self._readTimeout, writeTimeout=self._writeTimeout)
|
||||
self.changeState(State.CONNECTED)
|
||||
self._transport_logger.debug("Connected to %s" % self._serial)
|
||||
except:
|
||||
self.logError("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
|
||||
self.onError("Failed to open serial port, permissions correct?")
|
||||
return False
|
||||
eventManager().fire(Events.CONNECTED, {"port": self._port, "baudrate": self._baudrate})
|
||||
return True
|
||||
|
||||
def _readline(self):
|
||||
if self._serial is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
line = self._serial.readline()
|
||||
except:
|
||||
exceptionString = getExceptionString()
|
||||
self.logError("Unexpected error while reading serial port: %s" % exceptionString)
|
||||
self.onError(exceptionString)
|
||||
self.disconnect()
|
||||
return None
|
||||
|
||||
if line != "":
|
||||
loggable_line = unicode(line, "ascii", "replace").encode("ascii", "replace").rstrip()
|
||||
self._transport_logger.debug("Recv: %s" % loggable_line)
|
||||
self.logRx(loggable_line)
|
||||
return line
|
||||
|
||||
def __getSerialList(self):
|
||||
baselist=[]
|
||||
if os.name == "nt":
|
||||
try:
|
||||
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
|
||||
i=0
|
||||
while(1):
|
||||
baselist+=[_winreg.EnumValue(key,i)[1]]
|
||||
i+=1
|
||||
except:
|
||||
pass
|
||||
baselist = baselist \
|
||||
+ glob.glob("/dev/ttyUSB*") \
|
||||
+ glob.glob("/dev/ttyACM*") \
|
||||
+ glob.glob("/dev/ttyAMA*") \
|
||||
+ glob.glob("/dev/tty.usb*") \
|
||||
+ glob.glob("/dev/cu.*") \
|
||||
+ glob.glob("/dev/rfcomm*")
|
||||
|
||||
additionalPorts = settings().get(["serial", "additionalPorts"])
|
||||
for additional in additionalPorts:
|
||||
baselist += glob.glob(additional)
|
||||
|
||||
prev = settings().get(["serial", "port"])
|
||||
if prev in baselist:
|
||||
baselist.remove(prev)
|
||||
baselist.insert(0, prev)
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "enabled"]):
|
||||
baselist.append("VIRTUAL")
|
||||
return baselist
|
||||
|
||||
def __getBaudrateList(self):
|
||||
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
|
||||
prev = settings().getInt(["serial", "baudrate"])
|
||||
if prev in ret:
|
||||
ret.remove(prev)
|
||||
ret.insert(0, prev)
|
||||
return ret
|
||||
+170
-79
@@ -1,33 +1,106 @@
|
||||
# coding=utf-8
|
||||
from __future__ import (print_function, absolute_import)
|
||||
|
||||
__author__ = "Lars Norpchen"
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import subprocess
|
||||
import Queue
|
||||
import threading
|
||||
import collections
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.plugin
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
|
||||
def all_events():
|
||||
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
|
||||
|
||||
|
||||
class Events(object):
|
||||
# application startup
|
||||
STARTUP = "Startup"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTED = "Connected"
|
||||
DISCONNECTED = "Disconnected"
|
||||
|
||||
# connect/disconnect by client
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
CLIENT_CLOSED = "ClientClosed"
|
||||
|
||||
# File management
|
||||
UPLOAD = "Upload"
|
||||
FILE_SELECTED = "FileSelected"
|
||||
FILE_DESELECTED = "FileDeselected"
|
||||
UPDATED_FILES = "UpdatedFiles"
|
||||
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
TRANSFER_DONE = "TransferDone"
|
||||
|
||||
# print job
|
||||
PRINT_STARTED = "PrintStarted"
|
||||
PRINT_DONE = "PrintDone"
|
||||
PRINT_FAILED = "PrintFailed"
|
||||
PRINT_CANCELLED = "PrintCancelled"
|
||||
PRINT_PAUSED = "PrintPaused"
|
||||
PRINT_RESUMED = "PrintResumed"
|
||||
ERROR = "Error"
|
||||
|
||||
# print/gcode events
|
||||
POWER_ON = "PowerOn"
|
||||
POWER_OFF = "PowerOff"
|
||||
HOME = "Home"
|
||||
Z_CHANGE = "ZChange"
|
||||
WAITING = "Waiting"
|
||||
DWELL = "Dwelling"
|
||||
COOLING = "Cooling"
|
||||
ALERT = "Alert"
|
||||
CONVEYOR = "Conveyor"
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
|
||||
# Slicing
|
||||
SLICING_STARTED = "SlicingStarted"
|
||||
SLICING_DONE = "SlicingDone"
|
||||
SLICING_FAILED = "SlicingFailed"
|
||||
SLICING_CANCELLED = "SlicingCancelled"
|
||||
|
||||
# Settings
|
||||
SETTINGS_UPDATED = "SettingsUpdated"
|
||||
|
||||
|
||||
def eventManager():
|
||||
global _instance
|
||||
if _instance is None:
|
||||
_instance = EventManager()
|
||||
return _instance
|
||||
|
||||
|
||||
class EventManager(object):
|
||||
"""
|
||||
Handles receiving events and dispatching them to subscribers
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._registeredListeners = {}
|
||||
self._registeredListeners = collections.defaultdict(list)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
@@ -39,9 +112,7 @@ class EventManager(object):
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
|
||||
eventListeners = self._registeredListeners.get(event, None)
|
||||
if eventListeners is None:
|
||||
return
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
@@ -51,6 +122,10 @@ class EventManager(object):
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
"""
|
||||
Fire an event to anyone subscribed to it
|
||||
@@ -62,18 +137,22 @@ class EventManager(object):
|
||||
payload being a payload object specific to the event.
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners.keys():
|
||||
return
|
||||
self._queue.put((event, payload), 0)
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
# TODO v1.3.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
self._queue.put((event, legacy_payload), 0)
|
||||
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners.keys():
|
||||
self._registeredListeners[event] = []
|
||||
|
||||
if callback in self._registeredListeners[event]:
|
||||
# callback is already subscribed to the event
|
||||
return
|
||||
@@ -86,10 +165,6 @@ class EventManager(object):
|
||||
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
|
||||
"""
|
||||
|
||||
if not event in self._registeredListeners:
|
||||
# no callback registered for callback, just return
|
||||
return
|
||||
|
||||
if not callback in self._registeredListeners[event]:
|
||||
# callback not subscribed to event, just return
|
||||
return
|
||||
@@ -97,6 +172,7 @@ class EventManager(object):
|
||||
self._registeredListeners[event].remove(callback)
|
||||
self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event))
|
||||
|
||||
|
||||
class GenericEventListener(object):
|
||||
"""
|
||||
The GenericEventListener can be subclassed to easily create custom event listeners.
|
||||
@@ -128,51 +204,56 @@ class GenericEventListener(object):
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class DebugEventListener(GenericEventListener):
|
||||
def __init__(self):
|
||||
GenericEventListener.__init__(self)
|
||||
|
||||
events = ["Startup", "Connected", "Disconnected", "ClientOpen", "ClientClosed", "PowerOn", "PowerOff", "Upload",
|
||||
"FileSelected", "TransferStarted", "TransferDone", "PrintStarted", "PrintDone", "PrintFailed",
|
||||
"Cancelled", "Home", "ZChange", "Paused", "Waiting", "Cooling", "Alert", "Conveyor", "Eject",
|
||||
"CaptureStart", "CaptureDone", "MovieDone", "EStop", "Error"]
|
||||
events = filter(lambda x: not x.startswith("__"), dir(Events))
|
||||
self.subscribe(events)
|
||||
|
||||
def eventCallback(self, event, payload):
|
||||
GenericEventListener.eventCallback(self, event, payload)
|
||||
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
|
||||
class CommandTrigger(GenericEventListener):
|
||||
def __init__(self, triggerType, printer):
|
||||
def __init__(self, printer):
|
||||
GenericEventListener.__init__(self)
|
||||
self._printer = printer
|
||||
self._subscriptions = {}
|
||||
|
||||
self._initSubscriptions(triggerType)
|
||||
self._initSubscriptions()
|
||||
|
||||
def _initSubscriptions(self, triggerType):
|
||||
def _initSubscriptions(self):
|
||||
"""
|
||||
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
|
||||
respective commands.
|
||||
"""
|
||||
if not settings().get(["events", triggerType]):
|
||||
if not settings().get(["events"]):
|
||||
return
|
||||
|
||||
if not settings().getBoolean(["events", triggerType, "enabled"]):
|
||||
if not settings().getBoolean(["events", "enabled"]):
|
||||
return
|
||||
|
||||
eventsToSubscribe = []
|
||||
for subscription in settings().get(["events", triggerType, "subscriptions"]):
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys():
|
||||
self._logger.info("Invalid %s, missing either event or command: %r" % (triggerType, subscription))
|
||||
for subscription in settings().get(["events", "subscriptions"]):
|
||||
if not "event" in subscription.keys() or not "command" in subscription.keys() \
|
||||
or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]:
|
||||
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: %r" % subscription)
|
||||
continue
|
||||
|
||||
if "enabled" in subscription.keys() and not subscription["enabled"]:
|
||||
self._logger.info("Disabled command trigger: %r" % subscription)
|
||||
continue
|
||||
|
||||
event = subscription["event"]
|
||||
command = subscription["command"]
|
||||
commandType = subscription["type"]
|
||||
|
||||
if not event in self._subscriptions.keys():
|
||||
self._subscriptions[event] = []
|
||||
self._subscriptions[event].append(command)
|
||||
self._subscriptions[event].append((command, commandType))
|
||||
|
||||
if not event in eventsToSubscribe:
|
||||
eventsToSubscribe.append(event)
|
||||
@@ -190,15 +271,48 @@ class CommandTrigger(GenericEventListener):
|
||||
if not event in self._subscriptions:
|
||||
return
|
||||
|
||||
for command in self._subscriptions[event]:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand)
|
||||
for command, commandType in self._subscriptions[event]:
|
||||
try:
|
||||
if isinstance(command, (tuple, list, set)):
|
||||
processedCommand = []
|
||||
for c in command:
|
||||
processedCommand.append(self._processCommand(c, payload))
|
||||
else:
|
||||
processedCommand = self._processCommand(command, payload)
|
||||
self.executeCommand(processedCommand, commandType)
|
||||
except KeyError, e:
|
||||
self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command)
|
||||
|
||||
def executeCommand(self, command):
|
||||
"""
|
||||
Not implemented, override in child classes
|
||||
"""
|
||||
pass
|
||||
def executeCommand(self, command, commandType):
|
||||
if commandType == "system":
|
||||
self._executeSystemCommand(command)
|
||||
elif commandType == "gcode":
|
||||
self._executeGcodeCommand(command)
|
||||
|
||||
def _executeSystemCommand(self, command):
|
||||
def commandExecutioner(command):
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
subprocess.Popen(command, shell=True)
|
||||
|
||||
try:
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
for c in command:
|
||||
commandExecutioner(c)
|
||||
else:
|
||||
commandExecutioner(command)
|
||||
except subprocess.CalledProcessError, e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
except Exception, ex:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
def _executeGcodeCommand(self, command):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self._logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
self._printer.commands(commands)
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
"""
|
||||
@@ -206,59 +320,36 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
- %(currentZ)s : current Z position of the print head, or -1 if not available
|
||||
- %(filename)s : current selected filename, or "NO FILE" if no file is selected
|
||||
- %(progress)s : current print progress in percent, 0 if no print is in progress
|
||||
- %(data)s : the string representation of the event's payload
|
||||
- %(now)s : ISO 8601 representation of the current date and time
|
||||
- {__currentZ} : current Z position of the print head, or -1 if not available
|
||||
- {__filename} : current selected filename, or "NO FILE" if no file is selected
|
||||
- {__progress} : current print progress in percent, 0 if no print is in progress
|
||||
- {__data} : the string representation of the event's payload
|
||||
- {__now} : ISO 8601 representation of the current date and time
|
||||
|
||||
Additionally, the keys of the event's payload can also be used as placeholder.
|
||||
"""
|
||||
|
||||
params = {
|
||||
"currentZ": "-1",
|
||||
"filename": "NO FILE",
|
||||
"progress": "0",
|
||||
"data": str(payload),
|
||||
"now": datetime.datetime.now().isoformat()
|
||||
"__currentZ": "-1",
|
||||
"__filename": "NO FILE",
|
||||
"__progress": "0",
|
||||
"__data": str(payload),
|
||||
"__now": datetime.datetime.now().isoformat()
|
||||
}
|
||||
|
||||
currentData = self._printer.getCurrentData()
|
||||
|
||||
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
|
||||
params["currentZ"] = str(currentData["currentZ"])
|
||||
params["__currentZ"] = str(currentData["currentZ"])
|
||||
|
||||
if "job" in currentData.keys() and currentData["job"] is not None:
|
||||
params["filename"] = currentData["job"]["filename"]
|
||||
params["__filename"] = currentData["job"]["file"]["name"]
|
||||
if "progress" in currentData.keys() and currentData["progress"] is not None \
|
||||
and "progress" in currentData["progress"].keys() and currentData["progress"]["progress"] is not None:
|
||||
params["progress"] = str(round(currentData["progress"]["progress"] * 100))
|
||||
and "completion" in currentData["progress"].keys() and currentData["progress"]["completion"] is not None:
|
||||
params["__progress"] = str(round(currentData["progress"]["completion"] * 100))
|
||||
|
||||
return command % params
|
||||
# now add the payload keys as well
|
||||
if isinstance(payload, dict):
|
||||
params.update(payload)
|
||||
|
||||
class SystemCommandTrigger(CommandTrigger):
|
||||
"""
|
||||
Performs configured system commands for configured events.
|
||||
"""
|
||||
|
||||
def __init__(self, printer):
|
||||
CommandTrigger.__init__(self, "systemCommandTrigger", printer)
|
||||
|
||||
def executeCommand(self, command):
|
||||
try:
|
||||
self._logger.info("Executing system command: %s" % command)
|
||||
subprocess.Popen(command, shell=True)
|
||||
except subprocess.CalledProcessError, e:
|
||||
self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
except Exception, ex:
|
||||
self._logger.exception("Command failed")
|
||||
|
||||
class GcodeCommandTrigger(CommandTrigger):
|
||||
"""
|
||||
Sends configured GCODE commands to the printer for configured events.
|
||||
"""
|
||||
|
||||
def __init__(self, printer):
|
||||
CommandTrigger.__init__(self, "gcodeCommandTrigger", printer)
|
||||
|
||||
def executeCommand(self, command):
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
self._printer.commands(command.split(","))
|
||||
return command.format(**params)
|
||||
@@ -0,0 +1,381 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
|
||||
from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
|
||||
extensions = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
)
|
||||
)
|
||||
|
||||
def get_extensions(type, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if key == type:
|
||||
return get_all_extensions(subtree=value)
|
||||
elif isinstance(value, dict):
|
||||
sub_extensions = get_extensions(type, subtree=value)
|
||||
if sub_extensions:
|
||||
return sub_extensions
|
||||
|
||||
return None
|
||||
|
||||
def get_all_extensions(subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
result = []
|
||||
if isinstance(subtree, dict):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
|
||||
def get_path_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
if path:
|
||||
return [key] + path
|
||||
|
||||
return None
|
||||
|
||||
all_extensions = get_all_extensions()
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in all_extensions
|
||||
else:
|
||||
extensions = get_extensions(type)
|
||||
if extensions:
|
||||
return extension in extensions
|
||||
|
||||
def valid_file_type(filename, type=None):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return valid_extension(extension, type=type)
|
||||
|
||||
def get_file_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FileManager(object):
|
||||
def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._analysis_queue = analysis_queue
|
||||
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
|
||||
|
||||
self._storage_managers = dict()
|
||||
if initial_storage_managers:
|
||||
self._storage_managers.update(initial_storage_managers)
|
||||
|
||||
self._slicing_manager = slicing_manager
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
import threading
|
||||
self._slicing_jobs = dict()
|
||||
self._slicing_jobs_mutex = threading.Lock()
|
||||
|
||||
self._slicing_progress_callbacks = []
|
||||
self._last_slicing_progress = None
|
||||
|
||||
self._progress_plugins = plugin_manager().get_implementations(ProgressPlugin)
|
||||
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def register_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
|
||||
for entry, path, printer_profile in storage_manager.analysis_backlog:
|
||||
file_type = get_file_type(path)[-1]
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=False)
|
||||
|
||||
def add_storage(self, storage_type, storage_manager):
|
||||
self._storage_managers[storage_type] = storage_manager
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def remove_storage(self, type):
|
||||
if not type in self._storage_managers:
|
||||
return
|
||||
del self._storage_managers[type]
|
||||
|
||||
@property
|
||||
def slicing_enabled(self):
|
||||
return self._slicing_manager.slicing_enabled
|
||||
|
||||
@property
|
||||
def registered_slicers(self):
|
||||
return self._slicing_manager.registered_slicers
|
||||
|
||||
@property
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.get_absolute_path(source_location, source_path)
|
||||
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path})
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta["hash"]
|
||||
|
||||
class Wrapper(object):
|
||||
def __init__(self, stl_name, temp_path, hash):
|
||||
self.stl_name = stl_name
|
||||
self.temp_path = temp_path
|
||||
self.hash = hash
|
||||
|
||||
def save(self, absolute_dest_path):
|
||||
with open(absolute_dest_path, "w") as d:
|
||||
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
|
||||
with open(tmp_path, "r") as s:
|
||||
import shutil
|
||||
shutil.copyfileobj(s, d)
|
||||
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = Wrapper(stl_name, temp_path, hash)
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
callback(*callback_args)
|
||||
finally:
|
||||
os.remove(tmp_path)
|
||||
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
if source_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[source_job_key]
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
import time
|
||||
start_time = time.time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
|
||||
|
||||
import tempfile
|
||||
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
|
||||
temp_path = f.name
|
||||
f.close()
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path)
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path)
|
||||
|
||||
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args)
|
||||
return self._slicing_manager.slice(
|
||||
slicer_name,
|
||||
absolute_source_path,
|
||||
temp_path,
|
||||
profile,
|
||||
stlProcessed,
|
||||
position=position,
|
||||
callback_args=args,
|
||||
overrides=overrides,
|
||||
printer_profile_id=printer_profile_id,
|
||||
on_progress=self.on_slicing_progress,
|
||||
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
|
||||
|
||||
def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None):
|
||||
if not _progress:
|
||||
return
|
||||
|
||||
progress_int = int(_progress * 100)
|
||||
if self._last_slicing_progress != progress_int:
|
||||
self._last_slicing_progress = progress_int
|
||||
for callback in self._slicing_progress_callbacks:
|
||||
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except: self._logger.exception("Exception while pushing slicing progress")
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
for name, plugin in self._progress_plugins.items():
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % name)
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
|
||||
def get_busy_files(self):
|
||||
return self._slicing_jobs.keys()
|
||||
|
||||
def file_exists(self, destination, path):
|
||||
return self._storage(destination).file_exists(path)
|
||||
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
for dst in destinations:
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
|
||||
return result
|
||||
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
absolute_path = self._storage(destination).get_absolute_path(file_path)
|
||||
|
||||
if analysis is None:
|
||||
file_type = get_file_type(absolute_path)
|
||||
if file_type:
|
||||
queue_entry = QueueEntry(file_path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return file_path
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
self._storage(destination).remove_file(path)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return folder_path
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
self._storage(destination).remove_folder(path, recursive=recursive)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def get_metadata(self, destination, path):
|
||||
return self._storage(destination).get_metadata(path)
|
||||
|
||||
def add_link(self, destination, path, rel, data):
|
||||
self._storage(destination).add_link(path, rel, data)
|
||||
|
||||
def remove_link(self, destination, path, rel, data):
|
||||
self._storage(destination).remove_link(path, rel, data)
|
||||
|
||||
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
|
||||
try:
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
|
||||
except NoSuchStorage:
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
pass
|
||||
|
||||
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
|
||||
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
|
||||
|
||||
def remove_additional_metadata(self, destination, path, key):
|
||||
self._storage(destination).remove_additional_metadata(path, key)
|
||||
|
||||
def get_absolute_path(self, destination, path):
|
||||
return self._storage(destination).get_absolute_path(path)
|
||||
|
||||
def sanitize(self, destination, path):
|
||||
return self._storage(destination).sanitize(path)
|
||||
|
||||
def sanitize_name(self, destination, name):
|
||||
return self._storage(destination).sanitize_name(name)
|
||||
|
||||
def sanitize_path(self, destination, path):
|
||||
return self._storage(destination).sanitize_path(path)
|
||||
|
||||
def split_path(self, destination, path):
|
||||
return self._storage(destination).split_path(path)
|
||||
|
||||
def join_path(self, destination, *path):
|
||||
return self._storage(destination).join_path(*path)
|
||||
|
||||
def rel_path(self, destination, path):
|
||||
return self._storage(destination).rel_path(path)
|
||||
|
||||
def _storage(self, destination):
|
||||
if not destination in self._storage_managers:
|
||||
raise NoSuchStorage("No storage configured for destination {destination}".format(**locals()))
|
||||
return self._storage_managers[destination]
|
||||
|
||||
def _add_analysis_result(self, destination, path, result):
|
||||
if not destination in self._storage_managers:
|
||||
return
|
||||
|
||||
storage_manager = self._storage_managers[destination]
|
||||
storage_manager.set_additional_metadata(path, "analysis", result)
|
||||
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import Queue as queue
|
||||
import os
|
||||
import threading
|
||||
import collections
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path, printer_profile")):
|
||||
def __str__(self):
|
||||
return "{location}:{path}".format(location=self.location, path=self.path)
|
||||
|
||||
|
||||
class AnalysisQueue(object):
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._callbacks = []
|
||||
self._queues = dict(
|
||||
gcode=GcodeAnalysisQueue(self._analysis_finished)
|
||||
)
|
||||
|
||||
def register_finish_callback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregister_finish_callback(self, callback):
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if not entry.type in self._queues:
|
||||
return
|
||||
|
||||
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
|
||||
|
||||
def pause(self):
|
||||
for queue in self._queues.values():
|
||||
queue.pause()
|
||||
|
||||
def resume(self):
|
||||
for queue in self._queues.values():
|
||||
queue.resume()
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
callback(entry, result)
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
def __init__(self, finished_callback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._finished_callback = finished_callback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = queue.PriorityQueue()
|
||||
self._current = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = 0
|
||||
else:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
|
||||
prio = 100
|
||||
|
||||
self._queue.put((prio, entry))
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing analysis")
|
||||
self._active.clear()
|
||||
if self._current is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
|
||||
self._do_abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
if aborted is not None:
|
||||
entry = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals()))
|
||||
else:
|
||||
(priority, entry) = self._queue.get()
|
||||
self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals()))
|
||||
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyze(entry)
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = entry
|
||||
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
|
||||
|
||||
def _analyze(self, entry):
|
||||
path = entry.absolute_path
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._current = entry
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of {entry}".format(**locals()))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
|
||||
result = self._do_analysis()
|
||||
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
self._current_progress = None
|
||||
|
||||
def _do_analysis(self):
|
||||
return None
|
||||
|
||||
def _do_abort(self):
|
||||
pass
|
||||
|
||||
|
||||
class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
def _do_analysis(self):
|
||||
try:
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile)
|
||||
|
||||
result = dict()
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self):
|
||||
if self._gcode:
|
||||
self._gcode.abort()
|
||||
@@ -1,3 +1,6 @@
|
||||
# coding=utf-8
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
class FileDestinations(object):
|
||||
|
||||
SDCARD = "sdcard"
|
||||
|
||||
@@ -0,0 +1,885 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pylru
|
||||
import tempfile
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import safeRename
|
||||
|
||||
|
||||
class StorageInterface(object):
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
# empty generator pattern, yield is intentionally unreachable
|
||||
return
|
||||
yield
|
||||
|
||||
def file_exists(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_file(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_metadata(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
raise NotImplementedError()
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_path(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def sanitize_name(self, name):
|
||||
raise NotImplementedError()
|
||||
|
||||
def split_path(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def join_path(self, *path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def rel_path(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_absolute_path(self, path):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class LocalFileStorage(StorageInterface):
|
||||
|
||||
def __init__(self, basefolder, create=False):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
|
||||
if not os.path.exists(self.basefolder) and create:
|
||||
os.makedirs(self.basefolder)
|
||||
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
|
||||
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
|
||||
|
||||
import threading
|
||||
self._metadata_lock = threading.Lock()
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
@property
|
||||
def analysis_backlog(self):
|
||||
for entry in self._analysis_backlog_generator():
|
||||
yield entry
|
||||
|
||||
def _analysis_backlog_generator(self, path=None):
|
||||
if path is None:
|
||||
path = self.basefolder
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
|
||||
continue
|
||||
|
||||
absolute_path = os.path.join(path, entry)
|
||||
if os.path.isfile(absolute_path):
|
||||
if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]:
|
||||
printer_profile_rels = self.get_link(absolute_path, "printerprofile")
|
||||
if printer_profile_rels:
|
||||
printer_profile_id = printer_profile_rels[0]["id"]
|
||||
else:
|
||||
printer_profile_id = None
|
||||
|
||||
yield entry, absolute_path, printer_profile_id
|
||||
elif os.path.isdir(absolute_path):
|
||||
for sub_entry in self._analysis_backlog_generator(absolute_path):
|
||||
yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2]
|
||||
|
||||
def file_exists(self, path):
|
||||
path, name = self.sanitize(path)
|
||||
file_path = os.path.join(path, name)
|
||||
return os.path.exists(file_path) and os.path.isfile(file_path)
|
||||
|
||||
def list_files(self, path=None, filter=None, recursive=True):
|
||||
"""
|
||||
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
|
||||
subfolders.
|
||||
|
||||
An optional filter function can be supplied which will be called with a file name and file data and which has
|
||||
to return True if the file is to be included in the result or False if not.
|
||||
|
||||
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
|
||||
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
|
||||
|
||||
{
|
||||
"some_folder": {
|
||||
"type": "folder",
|
||||
"children": {
|
||||
"some_sub_folder": {
|
||||
"type": "folder",
|
||||
"children": { ... }
|
||||
},
|
||||
"some_file.gcode": {
|
||||
"type": "machinecode",
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [ ... ],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
"test.gcode": {
|
||||
"type": "machinecode",
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
"test.stl": {
|
||||
"type": "model",
|
||||
"hash": "<sha1 hash>",
|
||||
"links": [...],
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
:param path: base path from which to recursively list all files, optional, if not supplied listing will start
|
||||
from root of base folder
|
||||
:param filter: a filter that matches the files that are to be returned, may be left out in which case no
|
||||
filtering will take place
|
||||
:param recursive: will also step into sub folders for building the complete list if set to True
|
||||
:return: a dictionary mapping entry names to entry data that represents the whole file list
|
||||
"""
|
||||
|
||||
if path:
|
||||
path = self.sanitize_path(path)
|
||||
else:
|
||||
path = self.basefolder
|
||||
return self._list_folder(path, filter=filter, recursive=recursive)
|
||||
|
||||
def add_folder(self, path, ignore_existing=True):
|
||||
"""
|
||||
Adds a folder as ``path``. The ``path`` will be sanitized.
|
||||
|
||||
:param path: the path of the new folder
|
||||
:param ignore_existing: if set to True, no error will be raised if the folder to be added already exists
|
||||
:return: the sanitized name of the new folder to be used for future references to the folder
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
|
||||
folder_path = os.path.join(path, name)
|
||||
if os.path.exists(folder_path):
|
||||
if not ignore_existing:
|
||||
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
|
||||
else:
|
||||
os.mkdir(folder_path)
|
||||
|
||||
return self.rel_path((path, name))
|
||||
|
||||
def remove_folder(self, path, recursive=True):
|
||||
"""
|
||||
Removes the folder at ``path``.
|
||||
|
||||
:param path: the path of the folder to remove
|
||||
:param recursive: if set to True, contained folders and files will also be removed, otherwise and error will
|
||||
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
|
||||
folder_path = os.path.join(path, name)
|
||||
if not os.path.exists(folder_path):
|
||||
return
|
||||
|
||||
contents = os.listdir(folder_path)
|
||||
if ".metadata.yaml" in contents:
|
||||
contents.remove(".metadata.yaml")
|
||||
if contents and not recursive:
|
||||
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
|
||||
|
||||
import shutil
|
||||
shutil.rmtree(folder_path)
|
||||
|
||||
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
|
||||
"""
|
||||
Adds the file ``file_object`` as ``path``
|
||||
|
||||
:param path: the file's new path, will be sanitized
|
||||
:param file_object: a file object that provides a ``save`` method which will be called with the destination path
|
||||
where the object should then store its contents
|
||||
:param printer_profile: the printer profile associated with this file (if any)
|
||||
:param links: any links to add with the file
|
||||
:param allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
|
||||
and its metadata will just be silently overwritten
|
||||
:return: the sanitized name of the file to be used for future references to it
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
if not octoprint.filemanager.valid_file_type(name):
|
||||
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
|
||||
file_path = os.path.join(path, name)
|
||||
if os.path.exists(file_path) and not os.path.isfile(file_path):
|
||||
raise RuntimeError("{name} does already exist in {path} and is not a file".format(**locals()))
|
||||
if os.path.exists(file_path) and not allow_overwrite:
|
||||
raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()))
|
||||
|
||||
# make sure folders exist
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
# save the file
|
||||
file_object.save(file_path)
|
||||
|
||||
# save the file's hash to the metadata of the folder
|
||||
file_hash = self._create_hash(file_path)
|
||||
if not name in metadata or not "hash" in metadata[name] or metadata[name]["hash"] != file_hash:
|
||||
# make sure to create a new metadata entry if we've never seen that file with that content before
|
||||
file_metadata = dict(
|
||||
hash=file_hash
|
||||
)
|
||||
metadata[name] = file_metadata
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
# process any links that were also provided for adding to the file
|
||||
if not links:
|
||||
links = []
|
||||
|
||||
if printer_profile is not None:
|
||||
links.append(("printerprofile", dict(id=printer_profile["id"], name=printer_profile["name"])))
|
||||
|
||||
self._add_links(name, path, links)
|
||||
|
||||
return self.rel_path((path, name))
|
||||
|
||||
def remove_file(self, path):
|
||||
"""
|
||||
Removes the file at ``path``. Will also take care of deleting the corresponding entries
|
||||
in the metadata and deleting all links pointing to the file.
|
||||
|
||||
:param path: path of the file to remove
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
file_path = os.path.join(path, name)
|
||||
if not os.path.exists(file_path):
|
||||
return
|
||||
if not os.path.isfile(file_path):
|
||||
raise RuntimeError("{name} in {path} is not a file".format(**locals()))
|
||||
|
||||
try:
|
||||
os.remove(file_path)
|
||||
except Exception as e:
|
||||
raise RuntimeError("Could not delete {name} in {path}".format(**locals()), e)
|
||||
|
||||
if name in metadata:
|
||||
if "hash" in metadata[name]:
|
||||
hash = metadata[name]["hash"]
|
||||
for m in metadata.values():
|
||||
if not "links" in m:
|
||||
continue
|
||||
for link in m["links"]:
|
||||
if "rel" in link and "hash" in link and (link["rel"] == "model" or link["rel"] == "machinecode") and link["hash"] == hash:
|
||||
m["links"].remove(link)
|
||||
del metadata[name]
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def get_metadata(self, path):
|
||||
"""
|
||||
Retrieves the metadata for the file ``path``.
|
||||
|
||||
:param path: virtual path to the file for which to retrieve the metadata
|
||||
:return: the metadata associated with the file
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
if name in metadata:
|
||||
return metadata[name]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_link(self, path, rel):
|
||||
path, name = self.sanitize(path)
|
||||
return self._get_links(name, path, rel)
|
||||
|
||||
|
||||
def add_link(self, path, rel, data):
|
||||
"""
|
||||
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
|
||||
|
||||
The following relation types are currently supported:
|
||||
|
||||
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
|
||||
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
|
||||
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
|
||||
refering to ``name`` and its hash will also be added to the linked ``model`` file
|
||||
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
|
||||
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
|
||||
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
|
||||
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
|
||||
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
|
||||
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
|
||||
attribute describing when the content was retrieved
|
||||
|
||||
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
|
||||
as machine code will be refused.
|
||||
|
||||
:param path: path of the file for which to add a link
|
||||
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to add
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
self._add_links(name, path, [(rel, data)])
|
||||
|
||||
def remove_link(self, path, rel, data):
|
||||
"""
|
||||
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
|
||||
|
||||
:param path: path of the file from which to remove the link
|
||||
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
|
||||
:param data: additional data of the link to remove, must match existing link
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
self._remove_links(name, path, [(rel, data)])
|
||||
|
||||
def add_history(self, path, data):
|
||||
path, name = self.sanitize(path)
|
||||
self._add_history(name, path, data)
|
||||
|
||||
def update_history(self, path, index, data):
|
||||
path, name = self.sanitize(path)
|
||||
self._update_history(name, path, index, data)
|
||||
|
||||
def remove_history(self, path, index):
|
||||
path, name = self.sanitize(path)
|
||||
self._update_history(name, path, index)
|
||||
|
||||
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
|
||||
"""
|
||||
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
|
||||
|
||||
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
|
||||
|
||||
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
|
||||
the two dictionaries will be merged recursively.
|
||||
|
||||
:param path: the virtual path to the file for which to add additional metadata
|
||||
:param key: key of metadata to add
|
||||
:param data: metadata to add
|
||||
:param overwrite: if True and ``key`` already exists, it will be overwritten
|
||||
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
|
||||
will be merged
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
metadata = self._get_metadata(path)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
if not key in metadata[name] or overwrite:
|
||||
metadata[name][key] = data
|
||||
metadata_dirty = True
|
||||
elif key in metadata[name] and isinstance(metadata[name][key], dict) and isinstance(data, dict) and merge:
|
||||
current_data = metadata[name][key]
|
||||
|
||||
import octoprint.util
|
||||
new_data = octoprint.util.dict_merge(current_data, data)
|
||||
metadata[name][key] = new_data
|
||||
metadata_dirty = True
|
||||
elif key in metadata[name] and overwrite:
|
||||
metadata[name][key] = data
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def remove_additional_metadata(self, path, key):
|
||||
"""
|
||||
Removes additional metadata under ``key`` for ``name`` on ``path``
|
||||
|
||||
:param path: the virtual path to the file for which to remove the metadata under ``key``
|
||||
:param key: the key to remove
|
||||
"""
|
||||
|
||||
path, name = self.sanitize(path)
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata:
|
||||
return
|
||||
|
||||
if not key in metadata[name]:
|
||||
return
|
||||
|
||||
del metadata[name][key]
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def split_path(self, path):
|
||||
"""
|
||||
Split ``path`` into base directory and file name.
|
||||
|
||||
:param path: the path to split
|
||||
:return: a tuple (base directory, file name)
|
||||
"""
|
||||
|
||||
split = path.split("/")
|
||||
if len(split) == 1:
|
||||
return "", split[0]
|
||||
else:
|
||||
return self.join_path(*split[:-1]), split[-1]
|
||||
|
||||
def join_path(self, *path):
|
||||
"""
|
||||
Join path elements together
|
||||
:param path: path elements to join
|
||||
:return: joined representation of the path to be usable as fully qualified path for further operations
|
||||
"""
|
||||
|
||||
return "/".join(path)
|
||||
|
||||
def get_absolute_path(self, path):
|
||||
"""
|
||||
Retrieves the absolute path on disk for ``path``
|
||||
|
||||
:param path: the virtual path for which to retrieve the absolute path on disk
|
||||
:return: the absolute path on disk to ``path``
|
||||
"""
|
||||
path, name = self.sanitize(path)
|
||||
return os.path.join(path, name)
|
||||
|
||||
##~~ internals
|
||||
|
||||
def _add_history(self, name, path, data):
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
|
||||
if not "history" in metadata[name]:
|
||||
metadata[name]["history"] = []
|
||||
|
||||
metadata[name]["history"].append(data)
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _update_history(self, name, path, index, data):
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
try:
|
||||
metadata[name]["history"][index].update(data)
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
self._save_metadata(path, metadata)
|
||||
except IndexError:
|
||||
pass
|
||||
|
||||
def _delete_history(self, name, path, index):
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
try:
|
||||
del metadata[name]["history"][index]
|
||||
self._calculate_stats_from_history(name, path, metadata=metadata, save=False)
|
||||
self._save_metadata(path, metadata)
|
||||
except IndexError:
|
||||
pass
|
||||
|
||||
def _calculate_stats_from_history(self, name, path, metadata=None, save=True):
|
||||
if metadata is None:
|
||||
metadata = self._get_metadata(path)
|
||||
|
||||
if not name in metadata or not "history" in metadata[name]:
|
||||
return
|
||||
|
||||
# collect data from history
|
||||
former_print_times = dict()
|
||||
last_print = dict()
|
||||
|
||||
|
||||
for history_entry in metadata[name]["history"]:
|
||||
if not "printTime" in history_entry or not "success" in history_entry or not history_entry["success"] or not "printerProfile" in history_entry:
|
||||
continue
|
||||
|
||||
printer_profile = history_entry["printerProfile"]
|
||||
print_time = history_entry["printTime"]
|
||||
|
||||
if not printer_profile in former_print_times:
|
||||
former_print_times[printer_profile] = []
|
||||
former_print_times[printer_profile].append(print_time)
|
||||
|
||||
if not printer_profile in last_print or last_print[printer_profile] is None or ("timestamp" in history_entry and history_entry["timestamp"] > last_print[printer_profile]["timestamp"]):
|
||||
last_print[printer_profile] = history_entry
|
||||
|
||||
# calculate stats
|
||||
statistics = dict(averagePrintTime=dict(), lastPrintTime=dict())
|
||||
|
||||
for printer_profile in former_print_times:
|
||||
if not former_print_times[printer_profile]:
|
||||
continue
|
||||
statistics["averagePrintTime"][printer_profile] = sum(former_print_times[printer_profile]) / float(len(former_print_times[printer_profile]))
|
||||
|
||||
for printer_profile in last_print:
|
||||
if not last_print[printer_profile]:
|
||||
continue
|
||||
statistics["lastPrintTime"][printer_profile] = last_print[printer_profile]["printTime"]
|
||||
|
||||
metadata[name]["statistics"] = statistics
|
||||
|
||||
if save:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _get_links(self, name, path, searched_rel):
|
||||
metadata = self._get_metadata(path)
|
||||
result = []
|
||||
|
||||
if not name in metadata:
|
||||
return result
|
||||
|
||||
if not "links" in metadata[name]:
|
||||
return result
|
||||
|
||||
for data in metadata[name]["links"]:
|
||||
if not "rel" in data or not data["rel"] == searched_rel:
|
||||
continue
|
||||
result.append(data)
|
||||
return result
|
||||
|
||||
def _add_links(self, name, path, links):
|
||||
file_type = octoprint.filemanager.get_file_type(name)
|
||||
if file_type:
|
||||
file_type = file_type[0]
|
||||
|
||||
metadata = self._get_metadata(path)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata:
|
||||
metadata[name] = dict()
|
||||
|
||||
if not "hash" in metadata[name]:
|
||||
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
|
||||
|
||||
if not "links" in metadata[name]:
|
||||
metadata[name]["links"] = []
|
||||
|
||||
for rel, data in links:
|
||||
if (rel == "model" or rel == "machinecode") and "name" in data:
|
||||
if file_type == "model" and rel == "model":
|
||||
# adding a model link to a model doesn't make sense
|
||||
return
|
||||
elif file_type == "machinecode" and rel == "machinecode":
|
||||
# adding a machinecode link to a machinecode doesn't make sense
|
||||
return
|
||||
|
||||
ref_path = os.path.join(path, data["name"])
|
||||
if not os.path.exists(ref_path):
|
||||
# file doesn't exist, we won't create the link
|
||||
continue
|
||||
|
||||
# fetch hash of target file
|
||||
if data["name"] in metadata and "hash" in metadata[data["name"]]:
|
||||
hash = metadata[data["name"]]["hash"]
|
||||
else:
|
||||
hash = self._create_hash(ref_path)
|
||||
if not data["name"] in metadata:
|
||||
metadata[data["name"]] = dict(
|
||||
hash=hash,
|
||||
links=[]
|
||||
)
|
||||
else:
|
||||
metadata[data["name"]]["hash"] = hash
|
||||
|
||||
if "hash" in data and not data["hash"] == hash:
|
||||
# file doesn't have the correct hash, we won't create the link
|
||||
continue
|
||||
|
||||
if not "links" in metadata[data["name"]]:
|
||||
metadata[data["name"]]["links"] = []
|
||||
|
||||
# add reverse link to link target file
|
||||
metadata[data["name"]]["links"].append(
|
||||
dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"])
|
||||
)
|
||||
metadata_dirty = True
|
||||
|
||||
link_dict = dict(
|
||||
rel=rel,
|
||||
name=data["name"],
|
||||
hash=hash
|
||||
)
|
||||
|
||||
elif rel == "web" and "href" in data:
|
||||
link_dict = dict(
|
||||
rel=rel,
|
||||
href=data["href"]
|
||||
)
|
||||
if "retrieved" in data:
|
||||
link_dict["retrieved"] = data["retrieved"]
|
||||
|
||||
else:
|
||||
continue
|
||||
|
||||
if link_dict:
|
||||
metadata[name]["links"].append(link_dict)
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _remove_links(self, name, path, links):
|
||||
metadata = self._get_metadata(path)
|
||||
metadata_dirty = False
|
||||
|
||||
if not name in metadata or not "hash" in metadata[name]:
|
||||
hash = self._create_hash(os.path.join(path, name))
|
||||
else:
|
||||
hash = metadata[name]["hash"]
|
||||
|
||||
for rel, data in links:
|
||||
if (rel == "model" or rel == "machinecode") and "name" in data:
|
||||
if data["name"] in metadata and "links" in metadata[data["name"]]:
|
||||
ref_rel = "model" if rel == "machinecode" else "machinecode"
|
||||
for link in metadata[data["name"]]["links"]:
|
||||
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
|
||||
metadata[data["name"]]["links"].remove(link)
|
||||
metadata_dirty = True
|
||||
|
||||
if "links" in metadata[name]:
|
||||
for link in metadata[name]["links"]:
|
||||
if not link["rel"] == rel:
|
||||
continue
|
||||
|
||||
matches = True
|
||||
for k, v in data.items():
|
||||
if not k in link or not link[k] == v:
|
||||
matches = False
|
||||
break
|
||||
|
||||
if not matches:
|
||||
continue
|
||||
|
||||
metadata[name]["links"].remove(link)
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
def _list_folder(self, path, filter=None, recursive=True):
|
||||
metadata = self._get_metadata(path)
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
metadata_dirty = False
|
||||
|
||||
result = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith("."):
|
||||
# no hidden files and folders
|
||||
continue
|
||||
|
||||
entry_path = os.path.join(path, entry)
|
||||
|
||||
# file handling
|
||||
if os.path.isfile(entry_path):
|
||||
file_type = octoprint.filemanager.get_file_type(entry)
|
||||
if not file_type:
|
||||
# only supported extensions
|
||||
continue
|
||||
else:
|
||||
file_type = file_type[0]
|
||||
|
||||
if entry in metadata and isinstance(metadata[entry], dict):
|
||||
entry_data = metadata[entry]
|
||||
else:
|
||||
entry_data = dict(
|
||||
hash=self._create_hash(entry_path),
|
||||
links=[],
|
||||
notes=[]
|
||||
)
|
||||
metadata[entry] = entry_data
|
||||
metadata_dirty = True
|
||||
|
||||
# TODO extract model hash from source if possible to recreate link
|
||||
|
||||
if not filter or filter(entry, entry_data):
|
||||
# only add files passing the optional filter
|
||||
extended_entry_data = dict()
|
||||
extended_entry_data.update(entry_data)
|
||||
extended_entry_data["name"] = entry
|
||||
extended_entry_data["type"] = file_type
|
||||
stat = os.stat(entry_path)
|
||||
if stat:
|
||||
extended_entry_data["size"] = stat.st_size
|
||||
extended_entry_data["date"] = int(stat.st_mtime)
|
||||
|
||||
result[entry] = extended_entry_data
|
||||
|
||||
# folder recursion
|
||||
elif os.path.isdir(entry_path) and recursive:
|
||||
sub_result = self._list_folder(entry_path, filter=filter)
|
||||
result[entry] = dict(
|
||||
name=entry,
|
||||
type="folder",
|
||||
children=sub_result
|
||||
)
|
||||
|
||||
# TODO recreate links if we have metadata less entries
|
||||
|
||||
# save metadata
|
||||
if metadata_dirty:
|
||||
self._save_metadata(path, metadata)
|
||||
|
||||
return result
|
||||
|
||||
def _create_hash(self, path):
|
||||
import hashlib
|
||||
|
||||
blocksize = 65536
|
||||
hash = hashlib.sha1()
|
||||
with open(path, "rb") as f:
|
||||
buffer = f.read(blocksize)
|
||||
while len(buffer) > 0:
|
||||
hash.update(buffer)
|
||||
buffer = f.read(blocksize)
|
||||
|
||||
return hash.hexdigest()
|
||||
|
||||
def sanitize(self, path):
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
path = path.split("/")
|
||||
if isinstance(path, (list, tuple)):
|
||||
if len(path) == 1:
|
||||
name = path[0]
|
||||
path = "/"
|
||||
else:
|
||||
name = path[-1]
|
||||
path = "/" + self.join_path(*path[:-1])
|
||||
if not path:
|
||||
path = "/"
|
||||
|
||||
name = self.sanitize_name(name)
|
||||
path = self.sanitize_path(path)
|
||||
return path, name
|
||||
|
||||
def sanitize_name(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
def sanitize_path(self, path):
|
||||
if path[0] == "/" or path[0] == ".":
|
||||
path = path[1:]
|
||||
path_elements = path.split("/")
|
||||
joined_path = self.basefolder
|
||||
for path_element in path_elements:
|
||||
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
|
||||
path = os.path.realpath(joined_path)
|
||||
if not path.startswith(self.basefolder):
|
||||
raise ValueError("path not contained in base folder: {path}".format(**locals()))
|
||||
return path
|
||||
|
||||
def rel_path(self, path):
|
||||
if isinstance(path, (tuple, list)):
|
||||
path = self.join_path(*path)
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
if path.startswith(self.basefolder):
|
||||
path = path[len(self.basefolder):]
|
||||
path = path.replace(os.path.sep, "/")
|
||||
if path.startswith("/"):
|
||||
path = path[1:]
|
||||
|
||||
return path
|
||||
|
||||
def _get_metadata(self, path):
|
||||
if path in self._metadata_cache:
|
||||
return self._metadata_cache[path]
|
||||
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
if os.path.exists(metadata_path):
|
||||
with self._metadata_lock:
|
||||
with open(metadata_path) as f:
|
||||
try:
|
||||
import yaml
|
||||
metadata = yaml.safe_load(f)
|
||||
except:
|
||||
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = metadata
|
||||
return metadata
|
||||
return dict()
|
||||
|
||||
def _save_metadata(self, path, metadata):
|
||||
metadata_path = os.path.join(path, ".metadata.yaml")
|
||||
|
||||
fh, metadata_temporary_path = tempfile.mkstemp()
|
||||
os.close(fh)
|
||||
|
||||
with self._metadata_lock:
|
||||
try:
|
||||
with open(metadata_temporary_path, "w") as f:
|
||||
import yaml
|
||||
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
safeRename(metadata_temporary_path, metadata_path, throw_error=True)
|
||||
except:
|
||||
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
|
||||
else:
|
||||
self._metadata_cache[path] = metadata
|
||||
@@ -1,6 +0,0 @@
|
||||
|
||||
|
||||
class FileTypes(object):
|
||||
|
||||
STL = "stl"
|
||||
GCODE = "gcode"
|
||||
@@ -1,523 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import os
|
||||
import Queue
|
||||
import threading
|
||||
import datetime
|
||||
import yaml
|
||||
import time
|
||||
import logging
|
||||
import octoprint.util as util
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager
|
||||
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
GCODE_EXTENSIONS = ["gcode", "gco", "g"]
|
||||
STL_EXTENSIONS = ["stl"]
|
||||
SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS
|
||||
|
||||
def isGcodeFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .gcode extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS
|
||||
|
||||
|
||||
def isSTLFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .stl extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS
|
||||
|
||||
|
||||
def genGcodeFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".gcode"
|
||||
|
||||
|
||||
def genStlFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".stl"
|
||||
|
||||
|
||||
class GcodeManager:
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._settings = settings()
|
||||
|
||||
self._uploadFolder = self._settings.getBaseFolder("uploads")
|
||||
|
||||
self._callbacks = []
|
||||
|
||||
self._metadata = {}
|
||||
self._metadataDirty = False
|
||||
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
|
||||
self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp")
|
||||
self._metadataFileAccessMutex = threading.Lock()
|
||||
|
||||
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
|
||||
|
||||
self._loadMetadata()
|
||||
self._processAnalysisBacklog()
|
||||
|
||||
def _processAnalysisBacklog(self):
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
filename = self._getBasicFilename(osFile)
|
||||
if not isGcodeFileName(filename):
|
||||
continue
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
continue
|
||||
|
||||
fileData = self.getFileData(filename)
|
||||
if fileData is not None and "gcodeAnalysis" in fileData.keys():
|
||||
continue
|
||||
|
||||
self._metadataAnalyzer.addFileToBacklog(filename)
|
||||
|
||||
def _onMetadataAnalysisFinished(self, filename, gcode):
|
||||
if filename is None or gcode is None:
|
||||
return
|
||||
|
||||
basename = os.path.basename(filename)
|
||||
|
||||
absolutePath = self.getAbsolutePath(basename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
analysisResult = {}
|
||||
dirty = False
|
||||
if gcode.totalMoveTimeMinute:
|
||||
analysisResult["estimatedPrintTime"] = util.getFormattedTimeDelta(datetime.timedelta(minutes=gcode.totalMoveTimeMinute))
|
||||
dirty = True
|
||||
if gcode.extrusionAmount:
|
||||
analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000)
|
||||
if gcode.calculateVolumeCm3():
|
||||
analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3()
|
||||
dirty = True
|
||||
|
||||
if dirty:
|
||||
metadata = self.getFileMetadata(basename)
|
||||
metadata["gcodeAnalysis"] = analysisResult
|
||||
self._metadata[basename] = metadata
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
def _loadMetadata(self):
|
||||
if os.path.exists(self._metadataFile) and os.path.isfile(self._metadataFile):
|
||||
with self._metadataFileAccessMutex:
|
||||
with open(self._metadataFile, "r") as f:
|
||||
self._metadata = yaml.safe_load(f)
|
||||
if self._metadata is None:
|
||||
self._metadata = {}
|
||||
|
||||
def _saveMetadata(self, force=False):
|
||||
if not self._metadataDirty and not force:
|
||||
return
|
||||
|
||||
with self._metadataFileAccessMutex:
|
||||
with open(self._metadataTempFile, "wb") as f:
|
||||
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._metadataDirty = False
|
||||
util.safeRename(self._metadataTempFile, self._metadataFile)
|
||||
|
||||
self._loadMetadata()
|
||||
self._sendUpdateTrigger("gcodeFiles")
|
||||
|
||||
def _getBasicFilename(self, filename):
|
||||
if filename.startswith(self._uploadFolder):
|
||||
return filename[len(self._uploadFolder + os.path.sep):]
|
||||
else:
|
||||
return filename
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendUpdateTrigger(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendUpdateTrigger(type)
|
||||
except: pass
|
||||
|
||||
#~~ file handling
|
||||
|
||||
def addFile(self, file, destination, uploadCallback=None):
|
||||
"""
|
||||
Adds the given file for the given destination to the systems. Takes care of slicing if enabled and
|
||||
necessary.
|
||||
|
||||
If the file's processing won't be finished directly with the return from this method but happen
|
||||
asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's
|
||||
filename and False. Otherwise returns a tuple (filename, True).
|
||||
"""
|
||||
if not file or not destination:
|
||||
return None, True
|
||||
|
||||
curaEnabled = self._settings.getBoolean(["cura", "enabled"])
|
||||
filename = file.filename
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename, mustExist=False)
|
||||
gcode = isGcodeFileName(filename)
|
||||
|
||||
if absolutePath is None or (not curaEnabled and not gcode):
|
||||
return None, True
|
||||
|
||||
file.save(absolutePath)
|
||||
|
||||
if gcode:
|
||||
return self.processGcode(absolutePath, destination, uploadCallback), True
|
||||
else:
|
||||
if curaEnabled and isSTLFileName(filename):
|
||||
self.processStl(absolutePath, destination, uploadCallback)
|
||||
return filename, False
|
||||
|
||||
def getFutureFileName(self, file):
|
||||
if not file:
|
||||
return None
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
def processStl(self, absolutePath, destination, uploadCallback=None):
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
|
||||
cura = CuraFactory.create_slicer()
|
||||
gcodePath = genGcodeFileName(absolutePath)
|
||||
config = self._settings.get(["cura", "config"])
|
||||
|
||||
slicingStart = time.time()
|
||||
|
||||
def stlProcessed(stlPath, gcodePath, error=None):
|
||||
if error:
|
||||
eventManager().fire("SlicingFailed", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error})
|
||||
if os.path.exists(stlPath):
|
||||
os.remove(stlPath)
|
||||
else:
|
||||
slicingStop = time.time()
|
||||
eventManager().fire("SlicingDone", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": "%.2f" % (slicingStop - slicingStart)})
|
||||
self.processGcode(gcodePath, destination, uploadCallback)
|
||||
|
||||
eventManager().fire("SlicingStarted", {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)})
|
||||
cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath])
|
||||
|
||||
def processGcode(self, absolutePath, destination, uploadCallback=None):
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
filename = self._getBasicFilename(absolutePath)
|
||||
|
||||
if filename in self._metadata.keys():
|
||||
# delete existing metadata entry, since the file is going to get overwritten
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath))
|
||||
|
||||
if uploadCallback is not None:
|
||||
uploadCallback(filename, absolutePath, destination)
|
||||
return filename
|
||||
|
||||
def getFutureFilename(self, file):
|
||||
if not file:
|
||||
return None
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
def removeFile(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
stlPath = genStlFileName(absolutePath)
|
||||
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
os.remove(absolutePath)
|
||||
if os.path.exists(stlPath):
|
||||
os.remove(stlPath)
|
||||
|
||||
if filename in self._metadata.keys():
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
def getAbsolutePath(self, filename, mustExist=True):
|
||||
"""
|
||||
Returns the absolute path of the given filename in the correct upload folder.
|
||||
|
||||
Ensures that the file
|
||||
<ul>
|
||||
<li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li>
|
||||
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
|
||||
</ul>
|
||||
|
||||
@param filename the name of the file for which to determine the absolute path
|
||||
@param mustExist if set to true, the method also checks if the file exists and is a file
|
||||
@return the absolute path of the file or None if the file is not valid
|
||||
"""
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
|
||||
return None
|
||||
|
||||
# TODO: detect which type of file and add in the extra folder portion
|
||||
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
|
||||
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
|
||||
return None
|
||||
|
||||
return secure
|
||||
|
||||
def getAllFileData(self):
|
||||
files = []
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
fileData = self.getFileData(osFile)
|
||||
if fileData is not None:
|
||||
files.append(fileData)
|
||||
return files
|
||||
|
||||
def getFileData(self, filename):
|
||||
if not filename:
|
||||
return
|
||||
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
# TODO: Make this more robust when STLs will be viewable from the client
|
||||
if isSTLFileName(filename):
|
||||
return
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
statResult = os.stat(absolutePath)
|
||||
fileData = {
|
||||
"name": filename,
|
||||
"size": util.getFormattedSize(statResult.st_size),
|
||||
"bytes": statResult.st_size,
|
||||
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(statResult.st_ctime))
|
||||
}
|
||||
|
||||
# enrich with additional metadata from analysis if available
|
||||
if filename in self._metadata.keys():
|
||||
for key in self._metadata[filename].keys():
|
||||
if key == "prints":
|
||||
val = self._metadata[filename][key]
|
||||
formattedLast = None
|
||||
if "last" in val and val["last"] is not None:
|
||||
formattedLast = {
|
||||
"date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(val["last"]["date"])),
|
||||
"success": val["last"]["success"]
|
||||
}
|
||||
formattedPrints = {
|
||||
"success": val["success"],
|
||||
"failure": val["failure"],
|
||||
"last": formattedLast
|
||||
}
|
||||
fileData["prints"] = formattedPrints
|
||||
else:
|
||||
fileData[key] = self._metadata[filename][key]
|
||||
|
||||
return fileData
|
||||
|
||||
def getFileMetadata(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
if filename in self._metadata.keys():
|
||||
return self._metadata[filename]
|
||||
else:
|
||||
return {
|
||||
"prints": {
|
||||
"success": 0,
|
||||
"failure": 0,
|
||||
"last": None
|
||||
}
|
||||
}
|
||||
|
||||
def setFileMetadata(self, filename, metadata):
|
||||
filename = self._getBasicFilename(filename)
|
||||
self._metadata[filename] = metadata
|
||||
self._metadataDirty = True
|
||||
|
||||
#~~ print job data
|
||||
|
||||
def printSucceeded(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": True
|
||||
}
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def printFailed(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["failure"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": False
|
||||
}
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def changeLastPrintSuccess(self, filename, succeeded):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
if metadata is None:
|
||||
return
|
||||
|
||||
if "prints" in metadata.keys():
|
||||
if "last" in metadata.keys() and metadata["prints"]["last"] is not None:
|
||||
currentSucceeded = metadata["prints"]["last"]["success"]
|
||||
if currentSucceeded != succeeded:
|
||||
metadata["prints"]["last"]["success"] = succeeded
|
||||
if currentSucceeded:
|
||||
# last print job was counted as success but actually failed
|
||||
metadata["prints"]["success"] -= 1
|
||||
metadata["prints"]["failure"] += 1
|
||||
else:
|
||||
# last print job was counted as a failure but actually succeeded
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["failure"] -= 1
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
#~~ analysis control
|
||||
|
||||
def pauseAnalysis(self):
|
||||
self._metadataAnalyzer.pause()
|
||||
|
||||
def resumeAnalysis(self):
|
||||
self._metadataAnalyzer.resume()
|
||||
|
||||
class MetadataAnalyzer:
|
||||
def __init__(self, getPathCallback, loadedCallback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._getPathCallback = getPathCallback
|
||||
self._loadedCallback = loadedCallback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
self._gcode = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def addFileToQueue(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis queue (high priority)" % filename)
|
||||
self._queue.put((0, filename))
|
||||
|
||||
def addFileToBacklog(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis backlog (low priority)" % filename)
|
||||
self._queue.put((100, filename))
|
||||
|
||||
def working(self):
|
||||
return self.isActive() and not (self._queue.empty() and self._currentFile is None)
|
||||
|
||||
def isActive(self):
|
||||
return self._active.is_set()
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing Gcode analyzer")
|
||||
self._active.clear()
|
||||
if self._gcode is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when Gcode analyzer is resumed")
|
||||
self._gcode.abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming Gcode analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
self._active.wait()
|
||||
|
||||
if aborted is not None:
|
||||
filename = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for file %s, processing this instead of first item in queue" % filename)
|
||||
else:
|
||||
(priority, filename) = self._queue.get()
|
||||
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
|
||||
|
||||
try:
|
||||
self._analyzeGcode(filename)
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = filename
|
||||
self._logger.debug("Running analysis of file %s aborted" % filename)
|
||||
|
||||
def _analyzeGcode(self, filename):
|
||||
path = self._getPathCallback(filename)
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._currentFile = filename
|
||||
self._currentProgress = 0
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of file %s" % filename)
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.progressCallback = self._onParsingProgress
|
||||
self._gcode.load(path)
|
||||
self._logger.debug("Analysis of file %s finished, notifying callback" % filename)
|
||||
self._loadedCallback(self._currentFile, self._gcode)
|
||||
finally:
|
||||
self._gcode = None
|
||||
self._currentProgress = None
|
||||
self._currentFile = None
|
||||
|
||||
def _onParsingProgress(self, progress):
|
||||
self._currentProgress = progress
|
||||
@@ -0,0 +1,152 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import *
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
|
||||
global _instance
|
||||
if _instance is None:
|
||||
if init:
|
||||
if plugin_folders is None:
|
||||
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
|
||||
if plugin_types is None:
|
||||
plugin_types = [StartupPlugin,
|
||||
ShutdownPlugin,
|
||||
TemplatePlugin,
|
||||
SettingsPlugin,
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
if plugin_disabled_list is None:
|
||||
all_plugin_settings = settings().get(["plugins"])
|
||||
plugin_disabled_list = []
|
||||
for key in all_plugin_settings:
|
||||
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
|
||||
plugin_disabled_list.append(key)
|
||||
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=plugin_disabled_list)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
|
||||
|
||||
def plugin_settings(plugin_key, defaults=None):
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
if not isinstance(types, (list, tuple)):
|
||||
types = [types]
|
||||
if args is None:
|
||||
args = []
|
||||
if kwargs is None:
|
||||
kwargs = dict()
|
||||
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
for name, plugin in plugins.items():
|
||||
if hasattr(plugin, method):
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
|
||||
|
||||
class PluginSettings(object):
|
||||
def __init__(self, settings, plugin_key, defaults=None):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
if defaults is None:
|
||||
defaults = dict()
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
def add_defaults_to_kwargs(kwargs):
|
||||
kwargs.update(dict(defaults=self.defaults))
|
||||
return kwargs
|
||||
|
||||
self.access_methods = {
|
||||
'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs))
|
||||
}
|
||||
|
||||
def globalGet(self, path):
|
||||
return self.settings.get(path)
|
||||
|
||||
def globalGetInt(self, path):
|
||||
return self.settings.getInt(path)
|
||||
|
||||
def globalGetFloat(self, path):
|
||||
return self.settings.getFloat(path)
|
||||
|
||||
def globalGetBoolean(self, path):
|
||||
return self.settings.getBoolean(path)
|
||||
|
||||
def globalSet(self, path, value):
|
||||
self.settings.set(path, value)
|
||||
|
||||
def globalSetInt(self, path, value):
|
||||
self.settings.setInt(path, value)
|
||||
|
||||
def globalSetFloat(self, path, value):
|
||||
self.settings.setFloat(path, value)
|
||||
|
||||
def globalSetBoolean(self, path, value):
|
||||
self.settings.setBoolean(path, value)
|
||||
|
||||
def globalGetBaseFolder(self, folder_type):
|
||||
return self.settings.getBaseFolder(folder_type)
|
||||
|
||||
def getPluginLogfilePath(self, postfix=None):
|
||||
filename = "plugin_" + self.plugin_key
|
||||
if postfix is not None:
|
||||
filename += "_" + postfix
|
||||
filename += ".log"
|
||||
return os.path.join(self.settings.getBaseFolder("logs"), filename)
|
||||
|
||||
def __getattr__(self, item):
|
||||
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
|
||||
orig_item = getattr(self.settings, item)
|
||||
args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
|
||||
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
else:
|
||||
return getattr(self.settings, item)
|
||||
@@ -0,0 +1,286 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import imp
|
||||
from collections import defaultdict
|
||||
import logging
|
||||
|
||||
|
||||
class PluginInfo(object):
|
||||
|
||||
attr_name = '__plugin_name__'
|
||||
|
||||
attr_description = '__plugin_description__'
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
|
||||
attr_implementations = '__plugin_implementations__'
|
||||
|
||||
attr_helpers = '__plugin_helpers__'
|
||||
|
||||
attr_check = '__plugin_check__'
|
||||
|
||||
attr_init = '__plugin_init__'
|
||||
|
||||
def __init__(self, key, location, instance, version=None):
|
||||
self.key = key
|
||||
self.location = location
|
||||
self.instance = instance
|
||||
|
||||
self._version = version
|
||||
|
||||
def __str__(self):
|
||||
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
|
||||
|
||||
def get_hook(self, hook):
|
||||
if not hook in self.hooks:
|
||||
return None
|
||||
return self.hooks[hook]
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = set()
|
||||
for implementation in self.implementations:
|
||||
matches_all = True
|
||||
for type in types:
|
||||
if not isinstance(implementation, type):
|
||||
matches_all = False
|
||||
if matches_all:
|
||||
result.add(implementation)
|
||||
return result
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_name, default=None)
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=None)
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_hooks, default={})
|
||||
|
||||
@property
|
||||
def implementations(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_implementations, default=[])
|
||||
|
||||
@property
|
||||
def helpers(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_helpers, default={})
|
||||
|
||||
@property
|
||||
def check(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_check, default=lambda: True)
|
||||
|
||||
@property
|
||||
def init(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None):
|
||||
if not hasattr(self.instance, attr):
|
||||
return default
|
||||
return getattr(self.instance, attr)
|
||||
|
||||
|
||||
class PluginManager(object):
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
|
||||
self.plugin_folders = plugin_folders
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
|
||||
self.plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(list)
|
||||
|
||||
self.registered_clients = []
|
||||
|
||||
self.reload_plugins()
|
||||
|
||||
def _find_plugins(self):
|
||||
plugins = dict()
|
||||
if self.plugin_folders:
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins)
|
||||
if self.plugin_entry_points:
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
|
||||
return plugins
|
||||
|
||||
def _add_plugins_from_folders(self, folders, plugins):
|
||||
for folder in folders:
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
|
||||
entries = os.listdir(folder)
|
||||
for entry in entries:
|
||||
path = os.path.join(folder, entry)
|
||||
if os.path.isdir(path) and os.path.isfile(os.path.join(path, "__init__.py")):
|
||||
key = entry
|
||||
elif os.path.isfile(path) and entry.endswith(".py"):
|
||||
key = entry[:-3] # strip off the .py extension
|
||||
else:
|
||||
continue
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
|
||||
return plugins
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins):
|
||||
import pkg_resources
|
||||
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
|
||||
for group in groups:
|
||||
for entry_point in pkg_resources.iter_entry_points(group=group, name=None):
|
||||
key = entry_point.name
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, module_name=module_name, version=version)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
|
||||
return plugins
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
|
||||
# TODO error handling
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
return None
|
||||
|
||||
plugin = self._load_plugin(key, *module, version=version)
|
||||
if plugin:
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, version=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
return PluginInfo(key, filename, instance, version=version)
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
|
||||
return None
|
||||
|
||||
def _is_plugin_disabled(self, key):
|
||||
return key in self.plugin_disabled_list or key.endswith('disabled')
|
||||
|
||||
def reload_plugins(self):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders)))
|
||||
self.plugins = self._find_plugins()
|
||||
|
||||
for name, plugin in self.plugins.items():
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
|
||||
self.log_registered_plugins()
|
||||
|
||||
def log_registered_plugins(self):
|
||||
if len(self.plugins) <= 0:
|
||||
self.logger.info("No plugins found")
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values()))))
|
||||
|
||||
def get_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
return self.plugins[name].instance
|
||||
|
||||
def get_hooks(self, hook):
|
||||
if not hook in self.plugin_hooks:
|
||||
return dict()
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
implementations = self.plugin_implementations[t]
|
||||
if result is None:
|
||||
result = set(implementations)
|
||||
else:
|
||||
result = result.intersection(implementations)
|
||||
|
||||
if result is None:
|
||||
return dict()
|
||||
return {impl[0]: impl[1] for impl in result}
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
plugin = self.plugins[name]
|
||||
|
||||
all_helpers = plugin.helpers
|
||||
if len(helpers):
|
||||
return dict((k, v) for (k, v) in all_helpers.items() if k in helpers)
|
||||
else:
|
||||
return all_helpers
|
||||
|
||||
def register_client(self, client):
|
||||
if client is None:
|
||||
return
|
||||
self.registered_clients.append(client)
|
||||
|
||||
def unregister_client(self, client):
|
||||
self.registered_clients.remove(client)
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
for client in self.registered_clients:
|
||||
try: client.sendPluginMessage(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
pass
|
||||
@@ -0,0 +1,264 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from .core import Plugin
|
||||
|
||||
|
||||
class StartupPlugin(Plugin):
|
||||
"""
|
||||
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
|
||||
on or just after the startup of the server.
|
||||
"""
|
||||
|
||||
def on_startup(self, host, port):
|
||||
"""
|
||||
Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server
|
||||
will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just
|
||||
blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server
|
||||
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
|
||||
externally reachable, use ``on_after_startup`` instead or additionally.
|
||||
|
||||
:param host: the host the server will listen on, may be ``0.0.0.0``
|
||||
:param port: the port the server will listen on
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
def on_after_startup(self):
|
||||
"""
|
||||
Called just after launch of the server, so when the listen loop is actually running already.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ShutdownPlugin(Plugin):
|
||||
"""
|
||||
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
|
||||
``StartupPlugin`` mixin, to cleanly shut down additional services again that where started by the ``StartupPlugin``
|
||||
part of the plugin.
|
||||
"""
|
||||
|
||||
def on_shutdown(self):
|
||||
"""
|
||||
Called upon the imminent shutdown of OctoPrint.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class AssetPlugin(Plugin):
|
||||
"""
|
||||
The ``AssetPlugin`` mixin allows plugins to define additional static assets such as Javascript or CSS files to
|
||||
be automatically embedded into the pages delivered by the server to be used within the client sided part of
|
||||
the plugin.
|
||||
|
||||
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used on the settings page
|
||||
of a ``SettingsPlugin``.
|
||||
"""
|
||||
|
||||
def get_asset_folder(self):
|
||||
"""
|
||||
Defines the folder where the plugin stores its static assets as defined in ``get_assets``. Usually an
|
||||
implementation such as
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_asset_folder(self):
|
||||
import os
|
||||
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
|
||||
|
||||
should be sufficient here. This way, assets can be put into a sub folder ``static`` in the plugin directory.
|
||||
|
||||
:return: the absolute path to the folder where the plugin stores its static assets
|
||||
"""
|
||||
return None
|
||||
|
||||
def get_assets(self):
|
||||
"""
|
||||
Defines the static assets the plugin offers. The following asset types are recognized and automatically
|
||||
imported at the appropriate places to be available:
|
||||
|
||||
js
|
||||
Javascript files, such as additional view models
|
||||
css
|
||||
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
|
||||
less
|
||||
LESS files with additional styles, will be embedded into delivered pages when running in LESS mode.
|
||||
|
||||
The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that
|
||||
type, the files being represented as relative paths from the asset folder as defined via ``get_asset_folder``.
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=['js/my_file.js', 'js/my_other_file.js'],
|
||||
css=['css/my_styles.css'],
|
||||
less=['less/my_styles.less']
|
||||
)
|
||||
|
||||
The assets will be made available by OctoPrint under the URL ``/plugin_assets/<plugin name>/<path>``, with
|
||||
``plugin_name`` being the plugin's name and ``path`` being the path as defined in the asset dictionary.
|
||||
|
||||
:return: a dictionary describing the static assets to publish for the plugin
|
||||
"""
|
||||
return []
|
||||
|
||||
|
||||
class TemplatePlugin(Plugin):
|
||||
def get_template_vars(self):
|
||||
return dict()
|
||||
|
||||
def get_template_folder(self):
|
||||
return None
|
||||
|
||||
|
||||
class SimpleApiPlugin(Plugin):
|
||||
def get_api_commands(self):
|
||||
return None
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
return None
|
||||
|
||||
def on_api_get(self, request):
|
||||
return None
|
||||
|
||||
|
||||
class BlueprintPlugin(Plugin):
|
||||
"""
|
||||
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
|
||||
be it a more sophisticated API than what is possible via the ``SimpleApiPlugin`` or a custom web frontend.
|
||||
|
||||
The mechanism at work here is `Flask's <http://flask.pocoo.org/>`_ own `Blueprint mechanism <http://flask.pocoo.org/docs/0.10/blueprints/>`_.
|
||||
|
||||
Your plugin should define a blueprint like this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
template_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
|
||||
blueprint = flask.Blueprint("plugin.myplugin", __name__, template_folder=template_folder)
|
||||
|
||||
Use your blueprint just like any other Flask blueprint for defining your own endpoints, e.g.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@blueprint.route("/echo", methods=["GET"])
|
||||
def myEcho():
|
||||
if not "text" in flask.request.values:
|
||||
return flask.make_response("Expected a text to echo back.", 400)
|
||||
return flask.request.values["text"]
|
||||
|
||||
Your blueprint will be published by OctoPrint under the URL ``/plugin/<pluginname>/``, so the above example
|
||||
would be reachable under ``/plugin/myplugin/echo`` (given that you named your plugin "myplugin"). You'll be able
|
||||
to create URLs via ``url_for`` under the prefix that you've chosen when constructing your blueprint, ``plugin.myplugin``
|
||||
in the above example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
flask.url_for("plugin.myplugin.echo") # will return "/plugin/myplugin/echo"
|
||||
|
||||
OctoPrint Blueprint plugins should always follow the naming scheme ``plugin.<plugin name>`` here
|
||||
to avoid conflicts.
|
||||
"""
|
||||
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Retrieves the blueprint as defined by your plugin.
|
||||
|
||||
:return: the blueprint ready to be registered with Flask
|
||||
"""
|
||||
|
||||
return None
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
"""
|
||||
Whether the blueprint is supposed to be protected by API key (the default) or not.
|
||||
"""
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class SettingsPlugin(Plugin):
|
||||
def on_settings_load(self):
|
||||
return None
|
||||
|
||||
def on_settings_save(self, data):
|
||||
pass
|
||||
|
||||
|
||||
class EventHandlerPlugin(Plugin):
|
||||
def on_event(self, event, payload):
|
||||
pass
|
||||
|
||||
|
||||
class SlicerPlugin(Plugin):
|
||||
def is_slicer_configured(self):
|
||||
return False
|
||||
|
||||
def get_slicer_properties(self):
|
||||
return dict(
|
||||
type=None,
|
||||
name=None,
|
||||
same_device=True,
|
||||
progress_report=False
|
||||
)
|
||||
|
||||
def get_slicer_profile_options(self):
|
||||
return None
|
||||
|
||||
def get_slicer_profile(self, path):
|
||||
return None
|
||||
|
||||
def get_slicer_default_profile(self):
|
||||
return None
|
||||
|
||||
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
|
||||
pass
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
pass
|
||||
|
||||
def cancel_slicing(self, machinecode_path):
|
||||
pass
|
||||
|
||||
|
||||
class ProgressPlugin(Plugin):
|
||||
"""
|
||||
Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs,
|
||||
limited to minimally 1% steps.
|
||||
"""
|
||||
|
||||
def on_print_progress(self, storage, path, progress):
|
||||
"""
|
||||
Called by OctoPrint on minimally 1% increments during a running print job.
|
||||
|
||||
:param location string: Location of the file
|
||||
:param path string: Path of the file
|
||||
:param progress int: Current progress as a value between 0 and 100
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress):
|
||||
"""
|
||||
Called by OctoPrint on minimally 1% increments during a running slicing job.
|
||||
|
||||
:param slicer string: Key of the slicer reporting the progress
|
||||
:param source_location string: Location of the source file
|
||||
:param source_path string: Path of the source file
|
||||
:param destination_location string: Location the destination file
|
||||
:param destination_path string: Path of the destination file
|
||||
:param progress int: Current progress as a value between 0 and 100
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class AppPlugin(Plugin):
|
||||
def get_additional_apps(self):
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import flask
|
||||
import math
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
import octoprint.slicing
|
||||
import octoprint.settings
|
||||
|
||||
default_settings = {
|
||||
"cura_engine": None,
|
||||
"default_profile": None,
|
||||
"debug_logging": False
|
||||
}
|
||||
s = octoprint.plugin.plugin_settings("cura", defaults=default_settings)
|
||||
|
||||
from .profile import Profile
|
||||
|
||||
blueprint = flask.Blueprint("plugin.cura", __name__)
|
||||
|
||||
@blueprint.route("/import", methods=["POST"])
|
||||
def importCuraProfile():
|
||||
import datetime
|
||||
import tempfile
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
|
||||
input_name = "file"
|
||||
input_upload_name = input_name + "." + s.globalGet(["server", "uploads", "nameSuffix"])
|
||||
input_upload_path = input_name + "." + s.globalGet(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
|
||||
filename = flask.request.values[input_upload_name]
|
||||
try:
|
||||
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
|
||||
elif input_name in flask.request.files:
|
||||
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
|
||||
try:
|
||||
temp_file.close()
|
||||
upload = flask.request.files[input_name]
|
||||
upload.save(temp_file.name)
|
||||
profile_dict = Profile.from_cura_ini(temp_file.name)
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
finally:
|
||||
os.remove(temp_file)
|
||||
|
||||
filename = upload.filename
|
||||
|
||||
else:
|
||||
return flask.make_response("No file included", 400)
|
||||
|
||||
if profile_dict is None:
|
||||
return flask.make_response("Could not convert Cura profile", 400)
|
||||
|
||||
name, _ = os.path.splitext(filename)
|
||||
|
||||
# default values for name, display name and description
|
||||
profile_name = _sanitize_name(name)
|
||||
profile_display_name = name
|
||||
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.getFormattedDateTime(datetime.datetime.now()))
|
||||
profile_allow_overwrite = False
|
||||
|
||||
# overrides
|
||||
if "name" in flask.request.values:
|
||||
profile_name = flask.request.values["name"]
|
||||
if "displayName" in flask.request.values:
|
||||
profile_display_name = flask.request.values["displayName"]
|
||||
if "description" in flask.request.values:
|
||||
profile_description = flask.request.values["description"]
|
||||
if "allowOverwrite" in flask.request.values:
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
|
||||
|
||||
slicingManager.save_profile("cura",
|
||||
profile_name,
|
||||
profile_dict,
|
||||
allow_overwrite=profile_allow_overwrite,
|
||||
display_name=profile_display_name,
|
||||
description=profile_description)
|
||||
|
||||
result = dict(
|
||||
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
|
||||
displayName=profile_display_name,
|
||||
description=profile_description
|
||||
)
|
||||
r = flask.make_response(flask.jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
|
||||
class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("octoprint.plugins.cura")
|
||||
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
|
||||
|
||||
# setup job tracking across threads
|
||||
import threading
|
||||
self._slicing_commands = dict()
|
||||
self._cancelled_jobs = []
|
||||
self._job_mutex = threading.Lock()
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
def on_startup(self, host, port):
|
||||
# setup our custom logger
|
||||
cura_logging_handler = logging.handlers.RotatingFileHandler(s.getPluginLogfilePath(postfix="engine"), maxBytes=2*1024*1024)
|
||||
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
cura_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
self._cura_logger.addHandler(cura_logging_handler)
|
||||
self._cura_logger.setLevel(logging.DEBUG if s.getBoolean(["debug_logging"]) else logging.CRITICAL)
|
||||
self._cura_logger.propagate = False
|
||||
|
||||
##~~ BlueprintPlugin API
|
||||
|
||||
def get_blueprint(self):
|
||||
global blueprint
|
||||
return blueprint
|
||||
|
||||
##~~ AssetPlugin API
|
||||
|
||||
def get_asset_folder(self):
|
||||
import os
|
||||
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
|
||||
|
||||
def get_assets(self):
|
||||
return {
|
||||
"js": ["js/cura.js"],
|
||||
"less": ["less/cura.less"],
|
||||
"css": ["css/cura.css"]
|
||||
}
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def on_settings_load(self):
|
||||
return dict(
|
||||
cura_engine=s.get(["cura_engine"]),
|
||||
default_profile=s.get(["default_profile"]),
|
||||
debug_logging=s.getBoolean(["debug_logging"])
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
if "cura_engine" in data and data["cura_engine"]:
|
||||
s.set(["cura_engine"], data["cura_engine"])
|
||||
if "default_profile" in data and data["default_profile"]:
|
||||
s.set(["default_profile"], data["default_profile"])
|
||||
if "debug_logging" in data:
|
||||
old_debug_logging = s.getBoolean(["debug_logging"])
|
||||
new_debug_logging = data["debug_logging"] in octoprint.settings.valid_boolean_trues
|
||||
if old_debug_logging != new_debug_logging:
|
||||
if new_debug_logging:
|
||||
self._cura_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
self._cura_logger.setLevel(logging.CRITICAL)
|
||||
s.setBoolean(["debug_logging"], new_debug_logging)
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_vars(self):
|
||||
return dict(
|
||||
_settings_menu_entry="Cura"
|
||||
)
|
||||
|
||||
def get_template_folder(self):
|
||||
import os
|
||||
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
|
||||
|
||||
##~~ SlicerPlugin API
|
||||
|
||||
def is_slicer_configured(self):
|
||||
cura_engine = s.get(["cura_engine"])
|
||||
if cura_engine is not None and os.path.exists(cura_engine):
|
||||
return True
|
||||
else:
|
||||
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
|
||||
|
||||
def get_slicer_properties(self):
|
||||
return dict(
|
||||
type="cura",
|
||||
name="CuraEngine",
|
||||
same_device=True,
|
||||
progress_report=True
|
||||
)
|
||||
|
||||
def get_slicer_default_profile(self):
|
||||
path = s.get(["default_profile"])
|
||||
if not path:
|
||||
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
|
||||
return self.get_slicer_profile(path)
|
||||
|
||||
def get_slicer_profile(self, path):
|
||||
profile_dict = self._load_profile(path)
|
||||
|
||||
display_name = None
|
||||
description = None
|
||||
if "_display_name" in profile_dict:
|
||||
display_name = profile_dict["_display_name"]
|
||||
del profile_dict["_display_name"]
|
||||
if "_description" in profile_dict:
|
||||
description = profile_dict["_description"]
|
||||
del profile_dict["_description"]
|
||||
|
||||
properties = self.get_slicer_properties()
|
||||
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
|
||||
|
||||
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
|
||||
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
|
||||
|
||||
if profile.display_name is not None:
|
||||
new_profile["_display_name"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
new_profile["_description"] = profile.description
|
||||
|
||||
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
try:
|
||||
with self._job_mutex:
|
||||
if not profile_path:
|
||||
profile_path = s.get(["default_profile"])
|
||||
if not machinecode_path:
|
||||
path, _ = os.path.splitext(model_path)
|
||||
machinecode_path = path + ".gco"
|
||||
|
||||
if position and isinstance(position, dict) and "x" in position and "y" in position:
|
||||
posX = position["x"]
|
||||
posY = position["y"]
|
||||
else:
|
||||
posX = None
|
||||
posY = None
|
||||
|
||||
if on_progress:
|
||||
if not on_progress_args:
|
||||
on_progress_args = ()
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info("### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
|
||||
executable = s.get(["cura_engine"])
|
||||
if not executable:
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
|
||||
working_dir, _ = os.path.split(executable)
|
||||
args = ['"%s"' % executable, '-v', '-p']
|
||||
for k, v in engine_settings.items():
|
||||
args += ["-s", '"%s=%s"' % (k, str(v))]
|
||||
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
|
||||
|
||||
import sarge
|
||||
command = " ".join(args)
|
||||
self._logger.info("Running %r in %s" % (command, working_dir))
|
||||
|
||||
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
try:
|
||||
layer_count = None
|
||||
step_factor = dict(
|
||||
inset=0,
|
||||
skin=1,
|
||||
export=2
|
||||
)
|
||||
analysis = None
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if not line:
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
# The Cura slicing process has three individual steps, each consisting of <layer_count> substeps:
|
||||
#
|
||||
# - inset
|
||||
# - skin
|
||||
# - export
|
||||
#
|
||||
# So each layer will be processed three times, once for each step, resulting in a total amount of
|
||||
# substeps of 3 * <layer_count>.
|
||||
#
|
||||
# The CuraEngine reports the calculated layer count and the continuous progress on stderr.
|
||||
# The layer count gets reported right at the beginning in a line of the format:
|
||||
#
|
||||
# Layer count: <layer_count>
|
||||
#
|
||||
# The individual progress per each of the three steps gets reported on stderr in a line of
|
||||
# the format:
|
||||
#
|
||||
# Progress:<step>:<current_layer>:<layer_count>
|
||||
#
|
||||
# Thus, for determining the overall progress the following formula applies:
|
||||
#
|
||||
# progress = <step_factor> * <layer_count> + <current_layer> / <layer_count> * 3
|
||||
#
|
||||
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
|
||||
|
||||
if line.startswith("Layer count:") and layer_count is None:
|
||||
try:
|
||||
layer_count = float(line[len("Layer count:"):].strip())
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Progress:"):
|
||||
split_line = line[len("Progress:"):].strip().split(":")
|
||||
if len(split_line) == 3:
|
||||
step, current_layer, _ = split_line
|
||||
try:
|
||||
current_layer = float(current_layer)
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
if not step in step_factor:
|
||||
continue
|
||||
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
|
||||
on_progress(*on_progress_args, **on_progress_kwargs)
|
||||
|
||||
elif line.startswith("Print time:"):
|
||||
try:
|
||||
print_time = int(line[len("Print time:"):].strip())
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
analysis["estimatedPrintTime"] = print_time
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Filament:") or line.startswith("Filament2:"):
|
||||
if line.startswith("Filament:"):
|
||||
filament_str = line[len("Filament:"):].strip()
|
||||
tool_key = "tool0"
|
||||
else:
|
||||
filament_str = line[len("Filament2:"):].strip()
|
||||
tool_key = "tool1"
|
||||
|
||||
try:
|
||||
filament = int(filament_str)
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
if not "filament" in analysis:
|
||||
analysis["filament"] = dict()
|
||||
if not tool_key in analysis["filament"]:
|
||||
analysis["filament"][tool_key] = dict()
|
||||
analysis["filament"][tool_key]["length"] = filament
|
||||
if "filamentDiameter" in engine_settings:
|
||||
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
|
||||
filament_in_cm = filament / 10.0
|
||||
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cura_logger.info("### Cancelled")
|
||||
raise octoprint.slicing.SlicingCancelled()
|
||||
|
||||
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
|
||||
if p.returncode == 0:
|
||||
return True, dict(analysis=analysis)
|
||||
else:
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
|
||||
return False, "Got returncode %r" % p.returncode
|
||||
|
||||
except octoprint.slicing.SlicingCancelled as e:
|
||||
raise e
|
||||
except:
|
||||
self._logger.exception("Could not slice via Cura, got an unknown error")
|
||||
return False, "Unknown error, please consult the log file"
|
||||
|
||||
finally:
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cancelled_jobs.remove(machinecode_path)
|
||||
if machinecode_path in self._slicing_commands:
|
||||
del self._slicing_commands[machinecode_path]
|
||||
|
||||
self._cura_logger.info("-" * 40)
|
||||
|
||||
def cancel_slicing(self, machinecode_path):
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._slicing_commands:
|
||||
self._cancelled_jobs.append(machinecode_path)
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info("Cancelled slicing of %s" % machinecode_path)
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
profile_dict = dict()
|
||||
with open(path, "r") as f:
|
||||
try:
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
raise IOError("Couldn't read profile from {path}".format(path=path))
|
||||
return profile_dict
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
if not allow_overwrite and os.path.exists(path):
|
||||
raise IOError("Cannot overwrite {path}".format(path=path))
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
return profile.convert_to_engine()
|
||||
|
||||
def _sanitize_name(name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_implementations__ = [CuraPlugin()]
|
||||
@@ -0,0 +1,971 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from . import s
|
||||
|
||||
import re
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
TOUCHING_BUILDPLATE = "buildplate"
|
||||
EVERYWHERE = "everywhere"
|
||||
|
||||
class SupportDualTypes(object):
|
||||
BOTH = "both"
|
||||
FIRST = "first"
|
||||
SECOND = "second"
|
||||
|
||||
class SupportTypes(object):
|
||||
GRID = "grid"
|
||||
LINES = "lines"
|
||||
|
||||
class PlatformAdhesionTypes(object):
|
||||
NONE = "none"
|
||||
BRIM = "brim"
|
||||
RAFT = "raft"
|
||||
|
||||
class MachineShapeTypes(object):
|
||||
SQUARE = "square"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class GcodeFlavors(object):
|
||||
REPRAP = "reprap"
|
||||
REPRAP_VOLUME = "reprap_volume"
|
||||
ULTIGCODE = "ultigcode"
|
||||
MAKERBOT = "makerbot"
|
||||
BFB = "bfb"
|
||||
MACH3 = "mach3"
|
||||
|
||||
|
||||
defaults = dict(
|
||||
layer_height=0.1,
|
||||
wall_thickness=0.8,
|
||||
solid_layer_thickness=0.6,
|
||||
print_temperature=[220, 0, 0, 0],
|
||||
print_bed_temperature=70,
|
||||
platform_adhesion=PlatformAdhesionTypes.NONE,
|
||||
filament_diameter=[2.85, 0, 0, 0],
|
||||
filament_flow=100.0,
|
||||
bottom_thickness=0.3,
|
||||
first_layer_width_factor=100.0,
|
||||
object_sink=0.0,
|
||||
|
||||
fill_density=20,
|
||||
solid_top=True,
|
||||
solid_bottom=True,
|
||||
fill_overlap=15,
|
||||
|
||||
# speeds
|
||||
print_speed=50.0,
|
||||
travel_speed=150.0,
|
||||
bottom_layer_speed=20.0,
|
||||
infill_speed=0.0,
|
||||
outer_shell_speed=0.0,
|
||||
inner_shell_speed=0.0,
|
||||
|
||||
# dual extrusion
|
||||
overlap_dual=0.15,
|
||||
wipe_tower=False,
|
||||
wipe_tower_volume=15,
|
||||
ooze_shield=False,
|
||||
|
||||
# retraction
|
||||
retraction_enable=True,
|
||||
retraction_speed=40.0,
|
||||
retraction_amount=4.5,
|
||||
retraction_dual_amount=16.5,
|
||||
retraction_min_travel=1.5,
|
||||
retraction_combing=True,
|
||||
retraction_minimal_extrusion=0.02,
|
||||
retraction_hop=0.0,
|
||||
|
||||
# cooling
|
||||
cool_min_layer_time=5,
|
||||
fan_enabled=True,
|
||||
fan_full_height=0.5,
|
||||
fan_speed=100,
|
||||
fan_speed_max=100,
|
||||
cool_min_feedrate=10,
|
||||
cool_head_lift=False,
|
||||
|
||||
# support
|
||||
support=SupportLocationTypes.NONE,
|
||||
support_type=SupportTypes.GRID,
|
||||
support_angle=60.0,
|
||||
support_fill_rate=15,
|
||||
support_xy_distance=0.7,
|
||||
support_z_distance=0.15,
|
||||
support_dual_extrusion=SupportDualTypes.BOTH,
|
||||
|
||||
# platform adhesion
|
||||
skirt_line_count=1,
|
||||
skirt_gap=3.0,
|
||||
skirt_minimal_length=150.0,
|
||||
brim_line_count=20,
|
||||
raft_margin=5.0,
|
||||
raft_line_spacing=3.0,
|
||||
raft_base_thickness=0.3,
|
||||
raft_base_linewidth=1.0,
|
||||
raft_interface_thickness=0.27,
|
||||
raft_interface_linewidth=0.4,
|
||||
raft_airgap=0.22,
|
||||
raft_surface_layers=2,
|
||||
|
||||
# repairing
|
||||
fix_horrible_union_all_type_a=True,
|
||||
fix_horrible_union_all_type_b=False,
|
||||
fix_horrible_use_open_bits=False,
|
||||
fix_horrible_extensive_stitching=False,
|
||||
|
||||
# extras
|
||||
spiralize=False,
|
||||
follow_surface=False,
|
||||
|
||||
machine_width=205,
|
||||
machine_depth=205,
|
||||
machine_center_is_zero=False,
|
||||
has_heated_bed=False,
|
||||
gcode_flavor=GcodeFlavors.REPRAP,
|
||||
extruder_amount=1,
|
||||
steps_per_e=0,
|
||||
start_gcode=[
|
||||
# 1 extruder
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M109 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M82 ;set extruder to absolute mode
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E3 ;extrude 3mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 2 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 3 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T2 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 4 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T3 ;Switch to the 4th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T2 ;Switch to the 3th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
"""
|
||||
],
|
||||
end_gcode=[
|
||||
# 1 extruder
|
||||
""";End GCode
|
||||
M104 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 2 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 3 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 4 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M104 T3 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
"""
|
||||
],
|
||||
preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added before the T(n)
|
||||
""",
|
||||
postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added after the T(n)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
class Profile(object):
|
||||
|
||||
regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)")
|
||||
regex_filament_diameter = re.compile("filament_diameter(\d?)")
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import os
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import ConfigParser
|
||||
config = ConfigParser.ConfigParser()
|
||||
try:
|
||||
config.read(path)
|
||||
except:
|
||||
return None
|
||||
|
||||
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
|
||||
translated_options = dict(
|
||||
inset0_speed="outer_shell_speed",
|
||||
insetx_speed="inner_shell_speed",
|
||||
layer0_width_factor="first_layer_width_factor",
|
||||
simple_mode="follow_surface",
|
||||
)
|
||||
translated_options["start.gcode"] = "start_gcode"
|
||||
translated_options["end.gcode"] = "end_gcode"
|
||||
value_conversions = dict(
|
||||
platform_adhesion={
|
||||
"None": PlatformAdhesionTypes.NONE,
|
||||
"Brim": PlatformAdhesionTypes.BRIM,
|
||||
"Raft": PlatformAdhesionTypes.RAFT
|
||||
},
|
||||
support={
|
||||
"None": SupportLocationTypes.NONE,
|
||||
"Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE,
|
||||
"Everywhere": SupportLocationTypes.EVERYWHERE
|
||||
},
|
||||
support_type={
|
||||
"Lines": SupportTypes.LINES,
|
||||
"Grid": SupportTypes.GRID
|
||||
},
|
||||
support_dual_extrusion={
|
||||
"Both": SupportDualTypes.BOTH,
|
||||
"First extruder": SupportDualTypes.FIRST,
|
||||
"Second extruder": SupportDualTypes.SECOND
|
||||
}
|
||||
)
|
||||
|
||||
result = dict()
|
||||
for section in config.sections():
|
||||
if not section in ("profile", "alterations"):
|
||||
continue
|
||||
|
||||
for option in config.options(section):
|
||||
ignored = False
|
||||
key = option
|
||||
|
||||
# try to fetch the value in the correct type
|
||||
try:
|
||||
value = config.getboolean(section, option)
|
||||
except:
|
||||
# no boolean, try int
|
||||
try:
|
||||
value = config.getint(section, option)
|
||||
except:
|
||||
# no int, try float
|
||||
try:
|
||||
value = config.getfloat(section, option)
|
||||
except:
|
||||
# no float, use str
|
||||
value = config.get(section, option)
|
||||
index = None
|
||||
|
||||
for opt in arrayified_options:
|
||||
if key.startswith(opt):
|
||||
if key == opt:
|
||||
index = 0
|
||||
else:
|
||||
try:
|
||||
# try to convert the target index, e.g. print_temperature2 => print_temperature[1]
|
||||
index = int(key[len(opt):]) - 1
|
||||
except ValueError:
|
||||
# ignore entries for which that fails
|
||||
ignored = True
|
||||
key = opt
|
||||
break
|
||||
if ignored:
|
||||
continue
|
||||
|
||||
if key in translated_options:
|
||||
# if the key has to be translated to a new value, do that now
|
||||
key = translated_options[key]
|
||||
|
||||
if key in value_conversions and value in value_conversions[key]:
|
||||
value = value_conversions[key][value]
|
||||
|
||||
if index is not None:
|
||||
# if we have an array to fill, make sure the target array exists and has the right size
|
||||
if not key in result:
|
||||
result[key] = []
|
||||
if len(result[key]) <= index:
|
||||
for n in xrange(index - len(result[key]) + 1):
|
||||
result[key].append(None)
|
||||
result[key][index] = value
|
||||
else:
|
||||
# just set the value if there's no array to fill
|
||||
result[key] = value
|
||||
|
||||
# merge it with our default settings, the imported profile settings taking precedence
|
||||
return cls.merge_profile(result)
|
||||
|
||||
|
||||
@classmethod
|
||||
def merge_profile(cls, profile, overrides=None):
|
||||
result = dict()
|
||||
for key in defaults.keys():
|
||||
r = cls.merge_profile_key(key, profile, overrides=overrides)
|
||||
if r is not None:
|
||||
result[key] = r
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def merge_profile_key(cls, key, profile, overrides=None):
|
||||
profile_value = None
|
||||
override_value = None
|
||||
|
||||
if not key in defaults:
|
||||
return None
|
||||
import copy
|
||||
result = copy.deepcopy(defaults[key])
|
||||
|
||||
if key in profile:
|
||||
profile_value = profile[key]
|
||||
if overrides and key in overrides:
|
||||
override_value = overrides[key]
|
||||
|
||||
if profile_value is None and override_value is None:
|
||||
# neither override nor profile, no need to handle this key further
|
||||
return None
|
||||
|
||||
if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"):
|
||||
# the array fields need some special treatment. Basically something like this:
|
||||
#
|
||||
# override_value: [None, "b"]
|
||||
# profile_value : ["a" , None, "c"]
|
||||
# default_value : ["d" , "e" , "f", "g"]
|
||||
#
|
||||
# should merge to something like this:
|
||||
#
|
||||
# ["a" , "b" , "c", "g"]
|
||||
#
|
||||
# So override > profile > default, if neither override nor profile value are available
|
||||
# the default value should just be left as is
|
||||
|
||||
for x in xrange(len(result)):
|
||||
if override_value is not None and x < len(override_value) and override_value[x] is not None:
|
||||
# we have an override value for this location, so we use it
|
||||
result[x] = override_value[x]
|
||||
elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None:
|
||||
# we have a profile value for this location, so we use it
|
||||
result[x] = profile_value[x]
|
||||
|
||||
else:
|
||||
# just change the result value to the override_value if available, otherwise to the profile_value if
|
||||
# that is given, else just leave as is
|
||||
if override_value is not None:
|
||||
result = override_value
|
||||
elif profile_value is not None:
|
||||
result = profile_value
|
||||
|
||||
return result
|
||||
|
||||
def __init__(self, profile, printer_profile, posX, posY, overrides=None):
|
||||
self._profile = self.__class__.merge_profile(profile, overrides=overrides)
|
||||
self._printer_profile = printer_profile
|
||||
self._posX = posX
|
||||
self._posY = posY
|
||||
|
||||
def profile(self):
|
||||
import copy
|
||||
return copy.deepcopy(self._profile)
|
||||
|
||||
def get(self, key):
|
||||
if key in ("machine_width", "machine_depth", "machine_center_is_zero"):
|
||||
if key == "machine_width":
|
||||
return self._printer_profile["volume"]["width"]
|
||||
elif key == "machine_depth":
|
||||
return self._printer_profile["volume"]["depth"]
|
||||
elif key == "machine_height":
|
||||
return self._printer_profile["volume"]["height"]
|
||||
elif key == "machine_center_is_zero":
|
||||
return self._printer_profile["volume"]["formFactor"] == "circular"
|
||||
else:
|
||||
return None
|
||||
|
||||
elif key == "extruder_amount":
|
||||
return self._printer_profile["extruder"]["count"]
|
||||
|
||||
elif key.startswith("extruder_offset_"):
|
||||
extruder_offsets = self._printer_profile["extruder"]["offsets"]
|
||||
match = Profile.regex_extruder_offset.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
axis, number = match.groups()
|
||||
axis = axis.lower()
|
||||
number = int(number)
|
||||
|
||||
if not axis in ("x", "y"):
|
||||
return 0.0
|
||||
if number >= len(extruder_offsets):
|
||||
return 0.0
|
||||
|
||||
if axis == "x":
|
||||
return extruder_offsets[number][0]
|
||||
elif axis == "y":
|
||||
return extruder_offsets[number][1]
|
||||
else:
|
||||
return 0.0
|
||||
|
||||
elif key.startswith("filament_diameter"):
|
||||
match = Profile.regex_filament_diameter.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
diameters = self._get("filament_diameter")
|
||||
if not match.group(1):
|
||||
return diameters[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(diameters):
|
||||
return 0.0
|
||||
return diameters[index]
|
||||
|
||||
elif key.startswith("print_temperature"):
|
||||
match = Profile.regex_print_temperature.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
temperatures = self._get("print_temperature")
|
||||
if not match.group(1):
|
||||
return temperatures[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(temperatures):
|
||||
return 0.0
|
||||
return temperatures[index]
|
||||
|
||||
else:
|
||||
return self._get(key)
|
||||
|
||||
def _get(self, key):
|
||||
if key in self._profile:
|
||||
return self._profile[key]
|
||||
elif key in defaults:
|
||||
return defaults[key]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_int(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_float(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, (str, unicode, basestring)):
|
||||
value = value.replace(",", ".").strip()
|
||||
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_boolean(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
elif isinstance(value, (str, unicode, basestring)):
|
||||
return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1"
|
||||
elif isinstance(value, (int, float)):
|
||||
return value > 0
|
||||
else:
|
||||
return value == True
|
||||
|
||||
def get_microns(self, key, default=None):
|
||||
value = self.get_float(key, default=None)
|
||||
if value is None:
|
||||
return default
|
||||
return int(value * 1000)
|
||||
|
||||
def get_gcode_template(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
if key in self._profile:
|
||||
gcode = self._profile[key]
|
||||
else:
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
else:
|
||||
return gcode
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
import zlib
|
||||
|
||||
import copy
|
||||
profile = copy.deepcopy(defaults)
|
||||
profile.update(self._profile)
|
||||
for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4",
|
||||
"filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"):
|
||||
profile[key] = self.get(key)
|
||||
|
||||
result = []
|
||||
for k, v in profile.items():
|
||||
if isinstance(v, (str, unicode)):
|
||||
result.append("{k}={v}".format(k=k, v=v.encode("utf-8")))
|
||||
else:
|
||||
result.append("{k}={v}".format(k=k, v=v))
|
||||
|
||||
return base64.b64encode(zlib.compress("\b".join(result), 9))
|
||||
|
||||
def replaceTagMatch(self, m):
|
||||
import time
|
||||
|
||||
pre = m.group(1)
|
||||
tag = m.group(2)
|
||||
|
||||
if tag == 'time':
|
||||
return pre + time.strftime('%H:%M:%S')
|
||||
if tag == 'date':
|
||||
return pre + time.strftime('%d-%m-%Y')
|
||||
if tag == 'day':
|
||||
return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
|
||||
if tag == 'profile_string':
|
||||
return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string())
|
||||
|
||||
if pre == 'F' and tag == 'max_z_speed':
|
||||
f = self.get_float("travel_speed") * 60
|
||||
elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
|
||||
f = self.get_float(tag) * 60
|
||||
elif self.get(tag):
|
||||
f = self.get(tag)
|
||||
else:
|
||||
return '%s?%s?' % (pre, tag)
|
||||
|
||||
if (f % 1) == 0:
|
||||
return pre + str(int(f))
|
||||
|
||||
return pre + str(f)
|
||||
|
||||
def get_gcode(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
prefix = ""
|
||||
postfix = ""
|
||||
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
if key == "end_gcode":
|
||||
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
|
||||
return ""
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode")
|
||||
|
||||
e_steps = self.get_float("steps_per_e")
|
||||
if e_steps > 0:
|
||||
prefix += "M92 E{e_steps}\n" % (e_steps)
|
||||
temp = self.get_float("print_temperature")
|
||||
|
||||
bedTemp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bedTemp = self.get_float("print_bed_temperature")
|
||||
include_bed_temps = bedTemp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
if include_bed_temps:
|
||||
prefix += "M140 S{print_bed_temperature}\n"
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, template):
|
||||
t = temp
|
||||
if extruder > 0:
|
||||
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
|
||||
if print_temp > 0:
|
||||
t = print_temp
|
||||
return template.format(extruder=extruder, temp=t)
|
||||
for n in xrange(1, extruder_count):
|
||||
prefix += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
|
||||
for n in xrange(0, extruder_count):
|
||||
prefix += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
|
||||
prefix += "T0\n"
|
||||
else:
|
||||
prefix += "M109 S{temp}\n".format(temp=temp)
|
||||
|
||||
if include_bed_temps:
|
||||
prefix += "M190 S{print_bed_temperature}\n".format(bedTemp=bedTemp)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def calculate_edge_width_and_line_count(self):
|
||||
wall_thickness = self.get_float("wall_thickness")
|
||||
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
|
||||
|
||||
if self.get_boolean("spiralize") or self.get_boolean("follow_surface"):
|
||||
return wall_thickness, 1
|
||||
if wall_thickness < 0.01:
|
||||
return nozzle_size, 0
|
||||
if wall_thickness < nozzle_size:
|
||||
return wall_thickness, 1
|
||||
|
||||
edge_width = None
|
||||
line_count = int(wall_thickness / (nozzle_size - 0.0001))
|
||||
if line_count < 1:
|
||||
edge_width = nozzle_size
|
||||
line_count = 1
|
||||
line_width = wall_thickness / line_count
|
||||
line_width_alt = wall_thickness / (line_count + 1)
|
||||
if line_width > nozzle_size * 1.5:
|
||||
return line_width_alt, line_count + 1
|
||||
if not edge_width:
|
||||
edge_width = line_width
|
||||
return edge_width, line_count
|
||||
|
||||
def calculate_solid_layer_count(self):
|
||||
layer_height = self.get_float("layer_height")
|
||||
solid_thickness = self.get_float("solid_layer_thickness")
|
||||
if layer_height == 0.0:
|
||||
return 1
|
||||
import math
|
||||
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
|
||||
|
||||
def calculate_minimal_extruder_count(self):
|
||||
extruder_count = self.get("extruder_amount")
|
||||
if extruder_count < 2:
|
||||
return 1
|
||||
if self.get("support") == SupportLocationTypes.NONE:
|
||||
return 1
|
||||
if self.get("support_dual_extrusion") == SupportDualTypes.SECOND:
|
||||
return 2
|
||||
return 1
|
||||
|
||||
def get_pos_x(self):
|
||||
if self._posX:
|
||||
try:
|
||||
return int(float(self._posX) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def get_pos_y(self):
|
||||
if self._posY:
|
||||
try:
|
||||
return int(float(self._posY) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def convert_to_engine(self):
|
||||
|
||||
edge_width, line_count = self.calculate_edge_width_and_line_count()
|
||||
solid_layer_count = self.calculate_solid_layer_count()
|
||||
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
minimal_extruder_count = self.calculate_minimal_extruder_count()
|
||||
|
||||
settings = {
|
||||
"layerThickness": self.get_microns("layer_height"),
|
||||
"initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"),
|
||||
"filamentDiameter": self.get_microns("filament_diameter"),
|
||||
"filamentFlow": self.get_int("filament_flow"),
|
||||
"extrusionWidth": edge_width * 1000,
|
||||
"layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000),
|
||||
"insetCount": line_count,
|
||||
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
|
||||
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
|
||||
"infillOverlap": self.get_int("fill_overlap"),
|
||||
"initialSpeedupLayers": int(4),
|
||||
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
|
||||
"printSpeed": self.get_int("print_speed"),
|
||||
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
|
||||
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"moveSpeed": self.get_int("travel_speed"),
|
||||
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
|
||||
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
|
||||
"supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"),
|
||||
"supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0),
|
||||
"supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1,
|
||||
"supportXYDistance": int(1000 * self.get_float("support_xy_distance")),
|
||||
"supportZDistance": int(1000 * self.get_float("support_z_distance")),
|
||||
"supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1),
|
||||
"retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0,
|
||||
"retractionSpeed": self.get_int("retraction_speed"),
|
||||
"retractionMinimalDistance": self.get_microns("retraction_min_travel"),
|
||||
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
|
||||
"retractionZHop": self.get_microns("retraction_hop"),
|
||||
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
|
||||
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
|
||||
"multiVolumeOverlap": self.get_microns("overlap_dual"),
|
||||
"objectSink": max(0, self.get_microns("object_sink")),
|
||||
"minimalLayerTime": self.get_int("cool_min_layer_time"),
|
||||
"minimalFeedrate": self.get_int("cool_min_feedrate"),
|
||||
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
|
||||
|
||||
# model positioning
|
||||
"posx": self.get_pos_x(),
|
||||
"posy": self.get_pos_y(),
|
||||
|
||||
# gcodes
|
||||
"startCode": self.get_gcode("start_gcode"),
|
||||
"endCode": self.get_gcode("end_gcode"),
|
||||
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
|
||||
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
|
||||
|
||||
# fixing
|
||||
"fixHorrible": 0,
|
||||
}
|
||||
|
||||
for extruder in range(1, extruder_count):
|
||||
for axis in ("x", "y"):
|
||||
settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower()))
|
||||
|
||||
fanFullHeight = self.get_microns("fan_full_height")
|
||||
settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1
|
||||
if settings["fanFullOnLayerNr"] < 0:
|
||||
settings["fanFullOnLayerNr"] = 0
|
||||
|
||||
if self.get("support_type") == SupportTypes.LINES:
|
||||
settings["supportType"] = 1
|
||||
|
||||
# infill
|
||||
if self.get_float("fill_density") == 0:
|
||||
settings["sparseInfillLineDistance"] = -1
|
||||
|
||||
elif self.get_float("fill_density") == 100:
|
||||
settings["sparseInfillLineDistance"] = settings["extrusionWidth"]
|
||||
settings["downSkinCount"] = 10000
|
||||
settings["upSkinCount"] = 10000
|
||||
|
||||
else:
|
||||
settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density"))
|
||||
|
||||
# brim/raft/skirt
|
||||
if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = self.get_int("brim_line_count")
|
||||
|
||||
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = 0
|
||||
settings["raftMargin"] = self.get_microns("raft_margin")
|
||||
settings["raftLineSpacing"] = self.get_microns("raft_line_spacing")
|
||||
settings["raftBaseThickness"] = self.get_microns("raft_base_thickness")
|
||||
settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth")
|
||||
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
|
||||
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
|
||||
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
|
||||
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
|
||||
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
|
||||
settings["raftFanSpeed"] = 100
|
||||
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
|
||||
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
|
||||
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
|
||||
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
|
||||
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
|
||||
|
||||
else:
|
||||
settings["skirtDistance"] = self.get_microns("skirt_gap")
|
||||
settings["skirtLineCount"] = self.get_int("skirt_line_count")
|
||||
settings["skirtMinLength"] = self.get_microns("skirt_minimal_length")
|
||||
|
||||
# fixing
|
||||
if self.get_boolean("fix_horrible_union_all_type_a"):
|
||||
settings["fixHorrible"] |= 0x01
|
||||
if self.get_boolean("fix_horrible_union_all_type_b"):
|
||||
settings["fixHorrible"] |= 0x02
|
||||
if self.get_boolean("fix_horrible_use_open_bits"):
|
||||
settings["fixHorrible"] |= 0x10
|
||||
if self.get_boolean("fix_horrible_extensive_stitching"):
|
||||
settings["fixHorrible"] |= 0x04
|
||||
|
||||
if settings["layerThickness"] <= 0:
|
||||
settings["layerThickness"] = 1000
|
||||
|
||||
# gcode flavor
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
settings["gcodeFlavor"] = 1
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
|
||||
settings["gcodeFlavor"] = 2
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
|
||||
settings["gcodeFlavor"] = 3
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
settings["gcodeFlavor"] = 4
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
|
||||
settings["gcodeFlavor"] = 5
|
||||
|
||||
# extras
|
||||
if self.get_boolean("spiralize"):
|
||||
settings["spiralizeMode"] = 1
|
||||
if self.get_boolean("follow_surface"):
|
||||
settings["simpleMode"] = 1
|
||||
|
||||
# dual extrusion
|
||||
if self.get_boolean("wipe_tower") and extruder_count > 1:
|
||||
import math
|
||||
settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"]))
|
||||
if self.get_boolean("ooze_shield"):
|
||||
settings["enableOozeShield"] = 1
|
||||
|
||||
return settings
|
||||
@@ -0,0 +1,4 @@
|
||||
layer_height: 0.2
|
||||
print_temperature:
|
||||
- 220.0
|
||||
- 220.0
|
||||
@@ -0,0 +1 @@
|
||||
table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default}
|
||||
@@ -0,0 +1,191 @@
|
||||
$(function() {
|
||||
function CuraViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.slicingViewModel = parameters[2];
|
||||
|
||||
self.fileName = ko.observable();
|
||||
|
||||
self.placeholderName = ko.observable();
|
||||
self.placeholderDisplayName = ko.observable();
|
||||
self.placeholderDescription = ko.observable();
|
||||
|
||||
self.profileName = ko.observable();
|
||||
self.profileDisplayName = ko.observable();
|
||||
self.profileDescription = ko.observable();
|
||||
self.profileAllowOverwrite = ko.observable(true);
|
||||
|
||||
self.uploadElement = $("#settings-cura-import");
|
||||
self.uploadButton = $("#settings-cura-import-start");
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"plugin_cura_profiles",
|
||||
{
|
||||
"id": function(a, b) {
|
||||
if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
|
||||
if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
var aName = a.name();
|
||||
if (aName === undefined) {
|
||||
aName = "";
|
||||
}
|
||||
var bName = b.name();
|
||||
if (bName === undefined) {
|
||||
bName = "";
|
||||
}
|
||||
|
||||
if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
|
||||
if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"id",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.fileName(data.files[0].name);
|
||||
|
||||
var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
|
||||
self.placeholderName(self._sanitize(name).toLowerCase());
|
||||
self.placeholderDisplayName(name);
|
||||
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
|
||||
|
||||
self.uploadButton.on("click", function() {
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
}
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
}
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
});
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
|
||||
$("#settings-plugin-cura-import").modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.profiles.removeItem(function(item) {
|
||||
return (item.key == data.key);
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "DELETE",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.makeProfileDefault = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
_.each(self.profiles.items(), function(item) {
|
||||
item.isdefault(false);
|
||||
});
|
||||
var item = self.profiles.getItem(function(item) {
|
||||
return item.key == data.key;
|
||||
});
|
||||
if (item !== undefined) {
|
||||
item.isdefault(true);
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "PATCH",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({default: true}),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.showImportProfileDialog = function() {
|
||||
$("#settings_plugin_cura_import").modal("show");
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "slicing/cura/profiles",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
var profiles = [];
|
||||
_.each(_.keys(data), function(key) {
|
||||
profiles.push({
|
||||
key: key,
|
||||
name: ko.observable(data[key].displayName),
|
||||
description: ko.observable(data[key].description),
|
||||
isdefault: ko.observable(data[key].default),
|
||||
resource: ko.observable(data[key].resource)
|
||||
});
|
||||
});
|
||||
self.profiles.updateItems(profiles);
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function () {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([CuraViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_cura_dialog")]);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
table {
|
||||
th, td {
|
||||
&.settings_plugin_cura_profiles_key {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_actions {
|
||||
text-align: center;
|
||||
width: 100px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
<div id="settings_plugin_cura_dialog" data-bind="allowBindings: true">
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<h4>{{ _('Profiles') }}</h4>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: profiles.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Import Existing Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Profile ini file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.importCuraProfile") }}">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: fileName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_cura_edit" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Edit Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="tabbable">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#settings_plugin_cura_edit_general" data-toggle="tab">{{ _('General') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_basic" data-toggle="tab">{{ _('Basic') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_advanced" data-toggle="tab">{{ _('Advanced') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_expert" data-toggle="tab">{{ _('Expert') }}</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_cura_edit_general">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Descripton') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_basic">
|
||||
<form class="form-horizontal">
|
||||
<fieldset>
|
||||
<legend>{{ _('Quality') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Layer height (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Shell thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox"> {{ _('Enable retraction') }}
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Fill') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Bottom/top thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Fill density (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Speed and Temperature') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print speed (mm/s)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print temperature (°C)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Support') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Support type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="buildplate">{{ _('Touching buildplate') }}</option>
|
||||
<option value="everywhere">{{ _('Everywhere') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Platform adhesion type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="brim">{{ _('Brim') }}</option>
|
||||
<option value="raft">{{ _('Raft') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Filament') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Diameter (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Flow (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_advanced"></div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_expert"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.confirmEditProfile() }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,690 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
"""
|
||||
The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import flask
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
|
||||
try:
|
||||
import pybonjour
|
||||
except:
|
||||
pybonjour = False
|
||||
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
|
||||
def __plugin_init__():
|
||||
if not pybonjour:
|
||||
# no pybonjour available, we can't use that
|
||||
logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available")
|
||||
|
||||
discovery_plugin = DiscoveryPlugin()
|
||||
|
||||
global __plugin_implementations__
|
||||
__plugin_implementations__ = [discovery_plugin]
|
||||
|
||||
global __plugin_helpers__
|
||||
__plugin_helpers__ = dict(
|
||||
ssdp_browse=discovery_plugin.ssdp_browse
|
||||
)
|
||||
if pybonjour:
|
||||
__plugin_helpers__.update(dict(
|
||||
zeroconf_browse=discovery_plugin.zeroconf_browse,
|
||||
zeroconf_register=discovery_plugin.zeroconf_register,
|
||||
zeroconf_unregister=discovery_plugin.zeroconf_unregister
|
||||
))
|
||||
|
||||
|
||||
default_settings = {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
|
||||
|
||||
def get_uuid():
|
||||
upnpUuid = s.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
s.set(["upnpUuid"], upnpUuid)
|
||||
s.save()
|
||||
return upnpUuid
|
||||
UUID = get_uuid()
|
||||
del get_uuid
|
||||
|
||||
|
||||
def get_instance_name():
|
||||
name = s.globalGet(["appearance", "name"])
|
||||
if name:
|
||||
return u"OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return u"OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
#~~ custom blueprint for providing discovery.xml
|
||||
|
||||
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
|
||||
|
||||
@blueprint.route("/discovery.xml")
|
||||
def discovery():
|
||||
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendorUrl = s.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.jinja2",
|
||||
friendlyName=get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=s.get(["model", "description"]),
|
||||
modelNumber=s.get(["model", "number"]),
|
||||
modelUrl=s.get(["model", "url"]),
|
||||
serialNumber=s.get(["model", "serial"]),
|
||||
uuid=UUID,
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
|
||||
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
|
||||
ssdp_multicast_addr = "239.255.255.250"
|
||||
|
||||
ssdp_multicast_port = 1900
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("octoprint.plugins." + __name__)
|
||||
|
||||
self.host = None
|
||||
self.port = None
|
||||
|
||||
# zeroconf
|
||||
self._sd_refs = dict()
|
||||
self._cnames = dict()
|
||||
|
||||
# upnp/ssdp
|
||||
self._ssdp_monitor_active = False
|
||||
self._ssdp_monitor_thread = None
|
||||
self._ssdp_notify_timeout = 10
|
||||
self._ssdp_last_notify = 0
|
||||
|
||||
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
|
||||
|
||||
def get_blueprint(self):
|
||||
return blueprint
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
public_host = s.get(["publicHost"])
|
||||
if public_host:
|
||||
host = public_host
|
||||
public_port = s.get(["publicPort"])
|
||||
if public_port:
|
||||
port = public_port
|
||||
|
||||
self.host = host
|
||||
self.port = port
|
||||
|
||||
# Zeroconf
|
||||
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in s.get(["zeroConf"]):
|
||||
if "service" in zeroconf:
|
||||
self.zeroconf_register(
|
||||
zeroconf["service"],
|
||||
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
|
||||
port=zeroconf["port"] if "port" in zeroconf else None,
|
||||
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
|
||||
)
|
||||
|
||||
# SSDP
|
||||
self._ssdp_register()
|
||||
|
||||
##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown
|
||||
|
||||
def on_shutdown(self):
|
||||
for key in self._sd_refs:
|
||||
reg_type, port = key
|
||||
self.zeroconf_unregister(reg_type, port)
|
||||
|
||||
self._ssdp_unregister()
|
||||
|
||||
##~~ helpers
|
||||
|
||||
# ZeroConf
|
||||
|
||||
def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None):
|
||||
"""
|
||||
Registers a new service with Zeroconf/Bonjour/Avahi.
|
||||
|
||||
:param reg_type: type of service to register, e.g. "_gntp._tcp"
|
||||
:param name: displayable name of the service, if not given defaults to the OctoPrint instance name
|
||||
:param port: port to register for the service, if not given defaults to OctoPrint's (public) port
|
||||
:param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return
|
||||
|
||||
if not name:
|
||||
name = get_instance_name()
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
params = dict(
|
||||
name=name,
|
||||
regtype=reg_type,
|
||||
port=port
|
||||
)
|
||||
if txt_record:
|
||||
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self.logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
|
||||
|
||||
:param reg_type: the type of the service to be unregistered
|
||||
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
|
||||
:return:
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return
|
||||
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
key = (reg_type, port)
|
||||
if not key in self._sd_refs:
|
||||
return
|
||||
|
||||
sd_ref = self._sd_refs[key]
|
||||
try:
|
||||
sd_ref.close()
|
||||
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
except:
|
||||
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
|
||||
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
|
||||
"""
|
||||
Browses for services on the local network providing the specified service type. Can be used either blocking or
|
||||
non-blocking.
|
||||
|
||||
The non-blocking version (default behaviour) will not return until the lookup has completed and
|
||||
return all results that were found.
|
||||
|
||||
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
|
||||
If no callback is provided in non-blocking mode, a ValueError will be raised.
|
||||
|
||||
The results are provided as a list of discovered services, with each service being described by a dictionary
|
||||
with the following keys:
|
||||
|
||||
* `name`: display name of the service
|
||||
* `host`: host name of the service
|
||||
* `post`: port the service is listening on
|
||||
* `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service
|
||||
|
||||
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
|
||||
example for a valid callback:
|
||||
|
||||
def browse_callback(results):
|
||||
for result in results:
|
||||
print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result)
|
||||
|
||||
:param service_type: the service type to browse for
|
||||
:param block: whether to block, defaults to True
|
||||
:param callback: callback to call once lookup has completed, must be set when `block` is set to `False`
|
||||
:param browse_timeout: timeout for browsing operation
|
||||
:param resolve_timeout: timeout for resolving operations for discovered records
|
||||
:return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be
|
||||
supplied to the callback instead)
|
||||
"""
|
||||
|
||||
if not pybonjour:
|
||||
return None
|
||||
|
||||
import threading
|
||||
import select
|
||||
|
||||
if not block and not callback:
|
||||
raise ValueError("Non-blocking mode but no callback given")
|
||||
|
||||
result = []
|
||||
result_available = threading.Event()
|
||||
result_available.clear()
|
||||
|
||||
resolved = []
|
||||
|
||||
def resolve_callback(sd_ref, flags, interface_index, error_code, fullname, hosttarget, port, txt_record):
|
||||
if error_code == pybonjour.kDNSServiceErr_NoError:
|
||||
txt_record_dict = None
|
||||
if txt_record:
|
||||
record = pybonjour.TXTRecord.parse(txt_record)
|
||||
txt_record_dict = dict()
|
||||
for key, value in record:
|
||||
txt_record_dict[key] = value
|
||||
|
||||
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
|
||||
host = hosttarget[:-1]
|
||||
|
||||
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
result.append(dict(
|
||||
name=name,
|
||||
host=host,
|
||||
port=port,
|
||||
txt_record=txt_record_dict
|
||||
))
|
||||
resolved.append(True)
|
||||
|
||||
def browse_callback(sd_ref, flags, interface_index, error_code, service_name, regtype, reply_domain):
|
||||
if error_code != pybonjour.kDNSServiceErr_NoError:
|
||||
return
|
||||
|
||||
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
||||
return
|
||||
|
||||
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
|
||||
|
||||
try:
|
||||
while not resolved:
|
||||
ready = select.select([resolve_ref], [], [], resolve_timeout)
|
||||
if resolve_ref not in ready[0]:
|
||||
break
|
||||
|
||||
pybonjour.DNSServiceProcessResult(resolve_ref)
|
||||
else:
|
||||
resolved.pop()
|
||||
finally:
|
||||
resolve_ref.close()
|
||||
|
||||
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
|
||||
def browse():
|
||||
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
|
||||
try:
|
||||
while True:
|
||||
ready = select.select([sd_ref], [], [], browse_timeout)
|
||||
|
||||
if not ready[0]:
|
||||
break
|
||||
|
||||
if sd_ref in ready[0]:
|
||||
pybonjour.DNSServiceProcessResult(sd_ref)
|
||||
finally:
|
||||
sd_ref.close()
|
||||
|
||||
if callback:
|
||||
callback(result)
|
||||
result_available.set()
|
||||
|
||||
browse_thread = threading.Thread(target=browse)
|
||||
browse_thread.daemon = True
|
||||
browse_thread.start()
|
||||
|
||||
if block:
|
||||
result_available.wait()
|
||||
return result
|
||||
else:
|
||||
return []
|
||||
|
||||
# SSDP/UPNP
|
||||
|
||||
def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5):
|
||||
"""
|
||||
Browses for UPNP services matching the supplied query. Can be used either blocking or
|
||||
non-blocking.
|
||||
|
||||
The non-blocking version (default behaviour) will not return until the lookup has completed and
|
||||
return all results that were found.
|
||||
|
||||
For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes.
|
||||
If no callback is provided in non-blocking mode, a ValueError will be raised.
|
||||
|
||||
The results are provided as a list of discovered locations of device descriptor files.
|
||||
|
||||
Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an
|
||||
example for a valid callback:
|
||||
|
||||
def browse_callback(results):
|
||||
for result in results:
|
||||
print "Location: {}".format(result)
|
||||
|
||||
:param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices
|
||||
:param block: whether to block, defaults to True
|
||||
:param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False
|
||||
:param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1
|
||||
:param retries: number of retries to perform the lookup on all interfaces, defaults to 5
|
||||
:return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be
|
||||
supplied to the callback instead)
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
||||
import httplib
|
||||
import io
|
||||
class Response(httplib.HTTPResponse):
|
||||
def __init__(self, response_text):
|
||||
self.fp = io.BytesIO(response_text)
|
||||
self.debuglevel = 0
|
||||
self.strict = 0
|
||||
self.msg = None
|
||||
self._method = None
|
||||
self.begin()
|
||||
|
||||
result = []
|
||||
result_available = threading.Event()
|
||||
result_available.clear()
|
||||
|
||||
def browse():
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
|
||||
search_message = "".join([
|
||||
"M-SEARCH * HTTP/1.1\r\n",
|
||||
"ST: {query}\r\n",
|
||||
"MX: 3\r\n",
|
||||
"MAN: \"ssdp:discovery\"\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
|
||||
for _ in xrange(retries):
|
||||
for addr in octoprint.util.interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind((addr, 0))
|
||||
|
||||
message = search_message.format(query=query,
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in xrange(2):
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
|
||||
try:
|
||||
data = sock.recv(1024)
|
||||
except socket.timeout:
|
||||
pass
|
||||
else:
|
||||
response = Response(data)
|
||||
|
||||
result.append(response.getheader("Location"))
|
||||
except:
|
||||
pass
|
||||
|
||||
if callback:
|
||||
callback(result)
|
||||
result_available.set()
|
||||
|
||||
browse_thread = threading.Thread(target=browse)
|
||||
browse_thread.daemon = True
|
||||
browse_thread.start()
|
||||
|
||||
if block:
|
||||
result_available.wait()
|
||||
return result
|
||||
else:
|
||||
return []
|
||||
|
||||
##~~ internals
|
||||
|
||||
# Zeroconf
|
||||
|
||||
def _create_http_txt_record_dict(self):
|
||||
"""
|
||||
Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance.
|
||||
|
||||
Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html
|
||||
|
||||
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
|
||||
"""
|
||||
|
||||
# determine path entry
|
||||
path = "/"
|
||||
if s.get(["pathPrefix"]):
|
||||
path = s.get(["pathPrefix"])
|
||||
else:
|
||||
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
|
||||
if prefix:
|
||||
path = prefix
|
||||
|
||||
# fetch username and password (if set)
|
||||
username = s.get(["httpUsername"])
|
||||
password = s.get(["httpPassword"])
|
||||
|
||||
entries = dict(
|
||||
path=path
|
||||
)
|
||||
|
||||
if username and password:
|
||||
entries.update(dict(u=username, p=password))
|
||||
|
||||
return entries
|
||||
|
||||
def _create_octoprint_txt_record_dict(self):
|
||||
"""
|
||||
Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance.
|
||||
|
||||
The following keys are defined:
|
||||
|
||||
* `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp
|
||||
* `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp
|
||||
* `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp
|
||||
* `version`: OctoPrint software version
|
||||
* `api`: OctoPrint API version
|
||||
* `model`: Model of the device that is running OctoPrint
|
||||
* `vendor`: Vendor of the device that is running OctoPrint
|
||||
|
||||
:return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record
|
||||
"""
|
||||
|
||||
entries = self._create_http_txt_record_dict()
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.server.api
|
||||
|
||||
entries.update(dict(
|
||||
version=octoprint.server.VERSION,
|
||||
api=octoprint.server.api.VERSION,
|
||||
))
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if modelName:
|
||||
entries.update(dict(model=modelName))
|
||||
vendor = s.get(["model", "vendor"])
|
||||
if vendor:
|
||||
entries.update(dict(vendor=vendor))
|
||||
|
||||
return entries
|
||||
|
||||
# SSDP/UPNP
|
||||
|
||||
def _ssdp_register(self):
|
||||
"""
|
||||
Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface
|
||||
"""
|
||||
|
||||
import threading
|
||||
|
||||
self._ssdp_monitor_active = True
|
||||
|
||||
self._ssdp_monitor_thread = threading.Thread(target=self._ssdp_monitor, kwargs=dict(timeout=self._ssdp_notify_timeout))
|
||||
self._ssdp_monitor_thread.daemon = True
|
||||
self._ssdp_monitor_thread.start()
|
||||
|
||||
def _ssdp_unregister(self):
|
||||
"""
|
||||
Unregisters the OctoPrint instance again
|
||||
"""
|
||||
|
||||
self._ssdp_monitor_active = False
|
||||
if self.host and self.port:
|
||||
for _ in xrange(2):
|
||||
self._ssdp_notify(alive=False)
|
||||
|
||||
def _ssdp_notify(self, alive=True):
|
||||
"""
|
||||
Sends an SSDP notify message across the connected networks.
|
||||
|
||||
:param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message
|
||||
"""
|
||||
|
||||
import socket
|
||||
import time
|
||||
|
||||
if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time():
|
||||
# we just sent an alive, no need to send another one now
|
||||
return
|
||||
|
||||
if alive and not self._ssdp_monitor_active:
|
||||
# the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow
|
||||
return
|
||||
|
||||
for addr in octoprint.util.interface_addresses():
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind((addr, 0))
|
||||
|
||||
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
|
||||
|
||||
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
notify_message = "".join([
|
||||
"NOTIFY * HTTP/1.1\r\n",
|
||||
"Server: Python/2.7\r\n",
|
||||
"Cache-Control: max-age=900\r\n",
|
||||
"Location: {location}\r\n",
|
||||
"NTS: {nts}\r\n",
|
||||
"NT: upnp:rootdevice\r\n",
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
message = notify_message.format(uuid=UUID,
|
||||
location=location,
|
||||
nts="ssdp:alive" if alive else "ssdp:byebye",
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
mcast_port=self.__class__.ssdp_multicast_port)
|
||||
for _ in xrange(2):
|
||||
# send twice, stuff might get lost, it's only UDP
|
||||
sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port))
|
||||
except:
|
||||
pass
|
||||
|
||||
self._ssdp_last_notify = time.time()
|
||||
|
||||
def _ssdp_monitor(self, timeout=5):
|
||||
"""
|
||||
Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant
|
||||
|
||||
:param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an
|
||||
alive message
|
||||
"""
|
||||
|
||||
from BaseHTTPServer import BaseHTTPRequestHandler
|
||||
from StringIO import StringIO
|
||||
import socket
|
||||
|
||||
socket.setdefaulttimeout(timeout)
|
||||
|
||||
location_message = "".join([
|
||||
"HTTP/1.1 200 OK\r\n",
|
||||
"ST: upnp:rootdevice\r\n",
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"Location: {location}\r\n",
|
||||
"Cache-Control: max-age=60\r\n\r\n"
|
||||
])
|
||||
|
||||
class Request(BaseHTTPRequestHandler):
|
||||
|
||||
def __init__(self, request_text):
|
||||
self.rfile = StringIO(request_text)
|
||||
self.raw_requestline = self.rfile.readline()
|
||||
self.error_code = self.error_message = None
|
||||
self.parse_request()
|
||||
|
||||
def send_error(self, code, message=None):
|
||||
self.error_code = code
|
||||
self.error_message = message
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
||||
sock.bind(('', self.__class__.ssdp_multicast_port))
|
||||
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
|
||||
|
||||
self.logger.info(u"Registered {} for SSDP".format(get_instance_name()))
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
try:
|
||||
while (self._ssdp_monitor_active):
|
||||
try:
|
||||
data, address = sock.recvfrom(4096)
|
||||
request = Request(data)
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
except socket.timeout:
|
||||
pass
|
||||
finally:
|
||||
self._ssdp_notify(alive=True)
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<root xmlns="urn:schemas-upnp-org:device-1-0">
|
||||
<specVersion>
|
||||
<major>1</major>
|
||||
<minor>0</minor>
|
||||
</specVersion>
|
||||
<device>
|
||||
<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>
|
||||
<friendlyName>{{ friendlyName }}</friendlyName>
|
||||
<manufacturer>{{ manufacturer }}</manufacturer>
|
||||
{% if manufacturerUrl %}<manufacturerURL>{{ manufacturerUrl }}</manufacturerURL>{% endif %}
|
||||
<modelName>{{ modelName }}</modelName>
|
||||
{% if modelDescription %}<modelDescription>{{ modelDescription }}</modelDescription>{% endif %}
|
||||
{% if modelNumber %}<modelNumber>{{ modelNumber }}</modelNumber>{% endif %}
|
||||
{% if modelUrl %}<modelURL>{{ modelUrl }}</modelURL>{% endif %}
|
||||
{% if serialNumber %}<serialNumber>{{ serialNumber }}</serialNumber>{% endif %}
|
||||
<UDN>uuid:{{ uuid }}</UDN>
|
||||
<serviceList>
|
||||
</serviceList>
|
||||
<presentationURL>{{ presentationUrl }}</presentationURL>
|
||||
</device>
|
||||
</root>
|
||||
@@ -1,678 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
import copy
|
||||
import os
|
||||
import logging
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
class Printer():
|
||||
def __init__(self, gcodeManager):
|
||||
from collections import deque
|
||||
|
||||
self._gcodeManager = gcodeManager
|
||||
self._gcodeManager.registerCallback(self)
|
||||
|
||||
# state
|
||||
self._temp = None
|
||||
self._bedTemp = None
|
||||
self._targetTemp = None
|
||||
self._targetBedTemp = None
|
||||
self._temps = {
|
||||
"actual": deque([], 300),
|
||||
"target": deque([], 300),
|
||||
"actualBed": deque([], 300),
|
||||
"targetBed": deque([], 300)
|
||||
}
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._sdRemoteName = None
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
self._lastProgressReport = None
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
ratelimit=0.5,
|
||||
updateCallback=self._sendCurrentDataCallbacks,
|
||||
addTemperatureCallback=self._sendAddTemperatureCallbacks,
|
||||
addLogCallback=self._sendAddLogCallbacks,
|
||||
addMessageCallback=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"state": None, "stateString": self.getStateString(), "flags": self._getStateFlags()},
|
||||
jobData={"filename": None, "filesize": None, "estimatedPrintTime": None, "filament": None},
|
||||
progress={"progress": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
currentZ=None
|
||||
)
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addTemperature(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addLog(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addMessage(data)
|
||||
except: pass
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendCurrentData(copy.deepcopy(data))
|
||||
except: pass
|
||||
|
||||
def _sendTriggerUpdateCallbacks(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendUpdateTrigger(type)
|
||||
except: pass
|
||||
|
||||
def _sendFeedbackCommandOutput(self, name, output):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendFeedbackCommandOutput(name, output)
|
||||
except: pass
|
||||
|
||||
#~~ callback from gcodemanager
|
||||
|
||||
def sendUpdateTrigger(self, type):
|
||||
if type == "gcodeFiles" and self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ printer commands
|
||||
|
||||
def connect(self, port=None, baudrate=None):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
eventManager().fire("Disconnected")
|
||||
|
||||
def command(self, command):
|
||||
"""
|
||||
Sends a single gcode command to the printer.
|
||||
"""
|
||||
self.commands([command])
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends multiple gcode commands (provided as a list) to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
def setTemperatureOffset(self, extruder, bed):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setTemperatureOffset(extruder, bed)
|
||||
self._stateMonitor.setTempOffsets(extruder, bed)
|
||||
|
||||
def selectFile(self, filename, sd, printAfterSelect=False):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
logging.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._comm.selectFile(filename, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselectFile(self):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def startPrint(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setPause(not self._comm.isPaused())
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.cancelPrint()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
self.commands(["M84", "M104 S0", "M140 S0", "M106 S0"]) # disable motors, switch off heaters and fan
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"])
|
||||
eventManager().fire("PrintFailed", self._selectedFile["filename"])
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
|
||||
formattedCurrentZ = None
|
||||
if self._currentZ:
|
||||
formattedCurrentZ = "%.2f mm" % (self._currentZ)
|
||||
self._stateMonitor.setCurrentZ(formattedCurrentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.addLog(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.addMessage(message)
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, printTimeLeft):
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = printTimeLeft
|
||||
|
||||
formattedPrintTime = None
|
||||
if (self._printTime):
|
||||
formattedPrintTime = util.getFormattedTimeDelta(datetime.timedelta(seconds=self._printTime))
|
||||
|
||||
formattedPrintTimeLeft = None
|
||||
if (self._printTimeLeft):
|
||||
formattedPrintTimeLeft = util.getFormattedTimeDelta(datetime.timedelta(minutes=self._printTimeLeft))
|
||||
|
||||
formattedFilePos = None
|
||||
if (filepos):
|
||||
formattedFilePos = util.getFormattedSize(filepos)
|
||||
|
||||
self._stateMonitor.setProgress({"progress": self._progress, "filepos": formattedFilePos, "printTime": formattedPrintTime, "printTimeLeft": formattedPrintTimeLeft})
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
currentTimeUtc = int(time.time() * 1000)
|
||||
|
||||
self._temps["actual"].append((currentTimeUtc, temp))
|
||||
self._temps["target"].append((currentTimeUtc, targetTemp))
|
||||
self._temps["actualBed"].append((currentTimeUtc, bedTemp))
|
||||
self._temps["targetBed"].append((currentTimeUtc, bedTargetTemp))
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
self._targetTemp = targetTemp
|
||||
self._targetBedTemp = bedTargetTemp
|
||||
|
||||
self._stateMonitor.addTemperature({"currentTime": currentTimeUtc, "temp": self._temp, "bedTemp": self._bedTemp, "targetTemp": self._targetTemp, "targetBedTemp": self._targetBedTemp})
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
self._selectedFile = {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
"sd": sd
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
|
||||
formattedFilename = None
|
||||
formattedFilesize = None
|
||||
estimatedPrintTime = None
|
||||
fileMTime = None
|
||||
filament = None
|
||||
if filename:
|
||||
formattedFilename = os.path.basename(filename)
|
||||
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
fileMTime = str(os.stat(filename).st_mtime)
|
||||
|
||||
if filesize:
|
||||
formattedFilesize = util.getFormattedSize(filesize)
|
||||
|
||||
fileData = self._gcodeManager.getFileData(filename)
|
||||
if fileData is not None and "gcodeAnalysis" in fileData.keys():
|
||||
if "estimatedPrintTime" in fileData["gcodeAnalysis"].keys():
|
||||
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["gcodeAnalysis"].keys():
|
||||
filament = fileData["gcodeAnalysis"]["filament"]
|
||||
|
||||
self._stateMonitor.setJobData({"filename": formattedFilename, "filesize": formattedFilesize, "estimatedPrintTime": estimatedPrintTime, "filament": filament, "sd": sd, "mtime": fileMTime})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.getCurrentData()
|
||||
# convert the dict of deques to a dict of lists
|
||||
temps = {k: list(v) for (k,v) in self._temps.iteritems()}
|
||||
data.update({
|
||||
"temperatureHistory": temps,
|
||||
"logHistory": list(self._log),
|
||||
"messageHistory": list(self._messages)
|
||||
})
|
||||
callback.sendHistoryData(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
sdReady = False
|
||||
else:
|
||||
sdReady = self._comm.isSdReady()
|
||||
|
||||
return {
|
||||
"operational": self.isOperational(),
|
||||
"printing": self.isPrinting(),
|
||||
"closedOrError": self.isClosedOrError(),
|
||||
"error": self.isError(),
|
||||
"paused": self.isPaused(),
|
||||
"ready": self.isReady(),
|
||||
"sdReady": sdReady
|
||||
}
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
#~~ callbacks triggered from self._comm
|
||||
|
||||
def mcLog(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
self._addTemperatureData(temp, bedTemp, targetTemp, bedTargetTemp)
|
||||
|
||||
def mcStateChange(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
"""
|
||||
oldState = self._state
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == self._comm.STATE_OPERATIONAL:
|
||||
self._gcodeManager.printSucceeded(self._selectedFile["filename"])
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"])
|
||||
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
|
||||
|
||||
self._setState(state)
|
||||
|
||||
def mcMessage(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self._addMessage(message)
|
||||
|
||||
def mcProgress(self):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getPrintTimeRemainingEstimate())
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
oldZ = self._currentZ
|
||||
if newZ != oldZ:
|
||||
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
|
||||
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
|
||||
eventManager().fire("ZChange", newZ)
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def mcSdStateChange(self, sdReady):
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcSdFiles(self, files):
|
||||
self._sendTriggerUpdateCallbacks("gcodeFiles")
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def mcFileSelected(self, filename, filesize, sd):
|
||||
self._setJobData(filename, filesize, sd)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.startPrint()
|
||||
|
||||
def mcPrintjobDone(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferStarted(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferDone(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
|
||||
|
||||
self._sdRemoteName = None
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcReceivedRegisteredMessage(self, command, output):
|
||||
self._sendFeedbackCommandOutput(command, output)
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def getSdFiles(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return self._comm.getSdFiles()
|
||||
|
||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
logging.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = self._comm.getSdFiles()
|
||||
|
||||
self._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
|
||||
self._comm.startFileTransfer(absolutePath, self._sdRemoteName)
|
||||
|
||||
def deleteSdFile(self, filename):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.deleteSdFile(filename)
|
||||
|
||||
def initSdCard(self):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def releaseSdCard(self):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
|
||||
def refreshSdFiles(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state reports
|
||||
|
||||
def getStateString(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
def getCurrentJob(self):
|
||||
currentData = self._stateMonitor.getCurrentData()
|
||||
return currentData["job"]
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
if self._comm is not None:
|
||||
(tempOffset, bedTempOffset) = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = 0
|
||||
bedTempOffset = 0
|
||||
|
||||
return {
|
||||
"extruder": {
|
||||
"current": self._temp,
|
||||
"target": self._targetTemp,
|
||||
"offset": tempOffset
|
||||
},
|
||||
"bed": {
|
||||
"current": self._bedTemp,
|
||||
"target": self._targetBedTemp,
|
||||
"offset": bedTempOffset
|
||||
}
|
||||
}
|
||||
|
||||
def getCurrentConnection(self):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None
|
||||
|
||||
port, baudrate = self._comm.getConnection()
|
||||
return self._comm.getStateString(), port, baudrate
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
|
||||
def isOperational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def isPrinting(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def isPaused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def isError(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
def isReady(self):
|
||||
return self.isOperational() and not self._comm.isStreaming()
|
||||
|
||||
def isLoading(self):
|
||||
return self._gcodeLoader is not None
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||
self._ratelimit = ratelimit
|
||||
self._updateCallback = updateCallback
|
||||
self._addTemperatureCallback = addTemperatureCallback
|
||||
self._addLogCallback = addLogCallback
|
||||
self._addMessageCallback = addMessageCallback
|
||||
|
||||
self._state = None
|
||||
self._jobData = None
|
||||
self._gcodeData = None
|
||||
self._sdUploadData = None
|
||||
self._currentZ = None
|
||||
self._progress = None
|
||||
|
||||
self._tempOffset = 0
|
||||
self._bedTempOffset = 0
|
||||
|
||||
self._changeEvent = threading.Event()
|
||||
|
||||
self._lastUpdate = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
|
||||
self.setState(state)
|
||||
self.setJobData(jobData)
|
||||
self.setProgress(progress)
|
||||
self.setCurrentZ(currentZ)
|
||||
|
||||
def addTemperature(self, temperature):
|
||||
self._addTemperatureCallback(temperature)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addLog(self, log):
|
||||
self._addLogCallback(log)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addMessage(self, message):
|
||||
self._addMessageCallback(message)
|
||||
self._changeEvent.set()
|
||||
|
||||
def setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._changeEvent.set()
|
||||
|
||||
def setState(self, state):
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
|
||||
def setJobData(self, jobData):
|
||||
self._jobData = jobData
|
||||
self._changeEvent.set()
|
||||
|
||||
def setProgress(self, progress):
|
||||
self._progress = progress
|
||||
self._changeEvent.set()
|
||||
|
||||
def setTempOffsets(self, tempOffset, bedTempOffset):
|
||||
if tempOffset is not None:
|
||||
self._tempOffset = tempOffset
|
||||
if bedTempOffset is not None:
|
||||
self._bedTempOffset = bedTempOffset
|
||||
self._changeEvent.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._changeEvent.wait()
|
||||
|
||||
now = time.time()
|
||||
delta = now - self._lastUpdate
|
||||
additionalWaitTime = self._ratelimit - delta
|
||||
if additionalWaitTime > 0:
|
||||
time.sleep(additionalWaitTime)
|
||||
|
||||
data = self.getCurrentData()
|
||||
self._updateCallback(data)
|
||||
self._lastUpdate = time.time()
|
||||
self._changeEvent.clear()
|
||||
|
||||
def getCurrentData(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._jobData,
|
||||
"currentZ": self._currentZ,
|
||||
"progress": self._progress,
|
||||
"offsets": (self._tempOffset, self._bedTempOffset)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,963 @@
|
||||
# coding=utf-8
|
||||
from octoprint.comm.protocol.repetier import RepetierTextualProtocol
|
||||
from octoprint.comm.transport import Transport
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import time
|
||||
import threading
|
||||
import copy
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
from octoprint.comm.protocol import State as ProtocolState, Protocol
|
||||
from octoprint.comm.protocol.reprap import RepRapProtocol
|
||||
from octoprint.comm.transport.serialTransport import SerialTransport
|
||||
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
class Printer():
|
||||
def __init__(self, fileManager, analysisQueue, printerProfileManager):
|
||||
from collections import deque
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
#self._estimationLogger = logging.getLogger("ESTIMATIONS")
|
||||
#self._printTimeLogger = logging.getLogger("PRINT_TIME")
|
||||
|
||||
self._analysisQueue = analysisQueue
|
||||
self._fileManager = fileManager
|
||||
self._printerProfileManager = printerProfileManager
|
||||
|
||||
# state
|
||||
self._temps = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
self._timeEstimationData = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
self._protocol = self._createProtocol()
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
|
||||
# progress plugins
|
||||
self._lastProgressReport = None
|
||||
self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin)
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
ratelimit=0.5,
|
||||
updateCallback=self._sendCurrentDataCallbacks,
|
||||
addTemperatureCallback=self._sendAddTemperatureCallbacks,
|
||||
addLogCallback=self._sendAddLogCallbacks,
|
||||
addMessageCallback=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.getStateString(), "flags": self._getStateFlags()},
|
||||
jobData={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
currentZ=None
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished)
|
||||
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self.onMetadataStatisticsUpdated)
|
||||
|
||||
def _getTransportFactory(self):
|
||||
transports = self._getSubclassAttributes(Transport, "__transportinfo__", validator=lambda x: not x[2])
|
||||
|
||||
transportType = settings().get(["communication", "transport"])
|
||||
for t in transports:
|
||||
id, name, abstract, factory = t
|
||||
if transportType == id:
|
||||
return factory
|
||||
|
||||
return SerialTransport
|
||||
|
||||
def _createProtocol(self):
|
||||
transport = self._getTransportFactory()
|
||||
protocol_type = settings().get(["communication", "protocol"])
|
||||
|
||||
protocols = self._getSubclassAttributes(Protocol, "__protocolinfo__", validator=lambda x: not x[2])
|
||||
|
||||
protocol_factory = RepRapProtocol
|
||||
for p in protocols:
|
||||
id, name, abstract, factory = p
|
||||
if protocol_type == id:
|
||||
protocol_factory = factory
|
||||
break
|
||||
|
||||
return protocol_factory(transport, protocol_listener=self)
|
||||
|
||||
def _getSubclassAttributes(self, origin, attribute, converter=lambda o, v: v, validator=lambda x: True):
|
||||
result = []
|
||||
|
||||
if hasattr(origin, attribute):
|
||||
value = getattr(origin, attribute)
|
||||
if validator(value):
|
||||
converted = list(converter(origin, value))
|
||||
converted.append(origin)
|
||||
result.append(converted)
|
||||
|
||||
subclasses = origin.__subclasses__()
|
||||
if subclasses:
|
||||
for s in subclasses:
|
||||
result.extend(self._getSubclassAttributes(s, attribute, converter, validator))
|
||||
|
||||
return result
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addTemperature(data)
|
||||
except: self._logger.exception("Exception while adding temperature data point")
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addLog(data)
|
||||
except: self._logger.exception("Exception while adding communication log entry")
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addMessage(data)
|
||||
except: self._logger.exception("Exception while adding printer message")
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendCurrentData(copy.deepcopy(data))
|
||||
except: self._logger.exception("Exception while pushing current data")
|
||||
|
||||
def _sendTriggerUpdateCallbacks(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendEvent(type)
|
||||
except: self._logger.exception("Exception while pushing trigger update")
|
||||
|
||||
def _sendFeedbackCommandOutput(self, name, output):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendFeedbackCommandOutput(name, output)
|
||||
except: self._logger.exception("Exception while pushing feedback command output")
|
||||
|
||||
#~~ callbacks from protocol
|
||||
|
||||
def onStateChange(self, source, oldState, newState):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if oldState == ProtocolState.PRINTING:
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
if self._selectedFile is not None and newState == ProtocolState.OFFLINE or newState == ProtocolState.ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False)
|
||||
elif newState == ProtocolState.PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
|
||||
self._setState(newState)
|
||||
|
||||
def onTemperatureUpdate(self, source, temperatureData):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._addTemperatureData(temperatureData)
|
||||
|
||||
def onProgress(self, source, progress):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._setProgressData(progress["completion"], progress["filepos"], progress["printTime"])
|
||||
|
||||
def onZChange(self, source, oldZ, newZ):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
if newZ != oldZ:
|
||||
# we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or
|
||||
# anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes
|
||||
eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def onFileSelected(self, source, filename, filesize, origin):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._setJobData(filename, filesize, origin)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.startPrint()
|
||||
pass
|
||||
|
||||
def onPrintjobDone(self, source):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._setProgressData(100.0, self._selectedFile["filesize"], self._protocol.get_print_time())
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
def onPrintjobCancelled(self, source):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
|
||||
def onFileTransferStarted(self, source, filename, filesize):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, FileDestinations.SDCARD)
|
||||
self._setProgressData(0.0, 0, 0)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def onFileTransferDone(self, source):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
self._streamingFinishedCallback(self._sdRemoteName, FileDestinations.SDCARD)
|
||||
|
||||
self._sdRemoteName = None
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def onSdStateChange(self, source, sdAvailable):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def onSdFiles(self, source, files):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def onLogTx(self, source, tx):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._addLog("Send: %s" % tx)
|
||||
|
||||
def onLogRx(self, source, rx):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._addLog("Recv: %s" % rx)
|
||||
|
||||
def onLogError(self, source, error):
|
||||
if not source == self._protocol:
|
||||
return
|
||||
|
||||
self._addLog("ERROR: %s" % error)
|
||||
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
def onMetadataAnalysisFinished(self, event, data):
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
def onMetadataStatisticsUpdated(self, event, data):
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ progress plugin reporting
|
||||
|
||||
def _reportPrintProgressToPlugins(self, progress):
|
||||
if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
|
||||
return
|
||||
|
||||
storage = "sdcard" if self._selectedFile["sd"] else "local"
|
||||
filename = self._selectedFile["filename"]
|
||||
|
||||
def call_plugins(storage, filename, progress):
|
||||
for name, plugin in self._progressPlugins.items():
|
||||
try:
|
||||
plugin.on_print_progress(storage, filename, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % name)
|
||||
|
||||
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
#~~ printer commands
|
||||
|
||||
def connect(self, protocol_option_overrides=None, transport_option_overrides=None, profile=None):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
self._protocol.disconnect()
|
||||
|
||||
protocol_options = settings().get(["communication", "protocolOptions"], merged=True)
|
||||
if protocol_option_overrides is not None and isinstance(protocol_option_overrides, dict):
|
||||
protocol_options = util.dict_merge(protocol_options, protocol_option_overrides)
|
||||
|
||||
transport_options = settings().get(["communication", "transportOptions"], merged=True)
|
||||
if transport_option_overrides is not None and isinstance(transport_option_overrides, dict):
|
||||
transport_options = util.dict_merge(transport_options, transport_option_overrides)
|
||||
|
||||
self._protocol.connect(protocol_options, transport_options)
|
||||
self._printerProfileManager.select(profile)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
self._protocol.disconnect()
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def getConnectionOptions(self):
|
||||
connection_options = self._protocol.get_connection_options()
|
||||
|
||||
return {
|
||||
"ports": connection_options["port"],
|
||||
"baudrates": connection_options["baudrate"],
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
def command(self, command):
|
||||
self._protocol.send_manually(command)
|
||||
|
||||
def commands(self, commands):
|
||||
self.command(commands)
|
||||
|
||||
def jog(self, axis, amount):
|
||||
if not axis or not amount:
|
||||
return
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
axis = axis.lower()
|
||||
if axis in printer_profile["axes"]:
|
||||
speed = printer_profile["axes"][axis]["speed"]
|
||||
self._protocol.jog(axis, amount, speed)
|
||||
|
||||
def home(self, axes):
|
||||
self._protocol.home(axes)
|
||||
|
||||
def extrude(self, amount):
|
||||
if not amount:
|
||||
return
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
if "e" in printer_profile["axes"]:
|
||||
speed = printer_profile["axes"]["e"]["speed"]
|
||||
self._protocol.extrude(amount, speed)
|
||||
|
||||
def changeTool(self, tool):
|
||||
self._protocol.change_tool(tool)
|
||||
|
||||
def setTemperature(self, type, value):
|
||||
self._protocol.set_temperature(type, value)
|
||||
|
||||
def setTemperatureOffset(self, offsets):
|
||||
current_offsets = self._protocol.get_temperature_offsets()
|
||||
|
||||
new_offsets = {}
|
||||
new_offsets.update(current_offsets)
|
||||
|
||||
for key in offsets:
|
||||
if key == "bed" or re.match("tool\d+", key):
|
||||
new_offsets[key] = offsets[key]
|
||||
|
||||
self._protocol.set_temperature_offsets(new_offsets)
|
||||
self._stateMonitor.setTempOffsets(new_offsets)
|
||||
|
||||
def selectFile(self, filename, origin, printAfterSelect=False):
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._protocol.select_file(filename, origin)
|
||||
self._setProgressData(0, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselectFile(self):
|
||||
self._protocol.deselect_file()
|
||||
self._setProgressData(0, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def startPrint(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if not self._protocol.is_operational() or self._protocol.is_busy():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
self._timeEstimationData = TimeEstimationHelper()
|
||||
self._lastProgressReport = None
|
||||
self._setCurrentZ(None)
|
||||
self._protocol.start_print()
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
self._protocol.pause_print()
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
self._protocol.cancel_print()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extruder_count = printer_profile["extruder"]["count"]
|
||||
|
||||
# disable motors, switch off hotends, bed and fan
|
||||
commands = ["M84"]
|
||||
commands.extend(map(lambda x: "M104 T%d S0" % x, range(extruder_count)))
|
||||
commands.extend(["M140 S0", "M106 S0"])
|
||||
self.commands(commands)
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._protocol.get_print_time(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
}
|
||||
if self._selectedFile["sd"]:
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._stateMonitor.setCurrentZ(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.addLog(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.addMessage(message)
|
||||
|
||||
def _estimateTotalPrintTime(self, progress, printTime):
|
||||
if not progress or not printTime:
|
||||
#self._estimationLogger.info("{progress};{printTime};;;;".format(**locals()))
|
||||
return None
|
||||
|
||||
else:
|
||||
newEstimate = printTime * 100 / progress
|
||||
self._timeEstimationData.update(newEstimate)
|
||||
|
||||
result = None
|
||||
if self._timeEstimationData.is_stable():
|
||||
result = self._timeEstimationData.average_total_rolling
|
||||
|
||||
#averageTotal = self._timeEstimationData.average_total
|
||||
#averageTotalRolling = self._timeEstimationData.average_total_rolling
|
||||
#averageDistance = self._timeEstimationData.average_distance
|
||||
|
||||
#self._estimationLogger.info("{progress};{printTime};{newEstimate};{averageTotal};{averageTotalRolling};{averageDistance}".format(**locals()))
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime):
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, printTime)
|
||||
statisticalTotalPrintTime = None
|
||||
totalPrintTime = estimatedTotalPrintTime
|
||||
|
||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
|
||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||
if progress and printTime:
|
||||
if estimatedTotalPrintTime is None:
|
||||
totalPrintTime = statisticalTotalPrintTime
|
||||
else:
|
||||
if progress < 50:
|
||||
sub_progress = progress * 2 / 100
|
||||
else:
|
||||
sub_progress = 1.0
|
||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
||||
|
||||
#self._printTimeLogger.info("{progress};{printTime};{estimatedTotalPrintTime};{statisticalTotalPrintTime};{totalPrintTime}".format(**locals()))
|
||||
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = totalPrintTime - printTime if (totalPrintTime is not None and printTime is not None) else None
|
||||
|
||||
self._stateMonitor.setProgress({
|
||||
"completion": self._progress,
|
||||
"filepos": filepos,
|
||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
|
||||
})
|
||||
|
||||
if progress:
|
||||
progress_int = int(progress)
|
||||
if self._lastProgressReport != progress_int:
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
|
||||
def _addTemperatureData(self, temperatureData):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
data = {
|
||||
"time": currentTimeUtc
|
||||
}
|
||||
for tool in temperatureData.keys():
|
||||
data[tool] = {
|
||||
"actual": temperatureData[tool][0],
|
||||
"target": temperatureData[tool][1]
|
||||
}
|
||||
|
||||
self._temps.append(data)
|
||||
|
||||
self._stateMonitor.addTemperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, origin):
|
||||
sd = origin == FileDestinations.SDCARD
|
||||
if filename is not None:
|
||||
self._selectedFile = {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
"sd": sd,
|
||||
"estimatedPrintTime": None
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if filename:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(filename).st_ctime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, filename)
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["analysis"].keys():
|
||||
filament = fileData["analysis"]["filament"]
|
||||
if "statistics" in fileData:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
|
||||
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
|
||||
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
|
||||
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
|
||||
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
|
||||
|
||||
if averagePrintTime is not None:
|
||||
self._selectedFile["estimatedPrintTime"] = averagePrintTime
|
||||
elif estimatedPrintTime is not None:
|
||||
# TODO apply factor which first needs to be tracked!
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": os.path.basename(filename) if filename is not None else None,
|
||||
"origin": origin,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.getCurrentData()
|
||||
data.update({
|
||||
"temps": list(self._temps),
|
||||
"logs": list(self._log),
|
||||
"messages": list(self._messages)
|
||||
})
|
||||
callback.sendHistoryData(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.isOperational(),
|
||||
"printing": self.isPrinting(),
|
||||
"closedOrError": self.isClosedOrError(),
|
||||
"error": self.isError(),
|
||||
"paused": self.isPaused(),
|
||||
"ready": self.isReady(),
|
||||
"sdReady": self.isSdReady()
|
||||
}
|
||||
|
||||
#~~ callbacks triggered from self._comm
|
||||
|
||||
def mcReceivedRegisteredMessage(self, command, output):
|
||||
self._sendFeedbackCommandOutput(command, output)
|
||||
|
||||
def mcForceDisconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def getSdFiles(self):
|
||||
if not self._protocol.is_sd_ready():
|
||||
return []
|
||||
return self._protocol.get_sd_files()
|
||||
|
||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if self._protocol.is_busy() or not self._protocol.is_sd_ready():
|
||||
logging.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = map(lambda x: x[0], self._protocol.get_sd_files())
|
||||
|
||||
self._sdRemoteName = util.getDosFilename(filename, existingSdFiles)
|
||||
self._protocol.add_sd_file(absolutePath, filename, self._sdRemoteName)
|
||||
|
||||
return self._sdRemoteName
|
||||
|
||||
def deleteSdFile(self, filename):
|
||||
if not self._protocol.is_sd_ready():
|
||||
return
|
||||
self._protocol.remove_sd_file(filename)
|
||||
|
||||
def initSdCard(self):
|
||||
self._protocol.init_sd()
|
||||
|
||||
def releaseSdCard(self):
|
||||
if not self._protocol.is_sd_ready() or self._protocol.is_busy():
|
||||
return
|
||||
self._protocol.release_sd()
|
||||
|
||||
def refreshSdFiles(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._protocol.get_sd_files()). Defaults to a asynchronous operation.
|
||||
"""
|
||||
if not self._protocol.is_sd_ready():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._protocol.refresh_sd_files()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state reports
|
||||
|
||||
def getStateString(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
return self._state
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
def getCurrentJob(self):
|
||||
currentData = self._stateMonitor.getCurrentData()
|
||||
return currentData["job"]
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
temperatures = self._protocol.get_current_temperatures()
|
||||
offsets = self._protocol.get_temperature_offsets()
|
||||
|
||||
result = {}
|
||||
result.update(temperatures)
|
||||
for key, tool in result:
|
||||
tool["offset"] = offsets[key] if key in offsets and offsets[key] is not None else 0
|
||||
|
||||
return result
|
||||
|
||||
def getTemperatureHistory(self):
|
||||
return self._temps
|
||||
|
||||
def getCurrentConnection(self):
|
||||
opt = self._protocol.get_current_connection()
|
||||
if "port" in opt.keys() and "baudrate" in opt.keys():
|
||||
return self._protocol.get_state(), opt["port"], opt["baudrate"], self._printerProfileManager.get_current_or_default()
|
||||
return self._protocol.get_state(), None, None, None
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self._protocol.get_state() == ProtocolState.OFFLINE or self._protocol == ProtocolState.ERROR
|
||||
|
||||
def isOperational(self):
|
||||
return not self.isClosedOrError()
|
||||
|
||||
def isPrinting(self):
|
||||
return self._protocol.get_state() == ProtocolState.PRINTING
|
||||
|
||||
def isPaused(self):
|
||||
return self._protocol.get_state() == ProtocolState.PAUSED
|
||||
|
||||
def isError(self):
|
||||
return self._protocol.get_state() == ProtocolState.ERROR
|
||||
|
||||
def isReady(self):
|
||||
return self.isOperational() and not self._protocol.is_streaming()
|
||||
|
||||
def isSdReady(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return False
|
||||
else:
|
||||
return self._protocol.is_sd_ready()
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||
self._ratelimit = ratelimit
|
||||
self._updateCallback = updateCallback
|
||||
self._addTemperatureCallback = addTemperatureCallback
|
||||
self._addLogCallback = addLogCallback
|
||||
self._addMessageCallback = addMessageCallback
|
||||
|
||||
self._state = None
|
||||
self._jobData = None
|
||||
self._gcodeData = None
|
||||
self._sdUploadData = None
|
||||
self._currentZ = None
|
||||
self._progress = None
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._changeEvent = threading.Event()
|
||||
self._stateMutex = threading.Lock()
|
||||
|
||||
self._lastUpdate = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
|
||||
self.setState(state)
|
||||
self.setJobData(jobData)
|
||||
self.setProgress(progress)
|
||||
self.setCurrentZ(currentZ)
|
||||
|
||||
def addTemperature(self, temperature):
|
||||
self._addTemperatureCallback(temperature)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addLog(self, log):
|
||||
self._addLogCallback(log)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addMessage(self, message):
|
||||
self._addMessageCallback(message)
|
||||
self._changeEvent.set()
|
||||
|
||||
def setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._changeEvent.set()
|
||||
|
||||
def setState(self, state):
|
||||
with self._stateMutex:
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
|
||||
def setJobData(self, jobData):
|
||||
self._jobData = jobData
|
||||
self._changeEvent.set()
|
||||
|
||||
def setProgress(self, progress):
|
||||
self._progress = progress
|
||||
self._changeEvent.set()
|
||||
|
||||
def setTempOffsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._changeEvent.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._changeEvent.wait()
|
||||
|
||||
with self._stateMutex:
|
||||
now = time.time()
|
||||
delta = now - self._lastUpdate
|
||||
additionalWaitTime = self._ratelimit - delta
|
||||
if additionalWaitTime > 0:
|
||||
time.sleep(additionalWaitTime)
|
||||
|
||||
data = self.getCurrentData()
|
||||
self._updateCallback(data)
|
||||
self._lastUpdate = time.time()
|
||||
self._changeEvent.clear()
|
||||
|
||||
def getCurrentData(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._jobData,
|
||||
"currentZ": self._currentZ,
|
||||
"progress": self._progress,
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
|
||||
class TimeEstimationHelper(object):
|
||||
|
||||
STABLE_THRESHOLD = 0.1
|
||||
STABLE_COUNTDOWN = 250
|
||||
STABLE_ROLLING_WINDOW = 250
|
||||
|
||||
def __init__(self):
|
||||
import collections
|
||||
self._distances = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW)
|
||||
self._totals = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW)
|
||||
self._sum_total = 0
|
||||
self._count = 0
|
||||
self._stable_counter = None
|
||||
|
||||
def is_stable(self):
|
||||
return self._stable_counter is not None and self._stable_counter >= self.__class__.STABLE_COUNTDOWN
|
||||
|
||||
def update(self, newEstimate):
|
||||
old_average_total = self.average_total
|
||||
|
||||
self._sum_total += newEstimate
|
||||
self._totals.append(newEstimate)
|
||||
self._count += 1
|
||||
|
||||
if old_average_total:
|
||||
self._distances.append(abs(self.average_total - old_average_total))
|
||||
|
||||
if -1.0 * self.__class__.STABLE_THRESHOLD < self.average_distance < self.__class__.STABLE_THRESHOLD:
|
||||
if self._stable_counter is None:
|
||||
self._stable_counter = 0
|
||||
else:
|
||||
self._stable_counter += 1
|
||||
else:
|
||||
self._stable_counter = None
|
||||
|
||||
@property
|
||||
def average_total(self):
|
||||
if not self._count:
|
||||
return None
|
||||
else:
|
||||
return self._sum_total / self._count
|
||||
|
||||
@property
|
||||
def average_total_rolling(self):
|
||||
if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW:
|
||||
return None
|
||||
else:
|
||||
return sum(self._totals) / len(self._totals)
|
||||
|
||||
@property
|
||||
def average_distance(self):
|
||||
if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW + 1:
|
||||
return None
|
||||
else:
|
||||
return sum(self._distances) / len(self._distances)
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import copy
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
|
||||
class BedTypes(object):
|
||||
RECTANGULAR = "rectangular"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class PrinterProfileManager(object):
|
||||
|
||||
default = dict(
|
||||
id = "_default",
|
||||
name = "Default",
|
||||
model = "Generic RepRap Printer",
|
||||
color = "default",
|
||||
volume=dict(
|
||||
width = 200,
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
),
|
||||
heatedBed = False,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
(0, 0)
|
||||
],
|
||||
nozzleDiameter = 0.4
|
||||
),
|
||||
axes=dict(
|
||||
x = dict(speed=6000, inverted=False),
|
||||
y = dict(speed=6000, inverted=False),
|
||||
z = dict(speed=200, inverted=False),
|
||||
e = dict(speed=300, inverted=False)
|
||||
)
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
self._current = None
|
||||
|
||||
self._folder = settings().getBaseFolder("printerProfiles")
|
||||
|
||||
def select(self, identifier):
|
||||
if identifier is None or not self.exists(identifier):
|
||||
self._current = self.get_default()
|
||||
return False
|
||||
else:
|
||||
self._current = self.get(identifier)
|
||||
return True
|
||||
|
||||
def deselect(self):
|
||||
self._current = None
|
||||
|
||||
def get_all(self):
|
||||
return self._load_all()
|
||||
|
||||
def get(self, identifier):
|
||||
if identifier == "_default":
|
||||
return self._load_default()
|
||||
elif self.exists(identifier):
|
||||
return self._load_from_path(self._get_profile_path(identifier))
|
||||
else:
|
||||
return None
|
||||
|
||||
def remove(self, identifier):
|
||||
if identifier == "_default":
|
||||
return False
|
||||
return self._remove_from_path(self._get_profile_path(identifier))
|
||||
|
||||
def save(self, profile, allow_overwrite=False, make_default=False):
|
||||
if "id" in profile:
|
||||
identifier = profile["id"]
|
||||
elif "name" in profile:
|
||||
identifier = profile["name"]
|
||||
else:
|
||||
raise ValueError("profile must contain either id or name")
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
|
||||
settings().save()
|
||||
else:
|
||||
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
if make_default:
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
|
||||
return self.get(identifier)
|
||||
|
||||
def get_default(self):
|
||||
default = settings().get(["printerProfiles", "default"])
|
||||
if default is not None and self.exists(default):
|
||||
profile = self.get(default)
|
||||
if profile is not None:
|
||||
return profile
|
||||
|
||||
return self._load_default()
|
||||
|
||||
def set_default(self, identifier):
|
||||
all_identifiers = self._load_all_identifiers().keys()
|
||||
if identifier is not None and not identifier in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["printerProfile", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
if self._current is not None:
|
||||
return self._current
|
||||
else:
|
||||
return self.get_default()
|
||||
|
||||
def get_current(self):
|
||||
return self._current
|
||||
|
||||
def exists(self, identifier):
|
||||
if identifier is None:
|
||||
return False
|
||||
elif identifier == "_default":
|
||||
return True
|
||||
else:
|
||||
path = self._get_profile_path(identifier)
|
||||
return os.path.exists(path) and os.path.isfile(path)
|
||||
|
||||
def _load_all(self):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
results = dict()
|
||||
for identifier, path in all_identifiers.items():
|
||||
if identifier == "_default":
|
||||
profile = self._load_default()
|
||||
else:
|
||||
profile = self._load_from_path(path)
|
||||
|
||||
if profile is None:
|
||||
continue
|
||||
|
||||
results[identifier] = dict_merge(self._load_default(), profile)
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
for entry in os.listdir(self._folder):
|
||||
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
continue
|
||||
|
||||
path = os.path.join(self._folder, entry)
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
|
||||
identifier = entry[:-len(".profile")]
|
||||
results[identifier] = path
|
||||
return results
|
||||
|
||||
def _load_from_path(self, path):
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
with open(path) as f:
|
||||
profile = yaml.safe_load(f)
|
||||
return profile
|
||||
|
||||
def _save_to_path(self, path, profile, allow_overwrite=False):
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], e.message))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def _load_default(self):
|
||||
default_profile = settings().get(["printerProfiles", "defaultProfile"])
|
||||
return dict_merge(copy.deepcopy(self.__class__.default), default_profile)
|
||||
|
||||
def _get_profile_path(self, identifier):
|
||||
return os.path.join(self._folder, "%s.profile" % identifier)
|
||||
|
||||
def _sanitize(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
@@ -1,64 +1,136 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, render_template, send_from_directory
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response, session
|
||||
from flask.ext.login import LoginManager
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask.ext.babel import Babel
|
||||
from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
|
||||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
import atexit
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
|
||||
app = Flask("octoprint")
|
||||
babel = Babel(app)
|
||||
debug = False
|
||||
|
||||
printer = None
|
||||
gcodeManager = None
|
||||
printerProfileManager = None
|
||||
fileManager = None
|
||||
slicingManager = None
|
||||
analysisQueue = None
|
||||
userManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
pluginManager = None
|
||||
appSessionManager = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
user_permission = Permission(RoleNeed("user"))
|
||||
|
||||
|
||||
from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection
|
||||
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
|
||||
from octoprint.printer import Printer, getConnectionOptions
|
||||
from octoprint.printer.profile import PrinterProfileManager
|
||||
from octoprint.settings import settings
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.util as util
|
||||
import octoprint.users as users
|
||||
import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.util
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
|
||||
from . import util
|
||||
|
||||
|
||||
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
|
||||
versions = octoprint._version.get_versions()
|
||||
VERSION = versions['version']
|
||||
BRANCH = versions['branch'] if 'branch' in versions else None
|
||||
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
|
||||
del versions
|
||||
|
||||
|
||||
def get_available_locale_identifiers(locales):
|
||||
result = set()
|
||||
|
||||
# add available translations
|
||||
for locale in locales:
|
||||
result.add(locale.language)
|
||||
if locale.territory:
|
||||
# if a territory is specified, add that too
|
||||
result.add("%s_%s" % (locale.language, locale.territory))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
LOCALES = [Locale.parse("en")] + babel.list_translations()
|
||||
LANGUAGES = get_available_locale_identifiers(LOCALES)
|
||||
|
||||
|
||||
@app.before_request
|
||||
def before_request():
|
||||
g.locale = get_locale()
|
||||
|
||||
|
||||
@babel.localeselector
|
||||
def get_locale():
|
||||
if "l10n" in request.values:
|
||||
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
|
||||
return request.accept_languages.best_match(LANGUAGES)
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
branch = None
|
||||
commit = None
|
||||
try:
|
||||
branch, commit = util.getGitInfo()
|
||||
except:
|
||||
pass
|
||||
settings_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin)
|
||||
settings_plugin_template_vars = dict()
|
||||
for name, implementation in settings_plugins.items():
|
||||
settings_plugin_template_vars[name] = implementation.get_template_vars()
|
||||
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
asset_plugin_urls = dict()
|
||||
for name, implementation in asset_plugins.items():
|
||||
asset_plugin_urls[name] = implementation.get_assets()
|
||||
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
template_plugin_names = template_plugins.keys()
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None),
|
||||
enableGCodeVisualizer=settings().get(["feature", "gCodeVisualizer"]),
|
||||
enableGCodeVisualizer=settings().get(["gcodeViewer", "enabled"]),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0,
|
||||
enableAccessControl=userManager is not None,
|
||||
enableSdSupport=settings().get(["feature", "sdSupport"]),
|
||||
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
|
||||
debug=debug,
|
||||
gitBranch=branch,
|
||||
gitCommit=commit
|
||||
version=VERSION,
|
||||
display_version=DISPLAY_VERSION,
|
||||
stylesheet=settings().get(["devel", "stylesheet"]),
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||
uiApiKey=UI_API_KEY,
|
||||
settingsPlugins=settings_plugin_template_vars,
|
||||
templatePlugins=template_plugin_names,
|
||||
assetPlugins=asset_plugin_urls
|
||||
)
|
||||
|
||||
|
||||
@@ -67,6 +139,20 @@ def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
|
||||
|
||||
@app.route("/plugin_assets/<string:name>/<path:filename>")
|
||||
def plugin_assets(name, filename):
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
|
||||
if not name in asset_plugins:
|
||||
return make_response("Asset not found", 404)
|
||||
asset_plugin = asset_plugins[name]
|
||||
asset_folder = asset_plugin.get_asset_folder()
|
||||
if asset_folder is None:
|
||||
return make_response("Asset not found", 404)
|
||||
|
||||
return send_from_directory(asset_folder, filename)
|
||||
|
||||
|
||||
@identity_loaded.connect_via(app)
|
||||
def on_identity_loaded(sender, identity):
|
||||
user = load_user(identity.id)
|
||||
@@ -81,8 +167,19 @@ def on_identity_loaded(sender, identity):
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
|
||||
if session and "usersession.id" in session:
|
||||
sessionid = session["usersession.id"]
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if userManager is not None:
|
||||
return userManager.findUser(id)
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -90,30 +187,36 @@ def load_user(id):
|
||||
|
||||
|
||||
class Server():
|
||||
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False):
|
||||
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None):
|
||||
self._configfile = configfile
|
||||
self._basedir = basedir
|
||||
self._host = host
|
||||
self._port = port
|
||||
self._debug = debug
|
||||
self._allowRoot = allowRoot
|
||||
self._logConf = logConf
|
||||
self._server = None
|
||||
|
||||
|
||||
def run(self):
|
||||
if not self._allowRoot:
|
||||
self._checkForRoot()
|
||||
|
||||
global printer
|
||||
global gcodeManager
|
||||
global printerProfileManager
|
||||
global fileManager
|
||||
global slicingManager
|
||||
global analysisQueue
|
||||
global userManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global pluginManager
|
||||
global appSessionManager
|
||||
global debug
|
||||
|
||||
from tornado.wsgi import WSGIContainer
|
||||
from tornado.httpserver import HTTPServer
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application, FallbackHandler
|
||||
from tornado.web import Application
|
||||
|
||||
import sys
|
||||
|
||||
debug = self._debug
|
||||
|
||||
@@ -121,33 +224,77 @@ class Server():
|
||||
self._initSettings(self._configfile, self._basedir)
|
||||
|
||||
# then initialize logging
|
||||
self._initLogging(self._debug)
|
||||
self._initLogging(self._debug, self._logConf)
|
||||
logger = logging.getLogger(__name__)
|
||||
def exception_logger(exc_type, exc_value, exc_tb):
|
||||
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
|
||||
sys.excepthook = exception_logger
|
||||
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
|
||||
|
||||
# then initialize the plugin manager
|
||||
pluginManager = octoprint.plugin.plugin_manager(init=True)
|
||||
|
||||
printerProfileManager = PrinterProfileManager()
|
||||
eventManager = events.eventManager()
|
||||
gcodeManager = gcodefiles.GcodeManager()
|
||||
printer = Printer(gcodeManager)
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
|
||||
slicingManager = octoprint.slicing.SlicingManager(settings().getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(settings().getBaseFolder("uploads"))
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
additional_template_folders = []
|
||||
for plugin in template_plugins.values():
|
||||
folder = plugin.get_template_folder()
|
||||
if folder is not None:
|
||||
additional_template_folders.append(plugin.get_template_folder())
|
||||
|
||||
import jinja2
|
||||
jinja_loader = jinja2.ChoiceLoader([
|
||||
app.jinja_loader,
|
||||
jinja2.FileSystemLoader(additional_template_folders)
|
||||
])
|
||||
app.jinja_loader = jinja_loader
|
||||
del jinja2
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
|
||||
# setup system and gcode command triggers
|
||||
events.SystemCommandTrigger(printer)
|
||||
events.GcodeCommandTrigger(printer)
|
||||
# setup command triggers
|
||||
events.CommandTrigger(printer)
|
||||
if self._debug:
|
||||
events.DebugEventListener()
|
||||
|
||||
if settings().getBoolean(["accessControl", "enabled"]):
|
||||
userManagerName = settings().get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = util.getClass(userManagerName)
|
||||
clazz = octoprint.util.getClass(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||
|
||||
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
||||
app.wsgi_app = util.ReverseProxied(
|
||||
app.wsgi_app,
|
||||
settings().get(["server", "reverseProxy", "prefixHeader"]),
|
||||
settings().get(["server", "reverseProxy", "schemeHeader"]),
|
||||
settings().get(["server", "reverseProxy", "hostHeader"]),
|
||||
settings().get(["server", "reverseProxy", "prefixFallback"]),
|
||||
settings().get(["server", "reverseProxy", "schemeFallback"]),
|
||||
settings().get(["server", "reverseProxy", "hostFallback"])
|
||||
)
|
||||
|
||||
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
|
||||
secret_key = settings().get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
from random import choice
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
secret_key = "".join(choice(chars) for _ in xrange(32))
|
||||
settings().set(["server", "secretKey"], secret_key)
|
||||
settings().save()
|
||||
app.secret_key = secret_key
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
@@ -161,40 +308,103 @@ class Server():
|
||||
if self._port is None:
|
||||
self._port = settings().getInt(["server", "port"])
|
||||
|
||||
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
app.debug = self._debug
|
||||
|
||||
from octoprint.server.ajax import ajax
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.apps import apps
|
||||
|
||||
app.register_blueprint(ajax, url_prefix="/ajax")
|
||||
# register API blueprint
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
app.register_blueprint(apps, url_prefix="/apps")
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for name, plugin in blueprint_plugins.items():
|
||||
blueprint = plugin.get_blueprint()
|
||||
if blueprint is None:
|
||||
continue
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
blueprint.before_request(apiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||
|
||||
upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"]))
|
||||
self._tornado_app = Application(self._router.urls + [
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}),
|
||||
(r"/downloads/gcode/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}),
|
||||
(r".*", FallbackHandler, {"fallback": WSGIContainer(app.wsgi_app)})
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode|g))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
(r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes))
|
||||
])
|
||||
self._server = HTTPServer(self._tornado_app)
|
||||
max_body_sizes = [
|
||||
("POST", r"/api/files/([^/]*)", settings().getInt(["server", "uploads", "maxSize"]))
|
||||
]
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=settings().getInt(["server", "maxSize"]))
|
||||
self._server.listen(self._port, address=self._host)
|
||||
|
||||
eventManager.fire("Startup")
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
if settings().getBoolean(["serial", "autoconnect"]):
|
||||
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = getConnectionOptions()
|
||||
if port in connectionOptions["ports"]:
|
||||
printer.connect(port, baudrate)
|
||||
printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate), profile=printer_profile["id"] if "id" in printer_profile else "_default")
|
||||
|
||||
# start up watchdogs
|
||||
observer = Observer()
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), settings().getBaseFolder("watched"))
|
||||
observer.start()
|
||||
|
||||
ioloop = IOLoop.instance()
|
||||
|
||||
# run our startup plugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_startup",
|
||||
args=(self._host, self._port))
|
||||
|
||||
# prepare our after startup function
|
||||
def on_after_startup():
|
||||
logger.info("Listening on http://%s:%d" % (self._host, self._port))
|
||||
|
||||
# now this is somewhat ugly, but the issue is the following: startup plugins might want to do things for
|
||||
# which they need the server to be already alive (e.g. for being able to resolve urls, such as favicons
|
||||
# or service xmls or the like). While they are working though the ioloop would block. Therefore we'll
|
||||
# create a single use thread in which to perform our after-startup-tasks, start that and hand back
|
||||
# control to the ioloop
|
||||
def work():
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_after_startup")
|
||||
import threading
|
||||
threading.Thread(target=work).start()
|
||||
ioloop.add_callback(on_after_startup)
|
||||
|
||||
# prepare our shutdown function
|
||||
def on_shutdown():
|
||||
logger.info("Goodbye!")
|
||||
observer.stop()
|
||||
observer.join()
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
|
||||
"on_shutdown")
|
||||
atexit.register(on_shutdown)
|
||||
|
||||
try:
|
||||
IOLoop.instance().start()
|
||||
ioloop.start()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except:
|
||||
logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!")
|
||||
logger.exception("Stacktrace follows:")
|
||||
|
||||
def _createSocketConnection(self, session):
|
||||
global printer, gcodeManager, userManager, eventManager
|
||||
return PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
|
||||
global printer, fileManager, analysisQueue, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session)
|
||||
|
||||
def _checkForRoot(self):
|
||||
if "geteuid" in dir(os) and os.geteuid() == 0:
|
||||
@@ -203,8 +413,8 @@ class Server():
|
||||
def _initSettings(self, configfile, basedir):
|
||||
settings(init=True, basedir=basedir, configfile=configfile)
|
||||
|
||||
def _initLogging(self, debug):
|
||||
config = {
|
||||
def _initLogging(self, debug, logConf=None):
|
||||
defaultConfig = {
|
||||
"version": 1,
|
||||
"formatters": {
|
||||
"simple": {
|
||||
@@ -235,16 +445,13 @@ class Server():
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
#"octoprint.timelapse": {
|
||||
# "level": "DEBUG"
|
||||
#},
|
||||
#"octoprint.events": {
|
||||
# "level": "DEBUG"
|
||||
#},
|
||||
"SERIAL": {
|
||||
"TRANSPORT": {
|
||||
"level": "CRITICAL",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"tornado.application": {
|
||||
"level": "ERROR"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
@@ -254,15 +461,25 @@ class Server():
|
||||
}
|
||||
|
||||
if debug:
|
||||
config["root"]["level"] = "DEBUG"
|
||||
defaultConfig["root"]["level"] = "DEBUG"
|
||||
|
||||
if logConf is None:
|
||||
logConf = os.path.join(settings().settings_dir, "logging.yaml")
|
||||
|
||||
configFromFile = {}
|
||||
if os.path.exists(logConf) and os.path.isfile(logConf):
|
||||
import yaml
|
||||
with open(logConf, "r") as f:
|
||||
configFromFile = yaml.safe_load(f)
|
||||
|
||||
config = octoprint.util.dict_merge(defaultConfig, configFromFile)
|
||||
logging.config.dictConfig(config)
|
||||
|
||||
if settings().getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
|
||||
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
|
||||
|
||||
if __name__ == "__main__":
|
||||
octoprint = Server()
|
||||
octoprint.run()
|
||||
server = Server()
|
||||
server.run()
|
||||
@@ -1,141 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import netaddr
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response
|
||||
from flask.ext.login import login_user, logout_user, current_user
|
||||
from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
from octoprint.server import restricted_access, SUCCESS, admin_permission, loginManager, principals
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
|
||||
#~~ init ajax blueprint, including sub modules
|
||||
|
||||
ajax = Blueprint("ajax", __name__)
|
||||
|
||||
from . import control as ajax_control
|
||||
from . import gcodefiles as ajax_gcodefiles
|
||||
from . import settings as ajax_settings
|
||||
from . import timelapse as ajax_timelapse
|
||||
from . import users as ajax_users
|
||||
|
||||
|
||||
#~~ first run setup
|
||||
|
||||
|
||||
@ajax.route("/setup", methods=["POST"])
|
||||
def firstRunSetup():
|
||||
if not s().getBoolean(["server", "firstRun"]):
|
||||
abort(403)
|
||||
|
||||
if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
|
||||
"user" in request.values.keys() and "pass1" in request.values.keys() and \
|
||||
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
|
||||
# configure access control
|
||||
s().setBoolean(["accessControl", "enabled"], True)
|
||||
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
|
||||
# disable access control
|
||||
s().setBoolean(["accessControl", "enabled"], False)
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
|
||||
loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
|
||||
s().save()
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
#~~ system control
|
||||
|
||||
|
||||
@ajax.route("/system", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def performSystemAction():
|
||||
logger = logging.getLogger(__name__)
|
||||
if request.values.has_key("action"):
|
||||
action = request.values["action"]
|
||||
availableActions = s().get(["system", "actions"])
|
||||
for availableAction in availableActions:
|
||||
if availableAction["action"] == action:
|
||||
logger.info("Performing command: %s" % availableAction["command"])
|
||||
try:
|
||||
subprocess.check_output(availableAction["command"], shell=True)
|
||||
except subprocess.CalledProcessError, e:
|
||||
logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message))
|
||||
return make_response(("Command failed with return code %i: %s" % (e.returncode, e.message), 500, []))
|
||||
except Exception, ex:
|
||||
logger.exception("Command failed")
|
||||
return make_response(("Command failed: %r" % ex, 500, []))
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
#~~ Login/user handling
|
||||
|
||||
|
||||
@ajax.route("/login", methods=["POST"])
|
||||
def login():
|
||||
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||
username = request.values["user"]
|
||||
password = request.values["pass"]
|
||||
|
||||
if "remember" in request.values.keys() and request.values["remember"] == "true":
|
||||
remember = True
|
||||
else:
|
||||
remember = False
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if user.check_password(octoprint.users.UserManager.createPasswordHash(password)):
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
elif "passive" in request.values.keys():
|
||||
user = current_user
|
||||
if user is not None and not user.is_anonymous():
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
elif s().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and s().get(["accessControl", "autologinAs"]) is not None \
|
||||
and s().get(["accessControl", "localNetworks"]) is not None:
|
||||
|
||||
autologinAs = s().get(["accessControl", "autologinAs"])
|
||||
localNetworks = netaddr.IPSet([])
|
||||
for ip in s().get(["accessControl", "localNetworks"]):
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = util.getRemoteAddress(request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
login_user(user)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
except:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.auth_type'):
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
logout_user()
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@@ -1,288 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.server import printer, restricted_access, SUCCESS
|
||||
from octoprint.server.ajax import ajax
|
||||
import octoprint.util as util
|
||||
|
||||
#~~ Printer control
|
||||
|
||||
|
||||
@ajax.route("/control/connection", methods=["GET"])
|
||||
def connectionOptions():
|
||||
state, port, baudrate = printer.getCurrentConnection()
|
||||
current = {
|
||||
"state": state,
|
||||
"port": port,
|
||||
"baudrate": baudrate
|
||||
}
|
||||
return jsonify({"current": current, "options": getConnectionOptions()})
|
||||
|
||||
|
||||
@ajax.route("/control/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": ["autoconnect"],
|
||||
"disconnect": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "connect":
|
||||
options = getConnectionOptions()
|
||||
|
||||
port = None
|
||||
baudrate = None
|
||||
if "port" in data.keys():
|
||||
port = data["port"]
|
||||
if port not in options["ports"]:
|
||||
return make_response("Invalid port: %s" % port, 400)
|
||||
if "baudrate" in data.keys():
|
||||
baudrate = data["baudrate"]
|
||||
if baudrate not in options["baudrates"]:
|
||||
return make_response("Invalid baudrate: %d" % baudrate, 400)
|
||||
if "save" in data.keys() and data["save"]:
|
||||
settings().set(["serial", "port"], port)
|
||||
settings().setInt(["serial", "baudrate"], baudrate)
|
||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||
settings().save()
|
||||
printer.connect(port=port, baudrate=baudrate)
|
||||
elif command == "disconnect":
|
||||
printer.disconnect()
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 403)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
|
||||
parameters = {}
|
||||
if "parameters" in data.keys(): parameters = data["parameters"]
|
||||
|
||||
commands = []
|
||||
if "command" in data.keys(): commands = [data["command"]]
|
||||
elif "commands" in data.keys(): commands = data["commands"]
|
||||
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/job", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlJob():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 403)
|
||||
|
||||
valid_commands = {
|
||||
"start": [],
|
||||
"pause": [],
|
||||
"cancel": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "start":
|
||||
printer.startPrint()
|
||||
elif command == "pause":
|
||||
printer.togglePausePrint()
|
||||
elif command == "cancel":
|
||||
printer.cancelPrint()
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/printer/hotend", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlPrinterHotend():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 403)
|
||||
|
||||
valid_commands = {
|
||||
"temp": ["temps"],
|
||||
"offset": ["offsets"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
valid_targets = ["hotend", "bed"]
|
||||
|
||||
##~~ temperature
|
||||
if command == "temp":
|
||||
temps = data["temps"]
|
||||
|
||||
# make sure the targets are valid and the values are numbers
|
||||
validated_values = {}
|
||||
for type, value in temps.iteritems():
|
||||
if not type in valid_targets:
|
||||
return make_response("Invalid target for setting temperature: %s" % type, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (type, value), 400)
|
||||
validated_values[type] = value
|
||||
|
||||
# perform the actual temperature commands
|
||||
# TODO make this a generic method call (printer.setTemperature(type, value)) to get rid of gcode here
|
||||
if "hotend" in validated_values:
|
||||
printer.command("M104 S%f" % validated_values["hotend"])
|
||||
if "bed" in validated_values:
|
||||
printer.command("M140 S%f" % validated_values["bed"])
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offsets = data["offsets"]
|
||||
|
||||
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
|
||||
validated_values = {}
|
||||
for type, value in offsets.iteritems():
|
||||
if not type in valid_targets:
|
||||
return make_response("Invalid target for setting temperature: %s" % type, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (type, value), 400)
|
||||
if not -50 <= value <= 50:
|
||||
return make_response("Offset %s not in range [-50, 50]: %f" % (type, value), 400)
|
||||
validated_values[type] = value
|
||||
|
||||
# set the offsets
|
||||
if "hotend" in validated_values and "bed" in validated_values:
|
||||
printer.setTemperatureOffset(validated_values["hotend"], validated_values["bed"])
|
||||
elif "hotend" in validated_values:
|
||||
printer.setTemperatureOffset(validated_values["hotend"], None)
|
||||
elif "bed" in validated_values:
|
||||
printer.setTemperatureOffset(None, validated_values["bed"])
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/printer/printhead", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlPrinterPrinthead():
|
||||
if not printer.isOperational() or printer.isPrinting():
|
||||
# do not jog when a print job is running or we don't have a connection
|
||||
return make_response("Printer is not operational or currently printing", 403)
|
||||
|
||||
valid_commands = {
|
||||
"jog": [],
|
||||
"home": ["axes"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True)
|
||||
|
||||
valid_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
# validate all jog instructions, make sure that the values are numbers
|
||||
validated_values = {}
|
||||
for axis in valid_axes:
|
||||
if axis in data:
|
||||
value = data[axis]
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for axis %s: %r" % (axis, value), 400)
|
||||
validated_values[axis] = value
|
||||
|
||||
# execute the jog commands
|
||||
for axis, value in validated_values.iteritems():
|
||||
# TODO make this a generic method call (printer.jog(axis, value)) to get rid of gcode here
|
||||
printer.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), value, movementSpeed[axis]), "G90"])
|
||||
|
||||
##~~ home command
|
||||
elif command == "home":
|
||||
validated_values = []
|
||||
axes = data["axes"]
|
||||
for axis in axes:
|
||||
if not axis in valid_axes:
|
||||
return make_response("Invalid axis: %s" % axis, 400)
|
||||
validated_values.append(axis)
|
||||
|
||||
# execute the home command
|
||||
# TODO make this a generic method call (printer.home(axis, ...)) to get rid of gcode here
|
||||
printer.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_values)), "G90"])
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/printer/feeder", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlPrinterFeeder():
|
||||
if not printer.isOperational() or printer.isPrinting():
|
||||
# do not jog when a print job is running or we don't have a connection
|
||||
return make_response("Printer is not operational or currently printing", 403)
|
||||
|
||||
valid_commands = {
|
||||
"extrude": ["amount"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"])
|
||||
|
||||
if command == "extrude":
|
||||
amount = data["amount"]
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
|
||||
# TODO make this a generic method call (printer.extruder([hotend,] amount)) to get rid of gcode here
|
||||
printer.commands(["G91", "G1 E%s F%d" % (data["amount"], extrusionSpeed), "G90"])
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@ajax.route("/control/custom", methods=["GET"])
|
||||
def getCustomControls():
|
||||
customControls = settings().get(["controls"])
|
||||
return jsonify(controls=customControls)
|
||||
|
||||
|
||||
@ajax.route("/control/sd", methods=["POST"])
|
||||
@restricted_access
|
||||
def sdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or not printer.isOperational() or printer.isPrinting():
|
||||
return make_response("SD support is disabled", 403)
|
||||
|
||||
valid_commands = {
|
||||
"init": [],
|
||||
"refresh": [],
|
||||
"release": []
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "init":
|
||||
printer.initSdCard()
|
||||
elif command == "refresh":
|
||||
printer.refreshSdFiles()
|
||||
elif command == "release":
|
||||
printer.releaseSdCard()
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, gcodeManager, eventManager, restricted_access, SUCCESS
|
||||
from octoprint.server.util import redirectToTornado
|
||||
from octoprint.server.ajax import ajax
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
files = _getFileList(FileDestinations.LOCAL)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads"))))
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/<string:target>", methods=["GET"])
|
||||
def readGcodeFilesForTarget(target):
|
||||
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Invalid target: %s" % target, 400)
|
||||
|
||||
return jsonify(files=_getFileList(target), free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads"))))
|
||||
|
||||
|
||||
def _getFileList(target):
|
||||
if target == FileDestinations.SDCARD:
|
||||
sdFileList = printer.getSdFiles()
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile in sdFileList:
|
||||
files.append({
|
||||
"name": sdFile,
|
||||
"size": "n/a",
|
||||
"bytes": 0,
|
||||
"date": "n/a",
|
||||
"origin": FileDestinations.SDCARD
|
||||
})
|
||||
else:
|
||||
files = gcodeManager.getAllFileData()
|
||||
return files
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/<string:target>", methods=["POST"])
|
||||
@restricted_access
|
||||
def uploadGcodeFile(target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Invalid target: %s" % target, 400)
|
||||
|
||||
if "gcode_file" in request.files.keys():
|
||||
file = request.files["gcode_file"]
|
||||
sd = target == FileDestinations.SDCARD
|
||||
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
|
||||
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentSd = None
|
||||
currentJob = printer.getCurrentJob()
|
||||
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||
currentFilename = currentJob["filename"]
|
||||
currentSd = currentJob["sd"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
futureFilename = gcodeManager.getFutureFilename(file)
|
||||
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
|
||||
return make_response("Can not upload file %s, wrong format?" % file.filename, 400)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused():
|
||||
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 403)
|
||||
|
||||
filename = None
|
||||
|
||||
def fileProcessingFinished(filename, absFilename, destination):
|
||||
"""
|
||||
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
|
||||
finished.
|
||||
|
||||
Depending on the file's destination triggers either streaming to SD card or directly calls selectOrPrint.
|
||||
"""
|
||||
sd = destination == FileDestinations.SDCARD
|
||||
if sd:
|
||||
printer.addSdFile(filename, absFilename, selectAndOrPrint)
|
||||
else:
|
||||
selectAndOrPrint(absFilename, destination)
|
||||
|
||||
def selectAndOrPrint(nameToSelect, destination):
|
||||
"""
|
||||
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this only
|
||||
the case after they have finished streaming to the printer, which is why this callback is also used
|
||||
for the corresponding call to addSdFile.
|
||||
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
sd = destination == FileDestinations.SDCARD
|
||||
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd):
|
||||
printer.selectFile(nameToSelect, sd, printAfterSelect)
|
||||
|
||||
destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
|
||||
filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished)
|
||||
if filename is None:
|
||||
return make_response("Could not upload the file %s" % file.filename, 500)
|
||||
|
||||
eventManager.fire("Upload", filename)
|
||||
return jsonify(files=gcodeManager.getAllFileData(), filename=filename, done=done)
|
||||
else:
|
||||
return make_response("No gcode_file included", 400)
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/local/<path:filename>", methods=["GET"])
|
||||
def readGcodeFile(filename):
|
||||
return redirectToTornado(request, url_for("index") + "downloads/gcode/" + filename)
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/<string:target>/<path:filename>", methods=["POST"])
|
||||
@restricted_access
|
||||
def gcodeFileCommand(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Invalid target: %s" % target, 400)
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"load": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "load":
|
||||
# selects/loads a file
|
||||
printAfterLoading = False
|
||||
if "print" in data.keys() and data["print"]:
|
||||
printAfterLoading = True
|
||||
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = gcodeManager.getAbsolutePath(filename)
|
||||
printer.selectFile(filenameToSelect, sd, printAfterLoading)
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return make_response("Command %s is currently not implemented" % command, 400)
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/<string:target>/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Invalid target: %s" % target, 400)
|
||||
|
||||
sd = target == FileDestinations.SDCARD
|
||||
|
||||
currentJob = printer.getCurrentJob()
|
||||
currentFilename = None
|
||||
currentSd = None
|
||||
if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys():
|
||||
currentFilename = currentJob["filename"]
|
||||
currentSd = currentJob["sd"]
|
||||
|
||||
if currentFilename is not None and filename == currentFilename and not (printer.isPrinting() or printer.isPaused()):
|
||||
printer.unselectFile()
|
||||
|
||||
if not (currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused())):
|
||||
if sd:
|
||||
printer.deleteSdFile(filename)
|
||||
else:
|
||||
gcodeManager.removeFile(filename)
|
||||
return readGcodeFiles()
|
||||
|
||||
|
||||
@ajax.route("/gcodefiles/<string:target>/refresh", methods=["POST"])
|
||||
@restricted_access
|
||||
def refreshFiles(target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Invalid target: %s" % target, 400)
|
||||
|
||||
if target == FileDestinations.SDCARD:
|
||||
printer.updateSdFiles()
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort
|
||||
|
||||
from octoprint.server import printer, gcodeManager, SUCCESS
|
||||
from octoprint.server.util import api_access
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
|
||||
api = Blueprint("api", __name__)
|
||||
|
||||
|
||||
|
||||
@api.route("/load", methods=["POST"])
|
||||
@api_access
|
||||
def apiLoad():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
if not "file" in request.files.keys():
|
||||
abort(400)
|
||||
|
||||
# Perform an upload
|
||||
f = request.files["file"]
|
||||
if not gcodefiles.isGcodeFileName(f.filename):
|
||||
abort(400)
|
||||
|
||||
destination = FileDestinations.LOCAL
|
||||
filename, done = gcodeManager.addFile(f, destination)
|
||||
if filename is None:
|
||||
logger.warn("Upload via API failed")
|
||||
abort(500)
|
||||
|
||||
# Immediately perform a file select and possibly print too
|
||||
printAfterSelect = False
|
||||
if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues:
|
||||
printAfterSelect = True
|
||||
filepath = gcodeManager.getAbsolutePath(filename)
|
||||
if filepath is not None:
|
||||
printer.selectFile(filepath, False, printAfterSelect)
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@api_access
|
||||
def apiPrinterState():
|
||||
currentData = printer.getCurrentData()
|
||||
currentData.update({
|
||||
"temperatures": printer.getCurrentTemperatures()
|
||||
})
|
||||
return jsonify(currentData)
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import netaddr
|
||||
import sarge
|
||||
|
||||
from flask import Blueprint, request, jsonify, abort, current_app, session, make_response
|
||||
from flask.ext.login import login_user, logout_user, current_user
|
||||
from flask.ext.principal import Identity, identity_changed, AnonymousIdentity
|
||||
|
||||
import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
|
||||
api = Blueprint("api", __name__)
|
||||
|
||||
from . import printer as api_printer
|
||||
from . import job as api_job
|
||||
from . import connection as api_connection
|
||||
from . import files as api_files
|
||||
from . import settings as api_settings
|
||||
from . import timelapse as api_timelapse
|
||||
from . import users as api_users
|
||||
from . import log as api_logs
|
||||
from . import slicing as api_slicing
|
||||
from . import printer_profiles as api_printer_profiles
|
||||
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
#~~ data from plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["GET"])
|
||||
def pluginData(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
|
||||
if not name in api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
|
||||
api_plugin = api_plugins[name]
|
||||
response = api_plugin.on_api_get(request)
|
||||
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ commands for plugins
|
||||
|
||||
@api.route("/plugin/<string:name>", methods=["POST"])
|
||||
@restricted_access
|
||||
def pluginCommand(name):
|
||||
api_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SimpleApiPlugin)
|
||||
if not name in api_plugins:
|
||||
return make_response("Not found", 404)
|
||||
|
||||
api_plugin = api_plugins[name]
|
||||
valid_commands = api_plugin.get_api_commands()
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
response = api_plugin.on_api_command(command, data)
|
||||
if response is not None:
|
||||
return response
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ first run setup
|
||||
|
||||
|
||||
@api.route("/setup", methods=["POST"])
|
||||
def firstRunSetup():
|
||||
if not s().getBoolean(["server", "firstRun"]):
|
||||
abort(403)
|
||||
|
||||
if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
|
||||
"user" in request.values.keys() and "pass1" in request.values.keys() and \
|
||||
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
|
||||
# configure access control
|
||||
s().setBoolean(["accessControl", "enabled"], True)
|
||||
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
|
||||
# disable access control
|
||||
s().setBoolean(["accessControl", "enabled"], False)
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
|
||||
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
|
||||
s().save()
|
||||
return NO_CONTENT
|
||||
|
||||
#~~ system state
|
||||
|
||||
|
||||
@api.route("/state", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiPrinterState():
|
||||
return make_response(("/api/state has been deprecated, use /api/printer instead", 405, []))
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
return jsonify({
|
||||
"server": octoprint.server.VERSION,
|
||||
"api": VERSION
|
||||
})
|
||||
|
||||
#~~ system control
|
||||
|
||||
|
||||
@api.route("/system", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def performSystemAction():
|
||||
logger = logging.getLogger(__name__)
|
||||
if "action" in request.values.keys():
|
||||
action = request.values["action"]
|
||||
available_actions = s().get(["system", "actions"])
|
||||
for availableAction in available_actions:
|
||||
if availableAction["action"] == action:
|
||||
logger.info("Performing command: %s" % availableAction["command"])
|
||||
try:
|
||||
# Note: we put the command in brackets since sarge (up to the most recently released version) has
|
||||
# a bug concerning shell=True commands. Once sarge 0.1.4 we can upgrade to that and remove this
|
||||
# workaround again
|
||||
#
|
||||
# See https://bitbucket.org/vinay.sajip/sarge/issue/21/behavior-is-not-like-popen-using-shell
|
||||
p = sarge.run([availableAction["command"]], stderr=sarge.Capture(), shell=True)
|
||||
if p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stderr_text = p.stderr.text
|
||||
logger.warn("Command failed with return code %i: %s" % (returncode, stderr_text))
|
||||
return make_response(("Command failed with return code %i: %s" % (returncode, stderr_text), 500, []))
|
||||
except Exception, e:
|
||||
logger.warn("Command failed: %s" % e)
|
||||
return make_response(("Command failed: %s" % e, 500, []))
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
#~~ Login/user handling
|
||||
|
||||
|
||||
@api.route("/login", methods=["POST"])
|
||||
def login():
|
||||
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||
username = request.values["user"]
|
||||
password = request.values["pass"]
|
||||
|
||||
if "remember" in request.values.keys() and request.values["remember"] == "true":
|
||||
remember = True
|
||||
else:
|
||||
remember = False
|
||||
|
||||
if "usersession.id" in session:
|
||||
_logout(current_user)
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
elif "passive" in request.values.keys():
|
||||
if octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(current_user)
|
||||
else:
|
||||
user = current_user
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
elif s().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and s().get(["accessControl", "autologinAs"]) is not None \
|
||||
and s().get(["accessControl", "localNetworks"]) is not None:
|
||||
|
||||
autologinAs = s().get(["accessControl", "autologinAs"])
|
||||
localNetworks = netaddr.IPSet([])
|
||||
for ip in s().get(["accessControl", "localNetworks"]):
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = util.getRemoteAddress(request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
login_user(user)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
except:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/logout", methods=["POST"])
|
||||
@restricted_access
|
||||
def logout():
|
||||
# Remove session keys set by Flask-Principal
|
||||
for key in ('identity.id', 'identity.name', 'identity.auth_type'):
|
||||
if key in session:
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
_logout(current_user)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _logout(user):
|
||||
if "usersession.id" in session:
|
||||
del session["usersession.id"]
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
@@ -0,0 +1,88 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
def connectionState():
|
||||
state, port, baudrate, printer_profile = printer.getCurrentConnection()
|
||||
current = {
|
||||
"state": state,
|
||||
"port": port,
|
||||
"baudrate": baudrate,
|
||||
"printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default"
|
||||
}
|
||||
|
||||
return jsonify({"current": current, "options": _get_options()})
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": [],
|
||||
"disconnect": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "connect":
|
||||
connection_options = getConnectionOptions()
|
||||
|
||||
port = None
|
||||
baudrate = None
|
||||
printerProfile = None
|
||||
if "port" in data.keys():
|
||||
port = data["port"]
|
||||
if port not in connection_options["ports"]:
|
||||
return make_response("Invalid port: %s" % port, 400)
|
||||
if "baudrate" in data.keys():
|
||||
baudrate = data["baudrate"]
|
||||
if baudrate not in connection_options["baudrates"]:
|
||||
return make_response("Invalid baudrate: %d" % baudrate, 400)
|
||||
if "printerProfile" in data.keys():
|
||||
printerProfile = data["printerProfile"]
|
||||
if not printerProfileManager.exists(printerProfile):
|
||||
return make_response("Invalid printer profile: %s" % printerProfile, 400)
|
||||
if "save" in data.keys() and data["save"]:
|
||||
settings().set(["serial", "port"], port)
|
||||
settings().setInt(["serial", "baudrate"], baudrate)
|
||||
printerProfileManager.set_default(printerProfile)
|
||||
if "autoconnect" in data.keys():
|
||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||
settings().save()
|
||||
printer.connect(transport_option_overrides=dict(port=port, baudrate=baudrate), profile=printerProfile)
|
||||
elif command == "disconnect":
|
||||
printer.disconnect()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _get_options():
|
||||
connection_options = getConnectionOptions()
|
||||
profile_options = printerProfileManager.get_all()
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
|
||||
)
|
||||
|
||||
return options
|
||||
@@ -0,0 +1,439 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.events import Events
|
||||
import octoprint.filemanager
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
|
||||
@api.route("/files", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
filter = None
|
||||
if "filter" in request.values:
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
def readGcodeFilesForOrigin(origin):
|
||||
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown origin: %s" % origin, 404)
|
||||
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
|
||||
def _getFileDetails(origin, filename):
|
||||
files = _getFileList(origin)
|
||||
for file in files:
|
||||
if file["name"] == filename:
|
||||
return file
|
||||
return None
|
||||
|
||||
|
||||
def _getFileList(origin, filter=None):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.getSdFiles()
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile, sdSize in sdFileList:
|
||||
file = {
|
||||
"type": "machinecode",
|
||||
"name": sdFile,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFile, _external=True)
|
||||
}
|
||||
}
|
||||
if sdSize is not None:
|
||||
file.update({"size": sdSize})
|
||||
files.append(file)
|
||||
else:
|
||||
filter_func = None
|
||||
if filter:
|
||||
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
|
||||
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
|
||||
for file in files:
|
||||
file["origin"] = FileDestinations.LOCAL
|
||||
|
||||
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
file["gcodeAnalysis"] = file["analysis"]
|
||||
del file["analysis"]
|
||||
|
||||
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
# convert print log
|
||||
history = file["history"]
|
||||
del file["history"]
|
||||
success = 0
|
||||
failure = 0
|
||||
last = None
|
||||
for entry in history:
|
||||
success += 1 if "success" in entry and entry["success"] else 0
|
||||
failure += 1 if "success" in entry and not entry["success"] else 0
|
||||
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
|
||||
last = entry
|
||||
if last:
|
||||
prints = dict(
|
||||
success=success,
|
||||
failure=failure,
|
||||
last=dict(
|
||||
success=last["success"],
|
||||
date=last["timestamp"]
|
||||
)
|
||||
)
|
||||
if "printTime" in last:
|
||||
prints["last"]["printTime"] = last["printTime"]
|
||||
file["prints"] = prints
|
||||
|
||||
file.update({
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file["name"]
|
||||
}
|
||||
})
|
||||
return files
|
||||
|
||||
|
||||
def _verifyFileExists(origin, filename):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
return filename in map(lambda x: x[0], printer.getSdFiles())
|
||||
else:
|
||||
return fileManager.file_exists(origin, filename)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@restricted_access
|
||||
def uploadGcodeFile(target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
input_name = "file"
|
||||
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
|
||||
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
|
||||
if input_upload_name in request.values and input_upload_path in request.values:
|
||||
import shutil
|
||||
upload = util.Object()
|
||||
upload.filename = request.values[input_upload_name]
|
||||
upload.save = lambda new_path: shutil.move(request.values[input_upload_path], new_path)
|
||||
elif input_name in request.files:
|
||||
upload = request.files[input_name]
|
||||
else:
|
||||
return make_response("No file included", 400)
|
||||
|
||||
if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD card support is disabled", 404)
|
||||
|
||||
sd = target == FileDestinations.SDCARD
|
||||
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
|
||||
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
|
||||
|
||||
if sd:
|
||||
# validate that all preconditions for SD upload are met before attempting it
|
||||
if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())):
|
||||
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
|
||||
if not printer.isSdReady():
|
||||
return make_response("Can not upload to SD card, not yet initialized", 409)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = printer.getCurrentJob()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
|
||||
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused():
|
||||
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
|
||||
|
||||
def fileProcessingFinished(filename, absFilename, destination):
|
||||
"""
|
||||
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
|
||||
finished.
|
||||
|
||||
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
|
||||
"""
|
||||
|
||||
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
|
||||
return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint)
|
||||
else:
|
||||
selectAndOrPrint(filename, absFilename, destination)
|
||||
return filename
|
||||
|
||||
def selectAndOrPrint(filename, absFilename, destination):
|
||||
"""
|
||||
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only
|
||||
the case after they have finished streaming to the printer, which is why this callback is also used
|
||||
for the corresponding call to addSdFile.
|
||||
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
|
||||
printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
|
||||
added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True)
|
||||
if added_file is None:
|
||||
return make_response("Could not upload the file %s" % upload.filename, 500)
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl"):
|
||||
filename = added_file
|
||||
done = True
|
||||
else:
|
||||
filename = fileProcessingFinished(added_file, fileManager.get_absolute_path(FileDestinations.LOCAL, added_file), target)
|
||||
done = True
|
||||
|
||||
sdFilename = None
|
||||
if isinstance(filename, tuple):
|
||||
filename, sdFilename = filename
|
||||
|
||||
eventManager.fire(Events.UPLOAD, {"file": filename, "target": target})
|
||||
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True)
|
||||
files.update({
|
||||
FileDestinations.LOCAL: {
|
||||
"name": filename,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if sd and sdFilename:
|
||||
location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True)
|
||||
files.update({
|
||||
FileDestinations.SDCARD: {
|
||||
"name": sdFilename,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
"resource": location
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
r = make_response(jsonify(files=files, done=done), 201)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
|
||||
def readGcodeFile(target, filename):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
file = _getFileDetails(target, filename)
|
||||
if not file:
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
return jsonify(file)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["POST"])
|
||||
@restricted_access
|
||||
def gcodeFileCommand(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"select": [],
|
||||
"slice": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "select":
|
||||
# selects/loads a file
|
||||
printAfterLoading = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = filename
|
||||
else:
|
||||
filenameToSelect = fileManager.get_absolute_path(target, filename)
|
||||
printer.selectFile(filenameToSelect, target, printAfterLoading)
|
||||
|
||||
elif command == "slice":
|
||||
if "slicer" in data.keys():
|
||||
slicer = data["slicer"]
|
||||
del data["slicer"]
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Slicer {slicer} is not available".format(**locals()), 400)
|
||||
slicer_instance = slicingManager.get_slicer(slicer)
|
||||
elif "cura" in slicingManager.registered_slicers:
|
||||
slicer = "cura"
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
else:
|
||||
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
|
||||
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
|
||||
|
||||
if slicer_instance.get_slicer_properties()["same_device"] and (printer.isPrinting() or printer.isPaused()):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
|
||||
|
||||
if "gcode" in data.keys() and data["gcode"]:
|
||||
gcode_name = data["gcode"]
|
||||
del data["gcode"]
|
||||
else:
|
||||
import os
|
||||
name, _ = os.path.splitext(filename)
|
||||
gcode_name = name + ".gco"
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == gcode_name and currentOrigin == target and (printer.isPrinting() or printer.isPaused()):
|
||||
make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409)
|
||||
|
||||
if "profile" in data.keys() and data["profile"]:
|
||||
profile = data["profile"]
|
||||
del data["profile"]
|
||||
else:
|
||||
profile = None
|
||||
|
||||
if "printerProfile" in data.keys() and data["printerProfile"]:
|
||||
printerProfile = data["printerProfile"]
|
||||
del data["printerProfile"]
|
||||
else:
|
||||
printerProfile = None
|
||||
|
||||
if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]:
|
||||
position = data["position"]
|
||||
del data["position"]
|
||||
else:
|
||||
position = None
|
||||
|
||||
select_after_slicing = False
|
||||
if "select" in data.keys() and data["select"] in valid_boolean_trues:
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational, cannot directly select for printing", 409)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
def slicing_done(target, gcode_name, select_after_slicing, print_after_slicing):
|
||||
if select_after_slicing or print_after_slicing:
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = gcode_name
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.get_absolute_path(target, gcode_name)
|
||||
printer.selectFile(filenameToSelect, sd, print_after_slicing)
|
||||
|
||||
ok, result = fileManager.slice(slicer, target, filename, target, gcode_name,
|
||||
profile=profile,
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, gcode_name, select_after_slicing, print_after_slicing))
|
||||
|
||||
if ok:
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
|
||||
result = {
|
||||
"name": gcode_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
|
||||
}
|
||||
}
|
||||
|
||||
r = make_response(jsonify(result), 202)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
else:
|
||||
return make_response("Could not slice: {result}".format(result=result), 500)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteGcodeFile(filename, target):
|
||||
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
|
||||
return make_response("Unknown target: %s" % target, 404)
|
||||
|
||||
if not _verifyFileExists(target, filename):
|
||||
return make_response("File not found on '%s': %s" % (target, filename), 404)
|
||||
|
||||
# prohibit deleting files that are currently in use
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == filename and currentOrigin == target and (printer.isPrinting() or printer.isPaused()):
|
||||
make_response("Trying to delete file that is currently being printed: %s" % filename, 409)
|
||||
|
||||
if (target, filename) in fileManager.get_busy_files():
|
||||
make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselectFile()
|
||||
|
||||
# delete it
|
||||
if target == FileDestinations.SDCARD:
|
||||
printer.deleteSdFile(filename)
|
||||
else:
|
||||
fileManager.remove_file(target, filename)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _getCurrentFile():
|
||||
currentJob = printer.getCurrentJob()
|
||||
if currentJob is not None and "file" in currentJob.keys() and "name" in currentJob["file"] and "origin" in currentJob["file"]:
|
||||
return currentJob["file"]["origin"], currentJob["file"]["name"]
|
||||
else:
|
||||
return None, None
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/job", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlJob():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"start": [],
|
||||
"restart": [],
|
||||
"pause": [],
|
||||
"cancel": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
activePrintjob = printer.isPrinting() or printer.isPaused()
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.startPrint()
|
||||
elif command == "restart":
|
||||
if not printer.isPaused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.startPrint()
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
printer.togglePausePrint()
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancelPrint()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/job", methods=["GET"])
|
||||
def jobState():
|
||||
currentData = printer.getCurrentData()
|
||||
return jsonify({
|
||||
"job": currentData["job"],
|
||||
"progress": currentData["progress"],
|
||||
"state": currentData["state"]["text"]
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Marc Hannappel Salandora"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import getFreeBytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs")))
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def downloadLog(filename):
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def deleteLog(filename):
|
||||
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
|
||||
if not os.path.exists(secure):
|
||||
return make_response("File not found: %s" % filename, 404)
|
||||
|
||||
os.remove(secure)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
def _getLogFiles():
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("logs")
|
||||
for osFile in os.listdir(basedir):
|
||||
statResult = os.stat(os.path.join(basedir, osFile))
|
||||
files.append({
|
||||
"name": osFile,
|
||||
"date": int(statResult.st_mtime),
|
||||
"size": statResult.st_size,
|
||||
"refs": {
|
||||
"resource": url_for(".downloadLog", filename=osFile, _external=True),
|
||||
"download": url_for("index", _external=True) + "downloads/logs/" + osFile
|
||||
}
|
||||
})
|
||||
|
||||
return files
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, Response
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
import octoprint.util as util
|
||||
|
||||
#~~ Printer
|
||||
|
||||
|
||||
@api.route("/printer", methods=["GET"])
|
||||
def printerState():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
# process excludes
|
||||
excludes = []
|
||||
if "exclude" in request.values:
|
||||
excludeStr = request.values["exclude"]
|
||||
if len(excludeStr.strip()) > 0:
|
||||
excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(",")))
|
||||
|
||||
result = {}
|
||||
|
||||
# add temperature information
|
||||
if not "temperature" in excludes:
|
||||
result.update({"temperature": _getTemperatureData(lambda x: x)})
|
||||
|
||||
# add sd information
|
||||
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
|
||||
result.update({"sd": {"ready": printer.isSdReady()}})
|
||||
|
||||
# add state information
|
||||
if not "state" in excludes:
|
||||
state = printer.getCurrentData()["state"]
|
||||
result.update({"state": state})
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
#~~ Tool
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerToolCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"select": ["tool"],
|
||||
"target": ["targets"],
|
||||
"offset": ["offsets"],
|
||||
"extrude": ["amount"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
validation_regex = re.compile("tool\d+")
|
||||
|
||||
##~~ tool selection
|
||||
if command == "select":
|
||||
tool = data["tool"]
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid tool: %s" % tool, 400)
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
|
||||
printer.changeTool(tool)
|
||||
|
||||
##~~ temperature
|
||||
elif command == "target":
|
||||
targets = data["targets"]
|
||||
|
||||
# make sure the targets are valid and the values are numbers
|
||||
validated_values = {}
|
||||
for tool, value in targets.iteritems():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid target for setting temperature: %s" % tool, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
validated_values[tool] = value
|
||||
|
||||
# perform the actual temperature commands
|
||||
for tool in validated_values.keys():
|
||||
printer.setTemperature(tool, validated_values[tool])
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offsets = data["offsets"]
|
||||
|
||||
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
|
||||
validated_values = {}
|
||||
for tool, value in offsets.iteritems():
|
||||
if re.match(validation_regex, tool) is None:
|
||||
return make_response("Invalid target for setting temperature: %s" % tool, 400)
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for %s: %r" % (tool, value), 400)
|
||||
if not -50 <= value <= 50:
|
||||
return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400)
|
||||
validated_values[tool] = value
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset(validated_values)
|
||||
|
||||
##~~ extrusion
|
||||
elif command == "extrude":
|
||||
if printer.isPrinting():
|
||||
# do not extrude when a print job is running
|
||||
return make_response("Printer is currently printing", 409)
|
||||
|
||||
amount = data["amount"]
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
printer.extrude(amount)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
def printerToolState():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteBed(x):
|
||||
data = dict(x)
|
||||
|
||||
if "bed" in data.keys():
|
||||
del data["bed"]
|
||||
return data
|
||||
|
||||
return jsonify(_getTemperatureData(deleteBed))
|
||||
|
||||
|
||||
##~~ Heated bed
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerBedCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
##~~ temperature
|
||||
if command == "target":
|
||||
target = data["target"]
|
||||
|
||||
# make sure the target is a number
|
||||
if not isinstance(target, (int, long, float)):
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.setTemperature("bed", target)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
offset = data["offset"]
|
||||
|
||||
# make sure the offset is valid
|
||||
if not isinstance(offset, (int, long, float)):
|
||||
return make_response("Not a number: %r" % offset, 400)
|
||||
if not -50 <= offset <= 50:
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset({"bed": offset})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
def printerBedState():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteTools(x):
|
||||
data = dict(x)
|
||||
|
||||
for k in data.keys():
|
||||
if k.startswith("tool"):
|
||||
del data[k]
|
||||
return data
|
||||
|
||||
data = _getTemperatureData(deleteTools)
|
||||
if isinstance(data, Response):
|
||||
return data
|
||||
else:
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
##~~ Print head
|
||||
|
||||
|
||||
@api.route("/printer/printhead", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerPrintheadCommand():
|
||||
if not printer.isOperational() or printer.isPrinting():
|
||||
# do not jog when a print job is running or we don't have a connection
|
||||
return make_response("Printer is not operational or currently printing", 409)
|
||||
|
||||
valid_commands = {
|
||||
"jog": [],
|
||||
"home": ["axes"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
valid_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
# validate all jog instructions, make sure that the values are numbers
|
||||
validated_values = {}
|
||||
for axis in valid_axes:
|
||||
if axis in data:
|
||||
value = data[axis]
|
||||
if not isinstance(value, (int, long, float)):
|
||||
return make_response("Not a number for axis %s: %r" % (axis, value), 400)
|
||||
validated_values[axis] = value
|
||||
|
||||
# execute the jog commands
|
||||
for axis, value in validated_values.iteritems():
|
||||
printer.jog(axis, value)
|
||||
|
||||
##~~ home command
|
||||
elif command == "home":
|
||||
validated_values = []
|
||||
axes = data["axes"]
|
||||
for axis in axes:
|
||||
if not axis in valid_axes:
|
||||
return make_response("Invalid axis: %s" % axis, 400)
|
||||
validated_values.append(axis)
|
||||
|
||||
# execute the home command
|
||||
printer.home(validated_values)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
##~~ SD Card
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerSdCommand():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
if not printer.isOperational() or printer.isPrinting() or printer.isPaused():
|
||||
return make_response("Printer is not operational or currently busy", 409)
|
||||
|
||||
valid_commands = {
|
||||
"init": [],
|
||||
"refresh": [],
|
||||
"release": []
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "init":
|
||||
printer.initSdCard()
|
||||
elif command == "refresh":
|
||||
printer.refreshSdFiles()
|
||||
elif command == "release":
|
||||
printer.releaseSdCard()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/sd", methods=["GET"])
|
||||
def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
return jsonify(ready=printer.isSdReady())
|
||||
|
||||
|
||||
##~~ Commands
|
||||
|
||||
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerCommand():
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
|
||||
parameters = dict()
|
||||
if "parameters" in data.keys(): parameters = data["parameters"]
|
||||
|
||||
if "command" in data and "commands" in data:
|
||||
return make_response("'command' and 'commands' are mutually exclusive", 400)
|
||||
elif "command" in data:
|
||||
commands = [data["command"]]
|
||||
elif "commands" in data and isinstance(data["commands"], (list, tuple)):
|
||||
commands = data["commands"]
|
||||
else:
|
||||
return make_response("Need either single 'command' or list of 'commands'", 400)
|
||||
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
customControls = settings().get(["controls"])
|
||||
return jsonify(controls=customControls)
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
if not printer.isOperational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
tempData = printer.getCurrentTemperatures()
|
||||
|
||||
if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
|
||||
tempHistory = printer.getTemperatureHistory()
|
||||
|
||||
limit = 300
|
||||
if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric():
|
||||
limit = int(request.values["limit"])
|
||||
|
||||
history = list(tempHistory)
|
||||
limit = min(limit, len(history))
|
||||
|
||||
tempData.update({
|
||||
"history": map(lambda x: filter(x), history[-limit:])
|
||||
})
|
||||
|
||||
return filter(tempData)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import copy
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
from octoprint.server import printerProfileManager
|
||||
|
||||
|
||||
@api.route("/printerprofiles", methods=["GET"])
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerProfilesAdd():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = request.json
|
||||
if not "profile" in json_data:
|
||||
return None, None, make_response("No profile included in request", 400)
|
||||
|
||||
base_profile = printerProfileManager.get_default()
|
||||
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
|
||||
other_profile = printerProfileManager.get(json_data["basedOn"])
|
||||
if other_profile is not None:
|
||||
base_profile = other_profile
|
||||
|
||||
if "id" in base_profile:
|
||||
del base_profile["id"]
|
||||
if "name" in base_profile:
|
||||
del base_profile["name"]
|
||||
profile = dict_merge(base_profile, json_data["profile"])
|
||||
if not _validate_profile(profile):
|
||||
return None, None, make_response("Profile is invalid, missing obligatory values", 400)
|
||||
|
||||
return _overwrite_profile(profile)
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
make_response("Unknown profile: %s" % identifier, 404)
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def printerProfilesDelete(identifier):
|
||||
printerProfileManager.remove(identifier)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def printerProfilesUpdate(identifier):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = request.json
|
||||
if not "profile" in json_data:
|
||||
make_response("No profile included in request", 400)
|
||||
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
profile = printerProfileManager.get_default()
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
new_profile = dict_merge(profile, new_profile)
|
||||
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
new_profile["id"] = identifier
|
||||
if not _validate_profile(new_profile):
|
||||
make_response("Combined profile is invalid, missing obligatory values", 400)
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
|
||||
except Exception as e:
|
||||
make_response("Could not save profile: %s" % e.message)
|
||||
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
def _convert_profiles(profiles):
|
||||
result = dict()
|
||||
for identifier, profile in profiles.items():
|
||||
result[identifier] = _convert_profile(profile)
|
||||
return result
|
||||
|
||||
def _convert_profile(profile):
|
||||
default = printerProfileManager.get_default()["id"]
|
||||
current = printerProfileManager.get_current_or_default()["id"]
|
||||
|
||||
converted = copy.deepcopy(profile)
|
||||
converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True)
|
||||
converted["default"] = (profile["id"] == default)
|
||||
converted["current"] = (profile["id"] == current)
|
||||
return converted
|
||||
|
||||
def _validate_profile(profile):
|
||||
if not "name" in profile \
|
||||
and "volume" in profile \
|
||||
and "width" in profile["volume"] \
|
||||
and "depth" in profile["volume"] \
|
||||
and "height" in profile["volume"] \
|
||||
and "formFactor" in profile["volume"] \
|
||||
and "heatedBed" in profile \
|
||||
and "extruder" in profile \
|
||||
and "count" in profile["extruder"] \
|
||||
and "offsets" in profile["extruder"] \
|
||||
and len(profile["extruder"]["offsets"]) == profile["extruder"]["count"]:
|
||||
return False
|
||||
|
||||
for dimension in ("width", "depth", "height"):
|
||||
try:
|
||||
profile["volume"][dimension] = float(profile["volume"][dimension])
|
||||
except:
|
||||
return False
|
||||
|
||||
if not profile["volume"]["formFactor"] in ("rectangular", "circular"):
|
||||
return False
|
||||
|
||||
try:
|
||||
profile["heatedBed"] = bool(profile["heatedBed"])
|
||||
except:
|
||||
return False
|
||||
|
||||
try:
|
||||
profile["extruder"]["count"] = int(profile["extruder"]["count"])
|
||||
except:
|
||||
return False
|
||||
|
||||
converted_offsets = []
|
||||
for offset in profile["extruder"]["offsets"]:
|
||||
try:
|
||||
converted_offsets.append((float(offset[0]), float(offset[1])))
|
||||
except:
|
||||
return False
|
||||
profile["extruder"]["offsets"] = converted_offsets
|
||||
|
||||
return True
|
||||
|
||||
def _overwrite_profile(profile):
|
||||
if not "id" in profile and not "name" in profile:
|
||||
return None, None, make_response("Profile must contain either id or name")
|
||||
elif not "name" in profile:
|
||||
return None, None, make_response("Profile must contain a name")
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(profile, allow_overwrite=False)
|
||||
except Exception as e:
|
||||
return None, None, make_response("Could not save profile: %s" % e.message)
|
||||
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
@@ -1,45 +1,46 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
|
||||
from octoprint.server import restricted_access, admin_permission
|
||||
from octoprint.server.ajax import ajax
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
|
||||
#~~ settings
|
||||
|
||||
|
||||
@ajax.route("/settings", methods=["GET"])
|
||||
@api.route("/settings", methods=["GET"])
|
||||
def getSettings():
|
||||
s = settings()
|
||||
|
||||
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
|
||||
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||
|
||||
connectionOptions = getConnectionOptions()
|
||||
|
||||
return jsonify({
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"])
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
"appearance": {
|
||||
"name": s.get(["appearance", "name"]),
|
||||
"color": s.get(["appearance", "color"])
|
||||
},
|
||||
"printer": {
|
||||
"movementSpeedX": movementSpeedX,
|
||||
"movementSpeedY": movementSpeedY,
|
||||
"movementSpeedZ": movementSpeedZ,
|
||||
"movementSpeedE": movementSpeedE,
|
||||
"invertAxes": s.get(["printerParameters", "invertAxes"])
|
||||
"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
|
||||
},
|
||||
"webcam": {
|
||||
"streamUrl": s.get(["webcam", "stream"]),
|
||||
@@ -51,12 +52,14 @@ def getSettings():
|
||||
"flipV": s.getBoolean(["webcam", "flipV"])
|
||||
},
|
||||
"feature": {
|
||||
"gcodeViewer": s.getBoolean(["feature", "gCodeVisualizer"]),
|
||||
"gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]),
|
||||
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
|
||||
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
|
||||
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
|
||||
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"])
|
||||
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -67,13 +70,16 @@ def getSettings():
|
||||
"timeoutConnection": s.getFloat(["serial", "timeout", "connection"]),
|
||||
"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
|
||||
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
|
||||
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
"timelapse": s.getBaseFolder("timelapse"),
|
||||
"timelapseTmp": s.getBaseFolder("timelapse_tmp"),
|
||||
"logs": s.getBaseFolder("logs")
|
||||
"logs": s.getBaseFolder("logs"),
|
||||
"watched": s.getBaseFolder("watched")
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": s.get(["temperature", "profiles"])
|
||||
@@ -88,10 +94,24 @@ def getSettings():
|
||||
"path": s.get(["cura", "path"]),
|
||||
"config": s.get(["cura", "config"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
def process_plugin_result(name, plugin, result):
|
||||
if result:
|
||||
if not "plugins" in data:
|
||||
data["plugins"] = dict()
|
||||
if "__enabled" in result:
|
||||
del result["__enabled"]
|
||||
data["plugins"][name] = result
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.SettingsPlugin,
|
||||
"on_settings_load",
|
||||
callback=process_plugin_result)
|
||||
|
||||
return jsonify(data)
|
||||
|
||||
|
||||
@ajax.route("/settings", methods=["POST"])
|
||||
@api.route("/settings", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def setSettings():
|
||||
@@ -100,19 +120,16 @@ def setSettings():
|
||||
s = settings()
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.set(["api", "enabled"], data["api"]["enabled"])
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
if "appearance" in data.keys():
|
||||
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
|
||||
if "printer" in data.keys():
|
||||
if "movementSpeedX" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"])
|
||||
if "movementSpeedY" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"])
|
||||
if "movementSpeedZ" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"])
|
||||
if "movementSpeedE" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"])
|
||||
if "invertAxes" in data["printer"].keys(): s.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"])
|
||||
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
@@ -124,12 +141,14 @@ def setSettings():
|
||||
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||
|
||||
if "feature" in data.keys():
|
||||
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["feature", "gCodeVisualizer"], data["feature"]["gcodeViewer"])
|
||||
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
|
||||
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
|
||||
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
|
||||
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
|
||||
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
|
||||
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
|
||||
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
|
||||
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -138,23 +157,26 @@ def setSettings():
|
||||
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
|
||||
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
|
||||
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||
# disable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
||||
logging.getLogger("TRANSPORT").debug("Disabling transport logging")
|
||||
logging.getLogger("TRANSPORT").setLevel(logging.CRITICAL)
|
||||
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
logging.getLogger("TRANSPORT").setLevel(logging.DEBUG)
|
||||
logging.getLogger("TRANSPORT").debug("Enabling transport logging")
|
||||
|
||||
if "folder" in data.keys():
|
||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
@@ -180,7 +202,14 @@ def setSettings():
|
||||
enabled = cura.get("enabled")
|
||||
s.setBoolean(["cura", "enabled"], enabled)
|
||||
|
||||
s.save()
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
|
||||
|
||||
if s.save():
|
||||
eventManager().fire(Events.SETTINGS_UPDATED)
|
||||
|
||||
return getSettings()
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
|
||||
@api.route("/slicing", methods=["GET"])
|
||||
def slicingListAll():
|
||||
default_slicer = s().get(["slicing", "defaultSlicer"])
|
||||
|
||||
result = dict()
|
||||
for slicer in slicingManager.registered_slicers:
|
||||
result[slicer] = dict(
|
||||
key=slicer,
|
||||
displayName=slicingManager.get_slicer(slicer).get_slicer_properties()["name"],
|
||||
default=default_slicer == slicer,
|
||||
profiles=_getSlicingProfilesData(slicer)
|
||||
)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
|
||||
def slicingListSlicerProfiles(slicer):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
return jsonify(_getSlicingProfilesData(slicer))
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
result["data"] = profile.data
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
|
||||
@restricted_access
|
||||
def slicingAddSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
json_data = request.json
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
profile = slicingManager.save_profile(slicer, name, data, display_name=display_name, description=description)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
r = make_response(jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def slicingPatchSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
json_data = request.json
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
if "default" in json_data and json_data["default"] in valid_boolean_trues:
|
||||
default_profiles = s().get(["slicing", "defaultProfiles"])
|
||||
if not default_profiles:
|
||||
default_profiles = dict()
|
||||
default_profiles[slicer] = name
|
||||
s().set(["slicing", "defaultProfiles"], default_profiles)
|
||||
s().save(force=True)
|
||||
|
||||
slicingManager.save_profile(slicer, name, profile, overrides=data, display_name=display_name, description=description)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def slicingDelSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
slicingManager.delete_profile(slicer, name)
|
||||
return NO_CONTENT
|
||||
|
||||
def _getSlicingProfilesData(slicer):
|
||||
profiles = slicingManager.all_profiles(slicer)
|
||||
if not profiles:
|
||||
return dict()
|
||||
|
||||
result = dict()
|
||||
for name, profile in profiles.items():
|
||||
result[name] = _getSlicingProfileData(slicer, name, profile)
|
||||
return result
|
||||
|
||||
def _getSlicingProfileData(slicer, name, profile):
|
||||
defaultProfiles = s().get(["slicing", "defaultProfiles"])
|
||||
result = dict(
|
||||
key=name,
|
||||
default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
|
||||
resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)
|
||||
)
|
||||
if profile.display_name is not None:
|
||||
result["displayName"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
result["description"] = profile.description
|
||||
return result
|
||||
@@ -1,6 +1,9 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
|
||||
@@ -11,45 +14,45 @@ import octoprint.timelapse
|
||||
import octoprint.util as util
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import restricted_access, admin_permission
|
||||
from octoprint.server.util import redirectToTornado
|
||||
from octoprint.server.ajax import ajax
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
|
||||
|
||||
#~~ timelapse handling
|
||||
|
||||
|
||||
@ajax.route("/timelapse", methods=["GET"])
|
||||
@api.route("/timelapse", methods=["GET"])
|
||||
def getTimelapseData():
|
||||
timelapse = octoprint.timelapse.current
|
||||
|
||||
type = "off"
|
||||
additionalConfig = {}
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
type = "zchange"
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
type = "timed"
|
||||
additionalConfig = {
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
}
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
for file in files:
|
||||
file["url"] = url_for("index") + "downloads/timelapse/" + file["name"]
|
||||
|
||||
return jsonify({
|
||||
"type": type,
|
||||
"config": additionalConfig,
|
||||
"config": config,
|
||||
"files": files
|
||||
})
|
||||
|
||||
|
||||
@ajax.route("/timelapse/<filename>", methods=["GET"])
|
||||
@api.route("/timelapse/<filename>", methods=["GET"])
|
||||
def downloadTimelapse(filename):
|
||||
return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename)
|
||||
return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename)
|
||||
|
||||
|
||||
@ajax.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@api.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteTimelapse(filename):
|
||||
if util.isAllowedFile(filename, {"mpg"}):
|
||||
@@ -59,15 +62,23 @@ def deleteTimelapse(filename):
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
@ajax.route("/timelapse", methods=["POST"])
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@restricted_access
|
||||
def setTimelapseConfig():
|
||||
if "type" in request.values:
|
||||
config = {
|
||||
"type": request.values["type"],
|
||||
"postRoll": 0,
|
||||
"options": {}
|
||||
}
|
||||
|
||||
|
||||
if "postRoll" in request.values:
|
||||
try:
|
||||
config["postRoll"] = int(request.values["postRoll"])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if "interval" in request.values:
|
||||
interval = 10
|
||||
try:
|
||||
@@ -1,20 +1,24 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, abort, make_response
|
||||
from flask.ext.login import current_user
|
||||
|
||||
import octoprint.users as users
|
||||
|
||||
from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager
|
||||
from octoprint.server.ajax import ajax
|
||||
from octoprint.server import SUCCESS, admin_permission, userManager
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
|
||||
#~~ user settings
|
||||
|
||||
|
||||
@ajax.route("/users", methods=["GET"])
|
||||
@api.route("/users", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getUsers():
|
||||
@@ -24,7 +28,7 @@ def getUsers():
|
||||
return jsonify({"users": userManager.getAllUsers()})
|
||||
|
||||
|
||||
@ajax.route("/users", methods=["POST"])
|
||||
@api.route("/users", methods=["POST"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def addUser():
|
||||
@@ -49,7 +53,7 @@ def addUser():
|
||||
return getUsers()
|
||||
|
||||
|
||||
@ajax.route("/users/<username>", methods=["GET"])
|
||||
@api.route("/users/<username>", methods=["GET"])
|
||||
@restricted_access
|
||||
def getUser(username):
|
||||
if userManager is None:
|
||||
@@ -65,7 +69,7 @@ def getUser(username):
|
||||
abort(403)
|
||||
|
||||
|
||||
@ajax.route("/users/<username>", methods=["PUT"])
|
||||
@api.route("/users/<username>", methods=["PUT"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def updateUser(username):
|
||||
@@ -91,7 +95,7 @@ def updateUser(username):
|
||||
abort(404)
|
||||
|
||||
|
||||
@ajax.route("/users/<username>", methods=["DELETE"])
|
||||
@api.route("/users/<username>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
@admin_permission.require(http_exception=403)
|
||||
def removeUser(username):
|
||||
@@ -105,7 +109,7 @@ def removeUser(username):
|
||||
abort(404)
|
||||
|
||||
|
||||
@ajax.route("/users/<username>/password", methods=["PUT"])
|
||||
@api.route("/users/<username>/password", methods=["PUT"])
|
||||
@restricted_access
|
||||
def changePasswordForUser(username):
|
||||
if userManager is None:
|
||||
@@ -124,7 +128,7 @@ def changePasswordForUser(username):
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@ajax.route("/users/<username>/apikey", methods=["DELETE"])
|
||||
@api.route("/users/<username>/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteApikeyForUser(username):
|
||||
if userManager is None:
|
||||
@@ -140,7 +144,7 @@ def deleteApikeyForUser(username):
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
|
||||
@ajax.route("/users/<username>/apikey", methods=["POST"])
|
||||
@api.route("/users/<username>/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
def generateApikeyForUser(username):
|
||||
if userManager is None:
|
||||
@@ -0,0 +1,120 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import rsa
|
||||
from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
return jsonify(unverifiedKey=unverified_key, validUntil=valid_until)
|
||||
|
||||
@apps.route("/auth", methods=["POST"])
|
||||
def verifySessionKey():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
for key in ("appid", "key", "_sig"):
|
||||
if not key in data:
|
||||
return make_response("Missing argument: {key}".format(key=key), 400)
|
||||
|
||||
appid = str(data["appid"])
|
||||
if not "appversion" in data:
|
||||
appversion = "any"
|
||||
else:
|
||||
appversion = str(data["appversion"])
|
||||
key = str(data["key"])
|
||||
|
||||
# calculate message that was signed
|
||||
message = "{appid}:{appversion}:{key}".format(**locals())
|
||||
|
||||
# decode signature
|
||||
import base64
|
||||
signature = data["_sig"]
|
||||
signature = base64.decodestring("\n".join([signature[x:x+64] for x in range(0, len(signature), 64)]))
|
||||
|
||||
# fetch and validate app information
|
||||
lookup_key = appid + ":" + appversion
|
||||
apps = _get_registered_apps()
|
||||
if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401)
|
||||
|
||||
pubkey_string = apps[lookup_key]["pubkey"]
|
||||
pubkey_string = "\n".join([pubkey_string[x:x+64] for x in range(0, len(pubkey_string), 64)])
|
||||
try:
|
||||
pubkey = rsa.PublicKey.load_pkcs1("-----BEGIN RSA PUBLIC KEY-----\n" + pubkey_string + "\n-----END RSA PUBLIC KEY-----\n")
|
||||
except:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid pubkey stored in server", 500)
|
||||
|
||||
# verify signature
|
||||
try:
|
||||
rsa.verify(message, signature, pubkey)
|
||||
except rsa.VerificationError:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid signature", 401)
|
||||
|
||||
# generate new session key and return it
|
||||
result = octoprint.server.appSessionManager.verify(key)
|
||||
if not result:
|
||||
return make_response("Invalid key or already verified", 401)
|
||||
|
||||
verified_key, valid_until = result
|
||||
return jsonify(key=verified_key, validUntil=valid_until)
|
||||
|
||||
__registered_apps = None
|
||||
def _get_registered_apps():
|
||||
global __registered_apps
|
||||
|
||||
if __registered_apps is not None:
|
||||
return __registered_apps
|
||||
|
||||
apps = s().get(["api", "apps"], merged=True)
|
||||
for app, app_data in apps.items():
|
||||
if not "enabled" in app_data:
|
||||
apps[app]["enabled"] = True
|
||||
|
||||
app_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.AppPlugin)
|
||||
for name, plugin in app_plugins.items():
|
||||
additional_apps = plugin.get_additional_apps()
|
||||
any_version_enabled = dict()
|
||||
|
||||
for app_data in additional_apps:
|
||||
id, version, pubkey = app_data
|
||||
key = id + ":" + version
|
||||
if key in apps:
|
||||
continue
|
||||
|
||||
if not id in any_version_enabled:
|
||||
any_version_enabled[id] = False
|
||||
|
||||
if version == "any":
|
||||
any_version_enabled[id] = True
|
||||
|
||||
apps[key] = dict(
|
||||
pubkey=pubkey,
|
||||
enabled=True
|
||||
)
|
||||
|
||||
for id, enabled in any_version_enabled.items():
|
||||
if enabled:
|
||||
continue
|
||||
apps[id + ":any"] = dict(
|
||||
pubkey=None,
|
||||
enabled=False
|
||||
)
|
||||
|
||||
__registered_apps = apps
|
||||
return apps
|
||||
@@ -1,334 +0,0 @@
|
||||
from flask.ext.principal import identity_changed, Identity
|
||||
from tornado.web import StaticFileHandler, HTTPError
|
||||
from flask import url_for, make_response, request, current_app
|
||||
from flask.ext.login import login_required, login_user
|
||||
from werkzeug.utils import redirect
|
||||
from sockjs.tornado import SockJSConnection
|
||||
|
||||
import datetime
|
||||
import stat
|
||||
import mimetypes
|
||||
import email
|
||||
import time
|
||||
import os
|
||||
import threading
|
||||
import logging
|
||||
from functools import wraps
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
|
||||
def restricted_access(func, apiEnabled=True):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control plus that any conditions of the
|
||||
login_required decorator are met. It also allows to login using the masterkey or any
|
||||
of the user's apikeys if API access is enabled globally and for the decorated view.
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
|
||||
If an API key is provided and it matches a known key, the user will be logged in and
|
||||
the view will be called directly. If the provided key doesn't match any known key,
|
||||
a HTTP 403 status code will be returned by the decorated resource.
|
||||
|
||||
Otherwise the result of calling login_required will be returned.
|
||||
"""
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
return make_response("OctoPrint isn't setup yet", 403)
|
||||
|
||||
# if API is globally enabled, enabled for this request and an api key is provided, try to use that
|
||||
if settings().get(["api", "enabled"]) and apiEnabled and "apikey" in request.values.keys():
|
||||
apikey = request.values["apikey"]
|
||||
user = None
|
||||
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
user = ApiUser()
|
||||
else:
|
||||
# user key might have been used
|
||||
user = octoprint.server.userManager.findUser(apikey=apikey)
|
||||
|
||||
if user is None:
|
||||
make_response("Invalid API key", 403)
|
||||
if login_user(user, remember=False):
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# call regular login_required decorator
|
||||
return login_required(func)(*args, **kwargs)
|
||||
return decorated_view
|
||||
|
||||
|
||||
def api_access(func):
|
||||
@wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not settings().get(["api", "enabled"]):
|
||||
make_response("API disabled", 401)
|
||||
if not "apikey" in request.values.keys():
|
||||
make_response("No API key provided", 401)
|
||||
if request.values["apikey"] != settings().get(["api", "key"]):
|
||||
make_response("Invalid API key", 403)
|
||||
return func(args, kwargs)
|
||||
return decorated_view
|
||||
|
||||
#~~ Printer state
|
||||
|
||||
|
||||
class PrinterStateConnection(SockJSConnection):
|
||||
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||
SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._temperatureBacklog = []
|
||||
self._temperatureBacklogMutex = threading.Lock()
|
||||
self._logBacklog = []
|
||||
self._logBacklogMutex = threading.Lock()
|
||||
self._messageBacklog = []
|
||||
self._messageBacklogMutex = threading.Lock()
|
||||
|
||||
self._printer = printer
|
||||
self._gcodeManager = gcodeManager
|
||||
self._userManager = userManager
|
||||
self._eventManager = eventManager
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def on_open(self, info):
|
||||
self._logger.info("New connection from client: %s" % self._getRemoteAddress(info))
|
||||
self._printer.registerCallback(self)
|
||||
self._gcodeManager.registerCallback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
|
||||
self._eventManager.fire("ClientOpened")
|
||||
self._eventManager.subscribe("MovieDone", self._onMovieDone)
|
||||
self._eventManager.subscribe("SlicingStarted", self._onSlicingStarted)
|
||||
self._eventManager.subscribe("SlicingDone", self._onSlicingDone)
|
||||
self._eventManager.subscribe("SlicingFailed", self._onSlicingFailed)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
|
||||
def on_close(self):
|
||||
self._logger.info("Closed client connection")
|
||||
self._printer.unregisterCallback(self)
|
||||
self._gcodeManager.unregisterCallback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
|
||||
self._eventManager.fire("ClientClosed")
|
||||
self._eventManager.unsubscribe("MovieDone", self._onMovieDone)
|
||||
self._eventManager.unsubscribe("SlicingStarted", self._onSlicingStarted)
|
||||
self._eventManager.unsubscribe("SlicingDone", self._onSlicingDone)
|
||||
self._eventManager.unsubscribe("SlicingFailed", self._onSlicingFailed)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
|
||||
def sendCurrentData(self, data):
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
self._temperatureBacklog = []
|
||||
|
||||
with self._logBacklogMutex:
|
||||
logs = self._logBacklog
|
||||
self._logBacklog = []
|
||||
|
||||
with self._messageBacklogMutex:
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
data.update({
|
||||
"temperatures": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages
|
||||
})
|
||||
self._emit("current", data)
|
||||
|
||||
def sendHistoryData(self, data):
|
||||
self._emit("history", data)
|
||||
|
||||
def sendUpdateTrigger(self, type, payload=None):
|
||||
self._emit("updateTrigger", {"type": type, "payload": payload})
|
||||
|
||||
def sendFeedbackCommandOutput(self, name, output):
|
||||
self._emit("feedbackCommandOutput", {"name": name, "output": output})
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", timelapseConfig)
|
||||
|
||||
def addLog(self, data):
|
||||
with self._logBacklogMutex:
|
||||
self._logBacklog.append(data)
|
||||
|
||||
def addMessage(self, data):
|
||||
with self._messageBacklogMutex:
|
||||
self._messageBacklog.append(data)
|
||||
|
||||
def addTemperature(self, data):
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
def _onMovieDone(self, event, payload):
|
||||
self.sendUpdateTrigger("timelapseFiles")
|
||||
|
||||
def _onSlicingStarted(self, event, payload):
|
||||
self.sendUpdateTrigger("slicingStarted", payload)
|
||||
|
||||
def _onSlicingDone(self, event, payload):
|
||||
self.sendUpdateTrigger("slicingDone", payload)
|
||||
|
||||
def _onSlicingFailed(self, event, payload):
|
||||
self.sendUpdateTrigger("slicingFailed", payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
self.send({type: payload})
|
||||
|
||||
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(StaticFileHandler):
|
||||
|
||||
CHUNK_SIZE = 16 * 1024
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False):
|
||||
StaticFileHandler.initialize(self, path, default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
path = self.parse_url_path(path)
|
||||
abspath = os.path.abspath(os.path.join(self.root, path))
|
||||
# os.path.abspath strips a trailing /
|
||||
# it needs to be temporarily added back for requests to root/
|
||||
if not (abspath + os.path.sep).startswith(self.root):
|
||||
raise HTTPError(403, "%s is not in root static directory", path)
|
||||
if os.path.isdir(abspath) and self.default_filename is not None:
|
||||
# need to look at the request.path here for when path is empty
|
||||
# but there is some prefix to the path that was already
|
||||
# trimmed by the routing
|
||||
if not self.request.path.endswith("/"):
|
||||
self.redirect(self.request.path + "/")
|
||||
return
|
||||
abspath = os.path.join(abspath, self.default_filename)
|
||||
if not os.path.exists(abspath):
|
||||
raise HTTPError(404)
|
||||
if not os.path.isfile(abspath):
|
||||
raise HTTPError(403, "%s is not a file", path)
|
||||
|
||||
stat_result = os.stat(abspath)
|
||||
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
|
||||
|
||||
self.set_header("Last-Modified", modified)
|
||||
|
||||
mime_type, encoding = mimetypes.guess_type(abspath)
|
||||
if mime_type:
|
||||
self.set_header("Content-Type", mime_type)
|
||||
|
||||
cache_time = self.get_cache_time(path, modified, mime_type)
|
||||
|
||||
if cache_time > 0:
|
||||
self.set_header("Expires", datetime.datetime.utcnow() +
|
||||
datetime.timedelta(seconds=cache_time))
|
||||
self.set_header("Cache-Control", "max-age=" + str(cache_time))
|
||||
|
||||
self.set_extra_headers(path)
|
||||
|
||||
# Check the If-Modified-Since, and don't send the result if the
|
||||
# content has not been modified
|
||||
ims_value = self.request.headers.get("If-Modified-Since")
|
||||
if ims_value is not None:
|
||||
date_tuple = email.utils.parsedate(ims_value)
|
||||
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
|
||||
if if_since >= modified:
|
||||
self.set_status(304)
|
||||
return
|
||||
|
||||
if not include_body:
|
||||
assert self.request.method == "HEAD"
|
||||
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
|
||||
else:
|
||||
with open(abspath, "rb") as file:
|
||||
while True:
|
||||
data = file.read(LargeResponseHandler.CHUNK_SIZE)
|
||||
if not data:
|
||||
break
|
||||
self.write(data)
|
||||
self.flush()
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
|
||||
#~~ reverse proxy compatible wsgi middleware
|
||||
|
||||
|
||||
class ReverseProxied(object):
|
||||
"""
|
||||
Wrap the application in this middleware and configure the
|
||||
front-end server to add these headers, to let you quietly bind
|
||||
this to a URL other than / and to an HTTP scheme that is
|
||||
different than what is used locally.
|
||||
|
||||
In nginx:
|
||||
location /myprefix {
|
||||
proxy_pass http://192.168.0.1:5001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Scheme $scheme;
|
||||
proxy_set_header X-Script-Name /myprefix;
|
||||
}
|
||||
|
||||
Alternatively define prefix and scheme via config.yaml:
|
||||
server:
|
||||
baseUrl: /myprefix
|
||||
scheme: http
|
||||
|
||||
:param app: the WSGI application
|
||||
"""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
|
||||
if not script_name:
|
||||
script_name = settings().get(["server", "baseUrl"])
|
||||
|
||||
if script_name:
|
||||
environ['SCRIPT_NAME'] = script_name
|
||||
path_info = environ['PATH_INFO']
|
||||
if path_info.startswith(script_name):
|
||||
environ['PATH_INFO'] = path_info[len(script_name):]
|
||||
|
||||
scheme = environ.get('HTTP_X_SCHEME', '')
|
||||
if not scheme:
|
||||
scheme = settings().get(["server", "scheme"])
|
||||
|
||||
if scheme:
|
||||
environ['wsgi.url_scheme'] = scheme
|
||||
return self.app(environ, start_response)
|
||||
|
||||
|
||||
def redirectToTornado(request, target):
|
||||
requestUrl = request.url
|
||||
appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "/ajax")]
|
||||
|
||||
redirectUrl = appBaseUrl + target
|
||||
if "?" in requestUrl:
|
||||
fragment = requestUrl[requestUrl.rfind("?"):]
|
||||
redirectUrl += fragment
|
||||
return redirect(redirectUrl)
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
|
||||
import flask as _flask
|
||||
|
||||
from . import flask
|
||||
from . import sockjs
|
||||
from . import tornado
|
||||
from . import watchdog
|
||||
|
||||
|
||||
def apiKeyRequestHandler():
|
||||
"""
|
||||
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
|
||||
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
|
||||
case it has to be present and must be valid, so anything other than the above three types will result in denying
|
||||
the request.
|
||||
"""
|
||||
|
||||
import octoprint.server
|
||||
|
||||
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
|
||||
return optionsAllowOrigin(_flask.request)
|
||||
|
||||
apikey = get_api_key(_flask.request)
|
||||
if apikey is None:
|
||||
# no api key => 401
|
||||
return _flask.make_response("No API key provided", 401)
|
||||
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
# ui api key => continue regular request processing
|
||||
return
|
||||
|
||||
if not settings().get(["api", "enabled"]):
|
||||
# api disabled => 401
|
||||
return _flask.make_response("API disabled", 401)
|
||||
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# global api key => continue regular request processing
|
||||
return
|
||||
|
||||
if octoprint.server.appSessionManager.validate(apikey):
|
||||
# app session key => continue regular request processing
|
||||
return
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is not None:
|
||||
# user specific api key => continue regular request processing
|
||||
return
|
||||
|
||||
# invalid api key => 401
|
||||
return _flask.make_response("Invalid API key", 401)
|
||||
|
||||
|
||||
def corsResponseHandler(resp):
|
||||
|
||||
# Allow crossdomain
|
||||
allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin:
|
||||
resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin']
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
""" Always reply 200 on OPTIONS request """
|
||||
|
||||
resp = _flask.current_app.make_default_options_response()
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
# Allow the actual method
|
||||
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
|
||||
# Allow for 10 seconds
|
||||
resp.headers['Access-Control-Max-Age'] = "10"
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
|
||||
if customRequestHeaders is not None:
|
||||
# If present => allow them all
|
||||
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def get_user_for_apikey(apikey):
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
# master key or an app session key was used
|
||||
return ApiUser()
|
||||
elif octoprint.server.userManager is not None:
|
||||
# user key might have been used
|
||||
return octoprint.server.userManager.findUser(apikey=apikey)
|
||||
return None
|
||||
|
||||
|
||||
def get_api_key(request):
|
||||
# Check Flask GET/POST arguments
|
||||
if hasattr(request, "values") and "apikey" in request.values:
|
||||
return request.values["apikey"]
|
||||
|
||||
# Check Tornado GET/POST arguments
|
||||
if hasattr(request, "arguments") and "apikey" in request.arguments \
|
||||
and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0:
|
||||
return request.arguments["apikey"]
|
||||
|
||||
# Check Tornado and Flask headers
|
||||
if "X-Api-Key" in request.headers.keys():
|
||||
return request.headers.get("X-Api-Key")
|
||||
|
||||
return None
|
||||
|
||||
|
||||
#~~ reverse proxy compatible WSGI middleware
|
||||
|
||||
|
||||
class ReverseProxied(object):
|
||||
"""
|
||||
Wrap the application in this middleware and configure the
|
||||
front-end server to add these headers, to let you quietly bind
|
||||
this to a URL other than / and to an HTTP scheme that is
|
||||
different than what is used locally.
|
||||
|
||||
In nginx:
|
||||
location /myprefix {
|
||||
proxy_pass http://192.168.0.1:5001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Scheme $scheme;
|
||||
proxy_set_header X-Script-Name /myprefix;
|
||||
}
|
||||
|
||||
Alternatively define prefix and scheme via config.yaml:
|
||||
server:
|
||||
baseUrl: /myprefix
|
||||
scheme: http
|
||||
|
||||
:param app: the WSGI application
|
||||
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
|
||||
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
|
||||
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
|
||||
:param base_url: the prefix to use as fallback if headers are not set
|
||||
:param scheme: the scheme to use as fallback if headers are not set
|
||||
:param host: the host to use as fallback if headers are not set
|
||||
"""
|
||||
|
||||
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
|
||||
self.app = app
|
||||
|
||||
# headers for prefix & scheme & host, converted to conform to WSGI format
|
||||
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
|
||||
self._header_prefix = to_wsgi_format(header_prefix)
|
||||
self._header_scheme = to_wsgi_format(header_scheme)
|
||||
self._header_host = to_wsgi_format(header_host)
|
||||
|
||||
# fallback prefix & scheme & host from config
|
||||
self._fallback_prefix = base_url
|
||||
self._fallback_scheme = scheme
|
||||
self._fallback_host = host
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
# determine prefix
|
||||
prefix = environ.get(self._header_prefix, "")
|
||||
if not prefix:
|
||||
prefix = self._fallback_prefix
|
||||
|
||||
# rewrite SCRIPT_NAME and if necessary also PATH_INFO based on prefix
|
||||
if prefix:
|
||||
environ["SCRIPT_NAME"] = prefix
|
||||
path_info = environ["PATH_INFO"]
|
||||
if path_info.startswith(prefix):
|
||||
environ["PATH_INFO"] = path_info[len(prefix):]
|
||||
|
||||
# determine scheme
|
||||
scheme = environ.get(self._header_scheme, "")
|
||||
if not scheme:
|
||||
scheme = self._fallback_scheme
|
||||
|
||||
# rewrite wsgi.url_scheme based on scheme
|
||||
if scheme:
|
||||
environ["wsgi.url_scheme"] = scheme
|
||||
|
||||
# determine host
|
||||
host = environ.get(self._header_host, "")
|
||||
if not host:
|
||||
host = self._fallback_host
|
||||
|
||||
# rewrite host header based on host
|
||||
if host:
|
||||
environ["HTTP_HOST"] = host
|
||||
|
||||
# call wrapped app with rewritten environment
|
||||
return self.app(environ, start_response)
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import tornado.web
|
||||
import flask
|
||||
import flask.ext.login
|
||||
import flask.ext.principal
|
||||
import functools
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.server
|
||||
import octoprint.users
|
||||
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
|
||||
def admin_validator(request):
|
||||
"""
|
||||
Validates that the given request is made by an admin user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated() or not user.is_admin():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
|
||||
def user_validator(request):
|
||||
"""
|
||||
Validates that the given request is made by an authenticated user, identified either by API key or existing Flask
|
||||
session.
|
||||
|
||||
Must be executed in an existing Flask request context!
|
||||
|
||||
:param request: The Flask request object
|
||||
"""
|
||||
|
||||
user = _get_flask_user_from_request(request)
|
||||
if user is None or not user.is_authenticated():
|
||||
raise tornado.web.HTTPError(403)
|
||||
|
||||
|
||||
def _get_flask_user_from_request(request):
|
||||
"""
|
||||
Retrieves the current flask user from the request context. Uses API key if available, otherwise the current
|
||||
user session if available.
|
||||
|
||||
:param request: flask request from which to retrieve the current user
|
||||
:return: the user or None if no user could be determined
|
||||
"""
|
||||
import octoprint.server.util
|
||||
import flask.ext.login
|
||||
from octoprint.settings import settings
|
||||
|
||||
apikey = octoprint.server.util.get_api_key(request)
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||
else:
|
||||
user = flask.ext.login.current_user
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def redirect_to_tornado(request, target, code=302):
|
||||
"""
|
||||
Redirects from flask to tornado, flask request context must exist.
|
||||
|
||||
:param request:
|
||||
:param target:
|
||||
:param code:
|
||||
:return:
|
||||
"""
|
||||
|
||||
import flask
|
||||
|
||||
requestUrl = request.url
|
||||
appBaseUrl = requestUrl[:requestUrl.find(flask.url_for("index") + "api")]
|
||||
|
||||
redirectUrl = appBaseUrl + target
|
||||
if "?" in requestUrl:
|
||||
fragment = requestUrl[requestUrl.rfind("?"):]
|
||||
redirectUrl += fragment
|
||||
return flask.redirect(redirectUrl, code=code)
|
||||
|
||||
|
||||
def restricted_access(func, api_enabled=True):
|
||||
"""
|
||||
If you decorate a view with this, it will ensure that first setup has been
|
||||
done for OctoPrint's Access Control plus that any conditions of the
|
||||
login_required decorator are met. It also allows to login using the masterkey or any
|
||||
of the user's apikeys if API access is enabled globally and for the decorated view.
|
||||
|
||||
If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun"
|
||||
flag from the settings being set to True and the userManager not indicating
|
||||
that it's user database has been customized from default), the decorator
|
||||
will cause a HTTP 403 status code to be returned by the decorated resource.
|
||||
|
||||
If an API key is provided and it matches a known key, the user will be logged in and
|
||||
the view will be called directly. If the provided key doesn't match any known key,
|
||||
a HTTP 403 status code will be returned by the decorated resource.
|
||||
|
||||
Otherwise the result of calling login_required will be returned.
|
||||
"""
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
|
||||
# if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY:
|
||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||
|
||||
if user is None:
|
||||
return flask.make_response("Invalid API key", 401)
|
||||
if flask.ext.login.login_user(user, remember=False):
|
||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||
return func(*args, **kwargs)
|
||||
|
||||
# call regular login_required decorator
|
||||
return flask.ext.login.login_required(func)(*args, **kwargs)
|
||||
return decorated_view
|
||||
|
||||
|
||||
class AppSessionManager(object):
|
||||
|
||||
VALIDITY_UNVERIFIED = 1 * 60 # 1 minute
|
||||
VALIDITY_VERIFIED = 2 * 60 * 60 # 2 hours
|
||||
|
||||
def __init__(self):
|
||||
self._sessions = dict()
|
||||
self._oldest = None
|
||||
self._mutex = threading.RLock()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def create(self):
|
||||
self._clean_sessions()
|
||||
|
||||
key = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
created = time.time()
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
with self._mutex:
|
||||
self._sessions[key] = (created, False, valid_until)
|
||||
return key, valid_until
|
||||
|
||||
def remove(self, key):
|
||||
with self._mutex:
|
||||
if not key in self._sessions:
|
||||
return
|
||||
del self._sessions[key]
|
||||
|
||||
def verify(self, key):
|
||||
self._clean_sessions()
|
||||
|
||||
if not key in self._sessions:
|
||||
return False
|
||||
|
||||
with self._mutex:
|
||||
created, verified, _ = self._sessions[key]
|
||||
if verified:
|
||||
return False
|
||||
|
||||
valid_until = created + self.__class__.VALIDITY_VERIFIED
|
||||
self._sessions[key] = created, True, created + self.__class__.VALIDITY_VERIFIED
|
||||
|
||||
return key, valid_until
|
||||
|
||||
def validate(self, key):
|
||||
self._clean_sessions()
|
||||
return key in self._sessions and self._sessions[key][1]
|
||||
|
||||
def _clean_sessions(self):
|
||||
if self._oldest is not None and self._oldest > time.time():
|
||||
return
|
||||
|
||||
with self._mutex:
|
||||
self._oldest = None
|
||||
for key, value in self._sessions.items():
|
||||
created, verified, valid_until = value
|
||||
if not verified:
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
if valid_until < time.time():
|
||||
del self._sessions[key]
|
||||
elif self._oldest is None or valid_until < self._oldest:
|
||||
self._oldest = valid_until
|
||||
|
||||
self._logger.debug("App sessions after cleanup: %r" % self._sessions)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import sockjs.tornado
|
||||
|
||||
import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.events import Events
|
||||
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._temperatureBacklog = []
|
||||
self._temperatureBacklogMutex = threading.Lock()
|
||||
self._logBacklog = []
|
||||
self._logBacklogMutex = threading.Lock()
|
||||
self._messageBacklog = []
|
||||
self._messageBacklogMutex = threading.Lock()
|
||||
|
||||
self._printer = printer
|
||||
self._fileManager = fileManager
|
||||
self._analysisQueue = analysisQueue
|
||||
self._userManager = userManager
|
||||
self._eventManager = eventManager
|
||||
self._pluginManager = pluginManager
|
||||
|
||||
self._remoteAddress = None
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return info.ip
|
||||
|
||||
def on_open(self, info):
|
||||
self._remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
|
||||
|
||||
self._printer.registerCallback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
self._pluginManager.register_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
|
||||
def on_close(self):
|
||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||
self._printer.unregisterCallback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
self._pluginManager.unregister_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
|
||||
def sendCurrentData(self, data):
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
self._temperatureBacklog = []
|
||||
|
||||
with self._logBacklogMutex:
|
||||
logs = self._logBacklog
|
||||
self._logBacklog = []
|
||||
|
||||
with self._messageBacklogMutex:
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
busy_files = [dict(origin=v[0], name=v[1]) for v in self._fileManager.get_busy_files()]
|
||||
if "job" in data and data["job"] is not None \
|
||||
and "file" in data["job"] and "name" in data["job"]["file"] and "origin" in data["job"]["file"] \
|
||||
and data["job"]["file"]["name"] is not None and data["job"]["file"]["origin"] is not None \
|
||||
and (self._printer.isPrinting() or self._printer.isPaused()):
|
||||
busy_files.append(dict(origin=data["job"]["file"]["origin"], name=data["job"]["file"]["name"]))
|
||||
|
||||
data.update({
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
})
|
||||
self._emit("current", data)
|
||||
|
||||
def sendHistoryData(self, data):
|
||||
self._emit("history", data)
|
||||
|
||||
def sendEvent(self, type, payload=None):
|
||||
self._emit("event", {"type": type, "payload": payload})
|
||||
|
||||
def sendFeedbackCommandOutput(self, name, output):
|
||||
self._emit("feedbackCommandOutput", {"name": name, "output": output})
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", timelapseConfig)
|
||||
|
||||
def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
self._emit("slicingProgress",
|
||||
dict(slicer=slicer, source_location=source_location, source_path=source_path, dest_location=dest_location, dest_path=dest_path, progress=progress)
|
||||
)
|
||||
|
||||
def sendPluginMessage(self, plugin, data):
|
||||
self._emit("plugin", dict(plugin=plugin, data=data))
|
||||
|
||||
def addLog(self, data):
|
||||
with self._logBacklogMutex:
|
||||
self._logBacklog.append(data)
|
||||
|
||||
def addMessage(self, data):
|
||||
with self._messageBacklogMutex:
|
||||
self._messageBacklog.append(data)
|
||||
|
||||
def addTemperature(self, data):
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
def _onEvent(self, event, payload):
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message))
|
||||
@@ -0,0 +1,828 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
import datetime
|
||||
import stat
|
||||
import mimetypes
|
||||
import email
|
||||
import time
|
||||
import re
|
||||
|
||||
import tornado
|
||||
import tornado.web
|
||||
import tornado.gen
|
||||
import tornado.escape
|
||||
import tornado.httputil
|
||||
import tornado.httpserver
|
||||
import tornado.httpclient
|
||||
import tornado.http1connection
|
||||
import tornado.iostream
|
||||
import tornado.tcpserver
|
||||
import tornado.util
|
||||
|
||||
import octoprint.util
|
||||
|
||||
|
||||
#~~ WSGI middleware
|
||||
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
"""
|
||||
A `RequestHandler` similar to `tornado.web.FallbackHandler` which fetches any files contained in the request bodies
|
||||
of content type `multipart`, stores them in temporary files and supplies the `fallback` with the file's `name`,
|
||||
`content_type`, `path` and `size` instead via a rewritten body.
|
||||
|
||||
Basically similar to what the nginx upload module does.
|
||||
|
||||
Basic request body example:
|
||||
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="file"; filename="test.gcode"
|
||||
Content-Type: application/octet-stream
|
||||
|
||||
...
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="apikey"
|
||||
|
||||
my_funny_apikey
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="select"
|
||||
|
||||
true
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C--
|
||||
|
||||
That would get turned into:
|
||||
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="apikey"
|
||||
|
||||
my_funny_apikey
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="select"
|
||||
|
||||
true
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="file.path"
|
||||
|
||||
/tmp/tmpzupkro
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="file.name"
|
||||
|
||||
test.gcode
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="file.content_type"
|
||||
|
||||
application/octet-stream
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C
|
||||
Content-Disposition: form-data; name="file.size"
|
||||
|
||||
349182
|
||||
------WebKitFormBoundarypYiSUx63abAmhT5C--
|
||||
|
||||
The underlying application can then access the contained files via their respective paths and just move them
|
||||
where necessary.
|
||||
"""
|
||||
|
||||
# the request methods that may contain a request body
|
||||
BODY_METHODS = ("POST", "PATCH", "PUT")
|
||||
|
||||
def initialize(self, fallback, file_prefix="tmp", file_suffix="", path=None, suffixes=None):
|
||||
if not suffixes:
|
||||
suffixes = dict()
|
||||
|
||||
self._fallback = fallback
|
||||
self._file_prefix = file_prefix
|
||||
self._file_suffix = file_suffix
|
||||
self._path = path
|
||||
|
||||
self._suffixes = dict((key, key) for key in ("name", "path", "content_type", "size"))
|
||||
for suffix_type, suffix in suffixes.iteritems():
|
||||
if suffix_type in self._suffixes and suffix is not None:
|
||||
self._suffixes[suffix_type] = suffix
|
||||
|
||||
# Parts, files and values will be stored here
|
||||
self._parts = dict()
|
||||
self._files = []
|
||||
|
||||
# Part currently being processed
|
||||
self._current_part = None
|
||||
|
||||
# content type of request body
|
||||
self._content_type = None
|
||||
|
||||
# bytes left to read according to content_length of request body
|
||||
self._bytes_left = 0
|
||||
|
||||
# buffer needed for identifying form data parts
|
||||
self._buffer = b""
|
||||
|
||||
# buffer for new body
|
||||
self._new_body = b""
|
||||
|
||||
# logger
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def prepare(self):
|
||||
"""
|
||||
Prepares the processing of the request. If it's a request that may contain a request body (as defined in
|
||||
`UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a
|
||||
body-less request, just calls the `fallback` with an empty body and finishes the request.
|
||||
"""
|
||||
if self.request.method in UploadStorageFallbackHandler.BODY_METHODS:
|
||||
self._bytes_left = self.request.headers.get("Content-Length", 0)
|
||||
self._content_type = self.request.headers.get("Content-Type", None)
|
||||
|
||||
# request might contain a body
|
||||
if self.is_multipart():
|
||||
if not self._bytes_left:
|
||||
# we don't support requests without a content-length
|
||||
raise tornado.web.HTTPError(400, reason="No Content-Length supplied")
|
||||
|
||||
# extract the multipart boundary
|
||||
fields = self._content_type.split(";")
|
||||
for field in fields:
|
||||
k, sep, v = field.strip().partition("=")
|
||||
if k == "boundary" and v:
|
||||
if v.startswith(b'"') and v.endswith(b'"'):
|
||||
self._multipart_boundary = tornado.escape.utf8(v[1:-1])
|
||||
else:
|
||||
self._multipart_boundary = tornado.escape.utf8(v)
|
||||
break
|
||||
else:
|
||||
self._multipart_boundary = None
|
||||
else:
|
||||
self._fallback(self.request, b"")
|
||||
self._finished = True
|
||||
|
||||
def data_received(self, chunk):
|
||||
"""
|
||||
Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of
|
||||
processing the multipart data structure via `self._process_multipart_data`. If not, just adds the chunk to
|
||||
internal in-memory buffer.
|
||||
|
||||
:param chunk: chunk of data received from Tornado
|
||||
"""
|
||||
|
||||
data = self._buffer + chunk
|
||||
if self.is_multipart():
|
||||
self._process_multipart_data(data)
|
||||
else:
|
||||
self._buffer = data
|
||||
|
||||
def is_multipart(self):
|
||||
"""Checks whether this request is a `multipart` request"""
|
||||
return self._content_type is not None and self._content_type.startswith("multipart")
|
||||
|
||||
def _process_multipart_data(self, data):
|
||||
"""
|
||||
Processes the given data, parsing it for multipart definitions and calling the appropriate methods.
|
||||
|
||||
:param data: the data to process as a string
|
||||
"""
|
||||
|
||||
# check for boundary
|
||||
delimiter = b"--%s" % self._multipart_boundary
|
||||
delimiter_loc = data.find(delimiter)
|
||||
delimiter_len = len(delimiter)
|
||||
end_of_header = None
|
||||
if delimiter_loc != -1:
|
||||
# found the delimiter in the currently available data
|
||||
delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2
|
||||
data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:]
|
||||
end_of_header = self._buffer.find("\r\n\r\n")
|
||||
else:
|
||||
# make sure any boundary (with single or double ==) contained at the end of chunk does not get
|
||||
# truncated by this processing round => save it to the buffer for next round
|
||||
endlen = len(self._multipart_boundary) + 4
|
||||
data, self._buffer = data[0:-endlen], data[-endlen:]
|
||||
|
||||
# stream data to part handler
|
||||
if data and self._current_part:
|
||||
self._on_part_data(self._current_part, data)
|
||||
|
||||
if end_of_header >= 0:
|
||||
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
|
||||
self._buffer = self._buffer[end_of_header + 4:]
|
||||
|
||||
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
|
||||
# we saw the last boundary and are at the end of our request
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
self._current_part = None
|
||||
self._buffer = b""
|
||||
self._on_request_body_finish()
|
||||
|
||||
def _on_part_header(self, header):
|
||||
"""
|
||||
Called for a new multipart header, takes care of parsing the header and calling `self._on_part` with the
|
||||
relevant data, setting the current part in the process.
|
||||
|
||||
:param header: header to parse
|
||||
"""
|
||||
|
||||
# close any open parts
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
self._current_part = None
|
||||
|
||||
header_check = header.find(self._multipart_boundary)
|
||||
if header_check != -1:
|
||||
self._logger.warn("Header still contained multipart boundary, stripping it...")
|
||||
header = header[header_check:]
|
||||
|
||||
# convert to dict
|
||||
header = tornado.httputil.HTTPHeaders.parse(header.decode("utf-8"))
|
||||
disp_header = header.get("Content-Disposition", "")
|
||||
disposition, disp_params = tornado.httputil._parse_header(disp_header)
|
||||
|
||||
if disposition != "form-data":
|
||||
self._logger.warn("Got a multipart header without form-data content disposition, ignoring that one")
|
||||
return
|
||||
if not disp_params.get("name"):
|
||||
self._logger.warn("Got a multipart header without name, ignoring that one")
|
||||
return
|
||||
|
||||
self._current_part = self._on_part_start(disp_params["name"], header.get("Content-Type", None), filename=disp_params["filename"] if "filename" in disp_params else None)
|
||||
|
||||
def _on_part_start(self, name, content_type, filename=None):
|
||||
"""
|
||||
Called for new parts in the multipart stream. If `filename` is given creates new `file` part (which leads
|
||||
to storage of the data as temporary file on disk), if not creates a new `data` part (which stores
|
||||
incoming data in memory).
|
||||
|
||||
Structure of `file` parts:
|
||||
|
||||
* `name`: name of the part
|
||||
* `filename`: filename associated with the part
|
||||
* `path`: path to the temporary file storing the file's data
|
||||
* `content_type`: content type of the part
|
||||
* `file`: file handle for the temporary file (mode "wb", not deleted on close!)
|
||||
|
||||
Structure of `data` parts:
|
||||
|
||||
* `name`: name of the part
|
||||
* `content_type`: content type of the part
|
||||
* `data`: bytes of the part (initialized to "")
|
||||
|
||||
:param name: name of the part
|
||||
:param content_type: content type of the part
|
||||
:param filename: filename associated with the part.
|
||||
:return: dict describing the new part
|
||||
"""
|
||||
if filename is not None:
|
||||
# this is a file
|
||||
import tempfile
|
||||
handle = tempfile.NamedTemporaryFile(mode="wb", prefix=self._file_prefix, suffix=self._file_suffix, dir=self._path, delete=False)
|
||||
return dict(name=tornado.escape.utf8(name),
|
||||
filename=tornado.escape.utf8(filename),
|
||||
path=tornado.escape.utf8(handle.name),
|
||||
content_type=tornado.escape.utf8(content_type),
|
||||
file=handle)
|
||||
|
||||
else:
|
||||
return dict(name=tornado.escape.utf8(name), content_type=content_type, data=b"")
|
||||
|
||||
def _on_part_data(self, part, data):
|
||||
"""
|
||||
Called when new bytes are received for the given `part`, takes care of writing them to their storage.
|
||||
|
||||
:param part: part for which data was received
|
||||
:param data: data chunk which was received
|
||||
"""
|
||||
if "file" in part:
|
||||
part["file"].write(data)
|
||||
else:
|
||||
part["data"] += data
|
||||
|
||||
def _on_part_finish(self, part):
|
||||
"""
|
||||
Called when a part gets closed, takes care of storing the finished part in the internal parts storage and for
|
||||
`file` parts closing the temporary file and storing the part in the internal files storage.
|
||||
|
||||
:param part: part which was closed
|
||||
"""
|
||||
name = part["name"]
|
||||
self._parts[name] = part
|
||||
if "file" in part:
|
||||
self._files.append(part["path"])
|
||||
part["file"].close()
|
||||
del part["file"]
|
||||
|
||||
def _on_request_body_finish(self):
|
||||
"""
|
||||
Called when the request body has been read completely. Takes care of creating the replacement body out of the
|
||||
logged parts, turning `file` parts into new
|
||||
:return:
|
||||
"""
|
||||
|
||||
self._new_body = b""
|
||||
for name, part in self._parts.iteritems():
|
||||
if "filename" in part:
|
||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
||||
for n, p in fields.iteritems():
|
||||
key = name + "." + n
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += p + b"\r\n"
|
||||
elif "data" in part:
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
value = part["data"]
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % name
|
||||
if "content_type" in part and part["content_type"] is not None:
|
||||
self._new_body += b"Content-Type: %s\r\n" % part["content_type"]
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += value + b"\r\n"
|
||||
self._new_body += b"--%s--\r\n" % self._multipart_boundary
|
||||
|
||||
def _handle_method(self, *args, **kwargs):
|
||||
"""
|
||||
Handler for any request method, takes care of defining the new request body if necessary and forwarding
|
||||
the current request and changed body to the `fallback`.
|
||||
"""
|
||||
|
||||
# determine which body to supply
|
||||
body = b""
|
||||
if self.is_multipart():
|
||||
# make sure we really processed all data in the buffer
|
||||
while len(self._buffer):
|
||||
self._process_multipart_data(self._buffer)
|
||||
|
||||
# use rewritten body
|
||||
body = self._new_body
|
||||
|
||||
elif self.request.method in UploadStorageFallbackHandler.BODY_METHODS:
|
||||
# directly use data from buffer
|
||||
body = self._buffer
|
||||
|
||||
# rewrite content length
|
||||
self.request.headers["Content-Length"] = len(body)
|
||||
|
||||
try:
|
||||
# call the configured fallback with request and body to use
|
||||
self._fallback(self.request, body)
|
||||
self._headers_written = True
|
||||
finally:
|
||||
# make sure the temporary files are removed again
|
||||
for f in self._files:
|
||||
octoprint.util.silentRemove(f)
|
||||
|
||||
# make all http methods trigger _handle_method
|
||||
get = _handle_method
|
||||
post = _handle_method
|
||||
put = _handle_method
|
||||
patch = _handle_method
|
||||
delete = _handle_method
|
||||
head = _handle_method
|
||||
options = _handle_method
|
||||
|
||||
|
||||
class WsgiInputContainer(object):
|
||||
"""
|
||||
A WSGI container for use with Tornado that allows supplying the request body to be used for `wsgi.input` in the
|
||||
generated WSGI environment upon call.
|
||||
|
||||
A `RequestHandler` can thus provide the WSGI application with a stream for the request body, or a modified body.
|
||||
|
||||
Example usage:
|
||||
|
||||
wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app)
|
||||
application = tornado.web.Application([
|
||||
(r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app),
|
||||
])
|
||||
|
||||
The implementation logic is basically the same as `tornado.wsgi.WSGIContainer` but the `__call__` and `environ`
|
||||
methods have been adjusted to for an optionally supplied `body` argument which is then used for `wsgi.input`.
|
||||
"""
|
||||
|
||||
def __init__(self, wsgi_application):
|
||||
self.wsgi_application = wsgi_application
|
||||
|
||||
def __call__(self, request, body=None):
|
||||
"""
|
||||
Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado `HTTPServerRequest`.
|
||||
|
||||
:param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from
|
||||
:param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream
|
||||
"""
|
||||
|
||||
data = {}
|
||||
response = []
|
||||
|
||||
def start_response(status, response_headers, exc_info=None):
|
||||
data["status"] = status
|
||||
data["headers"] = response_headers
|
||||
return response.append
|
||||
app_response = self.wsgi_application(
|
||||
WsgiInputContainer.environ(request, body), start_response)
|
||||
try:
|
||||
response.extend(app_response)
|
||||
body = b"".join(response)
|
||||
finally:
|
||||
if hasattr(app_response, "close"):
|
||||
app_response.close()
|
||||
if not data:
|
||||
raise Exception("WSGI app did not call start_response")
|
||||
|
||||
status_code = int(data["status"].split()[0])
|
||||
headers = data["headers"]
|
||||
header_set = set(k.lower() for (k, v) in headers)
|
||||
body = tornado.escape.utf8(body)
|
||||
if status_code != 304:
|
||||
if "content-length" not in header_set:
|
||||
headers.append(("Content-Length", str(len(body))))
|
||||
if "content-type" not in header_set:
|
||||
headers.append(("Content-Type", "text/html; charset=UTF-8"))
|
||||
if "server" not in header_set:
|
||||
headers.append(("Server", "TornadoServer/%s" % tornado.version))
|
||||
|
||||
parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
|
||||
for key, value in headers:
|
||||
parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n")
|
||||
parts.append(b"\r\n")
|
||||
parts.append(body)
|
||||
request.write(b"".join(parts))
|
||||
request.finish()
|
||||
self._log(status_code, request)
|
||||
|
||||
@staticmethod
|
||||
def environ(request, body=None):
|
||||
"""
|
||||
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
|
||||
|
||||
An optional `body` to be used for populating `wsgi.input` can be supplied (either a string or a stream). If not
|
||||
supplied, `request.body` will be wrapped into a `io.BytesIO` stream and used instead.
|
||||
|
||||
:param request: the `tornado.httpserver.HTTPServerRequest` to derive the WSGI environment from
|
||||
:param body: an optional body to use as `wsgi.input` instead of `request.body`, can be a string or a stream
|
||||
"""
|
||||
from tornado.wsgi import to_wsgi_str
|
||||
import sys
|
||||
import io
|
||||
|
||||
# determine the request_body to supply as wsgi.input
|
||||
if body is not None:
|
||||
if isinstance(body, (bytes, str)):
|
||||
request_body = io.BytesIO(tornado.escape.utf8(body))
|
||||
else:
|
||||
request_body = body
|
||||
else:
|
||||
request_body = io.BytesIO(tornado.escape.utf8(request.body))
|
||||
|
||||
hostport = request.host.split(":")
|
||||
if len(hostport) == 2:
|
||||
host = hostport[0]
|
||||
port = int(hostport[1])
|
||||
else:
|
||||
host = request.host
|
||||
port = 443 if request.protocol == "https" else 80
|
||||
environ = {
|
||||
"REQUEST_METHOD": request.method,
|
||||
"SCRIPT_NAME": "",
|
||||
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
|
||||
request.path, encoding=None, plus=False)),
|
||||
"QUERY_STRING": request.query,
|
||||
"REMOTE_ADDR": request.remote_ip,
|
||||
"SERVER_NAME": host,
|
||||
"SERVER_PORT": str(port),
|
||||
"SERVER_PROTOCOL": request.version,
|
||||
"wsgi.version": (1, 0),
|
||||
"wsgi.url_scheme": request.protocol,
|
||||
"wsgi.input": request_body,
|
||||
"wsgi.errors": sys.stderr,
|
||||
"wsgi.multithread": False,
|
||||
"wsgi.multiprocess": True,
|
||||
"wsgi.run_once": False,
|
||||
}
|
||||
if "Content-Type" in request.headers:
|
||||
environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
|
||||
if "Content-Length" in request.headers:
|
||||
environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length")
|
||||
for key, value in request.headers.items():
|
||||
environ["HTTP_" + key.replace("-", "_").upper()] = value
|
||||
return environ
|
||||
|
||||
def _log(self, status_code, request):
|
||||
access_log = logging.getLogger("tornado.access")
|
||||
|
||||
if status_code < 400:
|
||||
log_method = access_log.info
|
||||
elif status_code < 500:
|
||||
log_method = access_log.warning
|
||||
else:
|
||||
log_method = access_log.error
|
||||
request_time = 1000.0 * request.request_time()
|
||||
summary = request.method + " " + request.uri + " (" + \
|
||||
request.remote_ip + ")"
|
||||
log_method("%d %s %.2fms", status_code, summary, request_time)
|
||||
|
||||
|
||||
#~~ customized HTTP1Connection implementation
|
||||
|
||||
|
||||
class CustomHTTPServer(tornado.httpserver.HTTPServer):
|
||||
"""
|
||||
Custom implementation of `tornado.httpserver.HTTPServer` that allows defining max body sizes depending on path and
|
||||
method.
|
||||
|
||||
The implementation is mostly taken from `tornado.httpserver.HTTPServer`, the only difference is the creation
|
||||
of a `CustomHTTP1ConnectionParameters` instance instead of `tornado.http1connection.HTTP1ConnectionParameters`
|
||||
which is supplied with the two new constructor arguments `max_body_sizes` and `max_default_body_size` and the
|
||||
creation of a `CustomHTTP1ServerConnection` instead of a `tornado.http1connection.HTTP1ServerConnection` upon
|
||||
connection by a client.
|
||||
|
||||
`max_body_sizes` is expected to be an iterable containing tuples of the form (method, path regex, maximum body size),
|
||||
with method and path regex having to match in order for maximum body size to take affect.
|
||||
|
||||
`default_max_body_size` is the default maximum body size to apply if no specific one from `max_body_sizes` matches.
|
||||
"""
|
||||
|
||||
def __init__(self, request_callback, no_keep_alive=False, io_loop=None,
|
||||
xheaders=False, ssl_options=None, protocol=None,
|
||||
decompress_request=False,
|
||||
chunk_size=None, max_header_size=None,
|
||||
idle_connection_timeout=None, body_timeout=None,
|
||||
max_body_sizes=None, default_max_body_size=None, max_buffer_size=None):
|
||||
self.request_callback = request_callback
|
||||
self.no_keep_alive = no_keep_alive
|
||||
self.xheaders = xheaders
|
||||
self.protocol = protocol
|
||||
self.conn_params = CustomHTTP1ConnectionParameters(
|
||||
decompress=decompress_request,
|
||||
chunk_size=chunk_size,
|
||||
max_header_size=max_header_size,
|
||||
header_timeout=idle_connection_timeout or 3600,
|
||||
max_body_sizes=max_body_sizes,
|
||||
default_max_body_size=default_max_body_size,
|
||||
body_timeout=body_timeout)
|
||||
tornado.tcpserver.TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
|
||||
max_buffer_size=max_buffer_size,
|
||||
read_chunk_size=chunk_size)
|
||||
self._connections = set()
|
||||
|
||||
|
||||
def handle_stream(self, stream, address):
|
||||
context = tornado.httpserver._HTTPRequestContext(stream, address,
|
||||
self.protocol)
|
||||
conn = CustomHTTP1ServerConnection(
|
||||
stream, self.conn_params, context)
|
||||
self._connections.add(conn)
|
||||
conn.start_serving(self)
|
||||
|
||||
|
||||
class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection):
|
||||
"""
|
||||
A custom implementation of `tornado.http1connection.HTTP1ServerConnection` which utilizes a `CustomHTTP1Connection`
|
||||
instead of a `tornado.http1connection.HTTP1Connection` in `_server_request_loop`. The implementation logic is
|
||||
otherwise the same as `tornado.http1connection.HTTP1ServerConnection`.
|
||||
"""
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def _server_request_loop(self, delegate):
|
||||
try:
|
||||
while True:
|
||||
conn = CustomHTTP1Connection(self.stream, False,
|
||||
self.params, self.context)
|
||||
request_delegate = delegate.start_request(self, conn)
|
||||
try:
|
||||
ret = yield conn.read_response(request_delegate)
|
||||
except (tornado.iostream.StreamClosedError,
|
||||
tornado.iostream.UnsatisfiableReadError):
|
||||
return
|
||||
except tornado.http1connection._QuietException:
|
||||
# This exception was already logged.
|
||||
conn.close()
|
||||
return
|
||||
except Exception:
|
||||
tornado.http1connection.gen_log.error("Uncaught exception", exc_info=True)
|
||||
conn.close()
|
||||
return
|
||||
if not ret:
|
||||
return
|
||||
yield tornado.gen.moment
|
||||
finally:
|
||||
delegate.on_close(self)
|
||||
|
||||
|
||||
class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
|
||||
"""
|
||||
A custom implementation of `tornado.http1connection.HTTP1Connection` which upon checking the `Content-Length` of
|
||||
the request against the configured maximum utilizes `max_body_sizes` and `default_max_body_size` as a fallback.
|
||||
"""
|
||||
|
||||
def __init__(self, stream, is_client, params=None, context=None):
|
||||
tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context)
|
||||
|
||||
import re
|
||||
self._max_body_sizes = map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or dict())
|
||||
self._default_max_body_size = self.params.default_max_body_size or self.stream.max_buffer_size
|
||||
|
||||
def _read_body(self, code, headers, delegate):
|
||||
"""
|
||||
Basically the same as `tornado.http1connection.HTTP1Connection._read_body`, but determines the maximum
|
||||
content length individually for the request (utilizing `._get_max_content_length`).
|
||||
|
||||
If the individual max content length is 0 or smaller no content length is checked. If the content length of the
|
||||
current request exceeds the individual max content length, the request processing is aborted and an
|
||||
`HTTPInputError` is raised.
|
||||
"""
|
||||
content_length = headers.get("Content-Length")
|
||||
if "Content-Length" in headers:
|
||||
if "," in headers["Content-Length"]:
|
||||
# Proxies sometimes cause Content-Length headers to get
|
||||
# duplicated. If all the values are identical then we can
|
||||
# use them but if they differ it's an error.
|
||||
pieces = re.split(r',\s*', headers["Content-Length"])
|
||||
if any(i != pieces[0] for i in pieces):
|
||||
raise tornado.httputil.HTTPInputError(
|
||||
"Multiple unequal Content-Lengths: %r" %
|
||||
headers["Content-Length"])
|
||||
headers["Content-Length"] = pieces[0]
|
||||
content_length = int(headers["Content-Length"])
|
||||
|
||||
content_length = int(content_length)
|
||||
max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path)
|
||||
if 0 <= max_content_length < content_length:
|
||||
raise tornado.httputil.HTTPInputError("Content-Length too long")
|
||||
else:
|
||||
content_length = None
|
||||
|
||||
if code == 204:
|
||||
# This response code is not allowed to have a non-empty body,
|
||||
# and has an implicit length of zero instead of read-until-close.
|
||||
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
|
||||
if ("Transfer-Encoding" in headers or
|
||||
content_length not in (None, 0)):
|
||||
raise tornado.httputil.HTTPInputError(
|
||||
"Response with code %d should not have body" % code)
|
||||
content_length = 0
|
||||
|
||||
if content_length is not None:
|
||||
return self._read_fixed_body(content_length, delegate)
|
||||
if headers.get("Transfer-Encoding") == "chunked":
|
||||
return self._read_chunked_body(delegate)
|
||||
if self.is_client:
|
||||
return self._read_body_until_close(delegate)
|
||||
return None
|
||||
|
||||
def _get_max_content_length(self, method, path):
|
||||
"""
|
||||
Gets the max content length for the given method and path. Checks whether method and path match against any
|
||||
of the specific maximum content lengths supplied in `max_body_sizes` and returns that as the maximum content
|
||||
length if available, otherwise returns `default_max_body_size`.
|
||||
|
||||
:param method: method of the request to match against
|
||||
:param path: path od the request to match against
|
||||
:return: determine maximum content length to apply to this request, max return 0 for unlimited allowed content
|
||||
length
|
||||
"""
|
||||
|
||||
for m, p, s in self._max_body_sizes:
|
||||
if method == m and p.match(path):
|
||||
return s
|
||||
return self._default_max_body_size
|
||||
|
||||
|
||||
class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionParameters):
|
||||
"""
|
||||
An implementation of `tornado.http1connection.HTTP1ConnectionParameters` that adds to new parameters
|
||||
`max_body_sizes` and `default_max_body_size`.
|
||||
|
||||
For a description of these please see the documentation of `CustomHTTPServer` above.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, args, kwargs)
|
||||
self.max_body_sizes = kwargs["max_body_sizes"] if "max_body_sizes" in kwargs else dict()
|
||||
self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else dict()
|
||||
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._access_validation = access_validation
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
if self._access_validation is not None:
|
||||
self._access_validation(self.request)
|
||||
result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
|
||||
return result
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
@classmethod
|
||||
def get_content_version(cls, abspath):
|
||||
import os
|
||||
import stat
|
||||
return os.stat(abspath)[stat.ST_MTIME]
|
||||
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
|
||||
def initialize(self, url=None, as_attachment=False, basename=None, access_validation=None):
|
||||
tornado.web.RequestHandler.initialize(self)
|
||||
self._url = url
|
||||
self._as_attachment = as_attachment
|
||||
self._basename = basename
|
||||
self._access_validation = access_validation
|
||||
|
||||
@tornado.web.asynchronous
|
||||
def get(self, *args, **kwargs):
|
||||
if self._access_validation is not None:
|
||||
self._access_validation(self.request)
|
||||
|
||||
if self._url is None:
|
||||
raise tornado.web.HTTPError(404)
|
||||
|
||||
client = tornado.httpclient.AsyncHTTPClient()
|
||||
r = tornado.httpclient.HTTPRequest(url=self._url, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True)
|
||||
|
||||
try:
|
||||
return client.fetch(r, self.handle_response)
|
||||
except tornado.web.HTTPError as e:
|
||||
if hasattr(e, "response") and e.response:
|
||||
self.handle_response(e.response)
|
||||
else:
|
||||
raise tornado.web.HTTPError(500)
|
||||
|
||||
def handle_response(self, response):
|
||||
if response.error and not isinstance(response.error, tornado.web.HTTPError):
|
||||
raise tornado.web.HTTPError(500)
|
||||
|
||||
filename = None
|
||||
|
||||
self.set_status(response.code)
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
|
||||
value = response.headers.get(name)
|
||||
if value:
|
||||
self.set_header(name, value)
|
||||
|
||||
if name == "Content-Type":
|
||||
filename = self.get_filename(value)
|
||||
|
||||
if self._as_attachment:
|
||||
if filename is not None:
|
||||
self.set_header("Content-Disposition", "attachment; filename=%s" % filename)
|
||||
else:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
if response.body:
|
||||
self.write(response.body)
|
||||
self.finish()
|
||||
|
||||
def get_filename(self, content_type):
|
||||
if not self._basename:
|
||||
return None
|
||||
|
||||
typeValue = map(str.strip, content_type.split(";"))
|
||||
if len(typeValue) == 0:
|
||||
return None
|
||||
|
||||
extension = mimetypes.guess_extension(typeValue[0])
|
||||
if not extension:
|
||||
return None
|
||||
|
||||
return "%s%s" % (self._basename, extension)
|
||||
|
||||
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
def access_validation_factory(app, login_manager, validator):
|
||||
"""
|
||||
Creates an access validation wrapper using the supplied validator.
|
||||
|
||||
:param validator: the access validator to use inside the validation wrapper
|
||||
:return: an access validation wrapper taking a request as parameter and performing the request validation
|
||||
"""
|
||||
def f(request):
|
||||
"""
|
||||
Creates a custom wsgi and Flask request context in order to be able to process user information
|
||||
stored in the current session.
|
||||
|
||||
:param request: The Tornado request for which to create the environment and context
|
||||
"""
|
||||
import flask
|
||||
|
||||
wsgi_environ = WsgiInputContainer.environ(request)
|
||||
with app.request_context(wsgi_environ):
|
||||
app.session_interface.open_session(app, flask.request)
|
||||
login_manager.reload_user()
|
||||
validator(flask.request)
|
||||
return f
|
||||
@@ -0,0 +1,85 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import watchdog.events
|
||||
|
||||
import octoprint.filemanager
|
||||
import octoprint.util
|
||||
|
||||
|
||||
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
"""
|
||||
Takes care of automatically "uploading" files that get added to the watched folder.
|
||||
"""
|
||||
|
||||
patterns = map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())
|
||||
|
||||
def __init__(self, file_manager, printer):
|
||||
watchdog.events.PatternMatchingEventHandler.__init__(self)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._file_manager = file_manager
|
||||
self._printer = printer
|
||||
|
||||
def _upload(self, path):
|
||||
class WatchdogFileWrapper(object):
|
||||
|
||||
def __init__(self, path):
|
||||
import os
|
||||
self._path = path
|
||||
self.filename = os.path.basename(self._path)
|
||||
|
||||
def save(self, target):
|
||||
octoprint.util.safeRename(self._path, target)
|
||||
|
||||
file_wrapper = WatchdogFileWrapper(path)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.getCurrentJob()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
|
||||
return
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.isPrinting() or self._printer.isPaused():
|
||||
return
|
||||
|
||||
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if added_file is None:
|
||||
return
|
||||
|
||||
slicer_name = self._file_manager.default_slicer
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl") and slicer_name:
|
||||
# if it's an STL we now have to slice it before we can continue
|
||||
import os
|
||||
name, ext = os.path.splitext(added_file)
|
||||
gcode_path = name + ".gco"
|
||||
self._file_manager.slice(slicer_name,
|
||||
octoprint.filemanager.FileDestinations.LOCAL,
|
||||
added_file,
|
||||
octoprint.filemanager.FileDestinations.LOCAL,
|
||||
gcode_path)
|
||||
|
||||
def on_created(self, event):
|
||||
self._upload(event.src_path)
|
||||
+336
-56
@@ -23,6 +23,30 @@ def settings(init=False, configfile=None, basedir=None):
|
||||
return instance
|
||||
|
||||
default_settings = {
|
||||
"communication": {
|
||||
"protocol": "reprap",
|
||||
"protocolOptions": {
|
||||
"buffer": 63,
|
||||
"temperature": 5,
|
||||
"sdStatus": 1,
|
||||
"waitForStart": False,
|
||||
"forceChecksum": True,
|
||||
"sdAlwaysAvailable": False
|
||||
},
|
||||
"transport": "serial",
|
||||
"transportOptions": {
|
||||
"port": None,
|
||||
"baudrate": None,
|
||||
"timeout": {
|
||||
"read": 5,
|
||||
"write": 0.5
|
||||
},
|
||||
"additionalPorts": []
|
||||
},
|
||||
"autoconnect": False,
|
||||
"log": False
|
||||
},
|
||||
# TODO Remove, not used by the new communication layer but apparently still by the layers above it!
|
||||
"serial": {
|
||||
"port": None,
|
||||
"baudrate": None,
|
||||
@@ -31,7 +55,9 @@ default_settings = {
|
||||
"timeout": {
|
||||
"detection": 0.5,
|
||||
"connection": 2,
|
||||
"communication": 5
|
||||
"communication": 5,
|
||||
"temperature": 5,
|
||||
"sdStatus": 1
|
||||
},
|
||||
"additionalPorts": []
|
||||
},
|
||||
@@ -39,8 +65,21 @@ default_settings = {
|
||||
"host": "0.0.0.0",
|
||||
"port": 5000,
|
||||
"firstRun": True,
|
||||
"baseUrl": "",
|
||||
"scheme": ""
|
||||
"secretKey": None,
|
||||
"reverseProxy": {
|
||||
"prefixHeader": "X-Script-Name",
|
||||
"schemeHeader": "X-Scheme",
|
||||
"hostHeader": "X-Forwarded-Host",
|
||||
"prefixFallback": "",
|
||||
"schemeFallback": "",
|
||||
"hostFallback": ""
|
||||
},
|
||||
"uploads": {
|
||||
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
|
||||
"nameSuffix": "name",
|
||||
"pathSuffix": "path"
|
||||
},
|
||||
"maxSize": 100 * 1024, # 100 KB
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -52,40 +91,51 @@ default_settings = {
|
||||
"flipV": False,
|
||||
"timelapse": {
|
||||
"type": "off",
|
||||
"options": {}
|
||||
"options": {},
|
||||
"postRoll": 0
|
||||
}
|
||||
},
|
||||
"gcodeViewer": {
|
||||
"enabled": True,
|
||||
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
|
||||
"sizeThreshold": 20 * 1024 * 1024, # 20MB
|
||||
},
|
||||
"gcodeAnalysis": {
|
||||
"maxExtruders": 10
|
||||
},
|
||||
"feature": {
|
||||
"gCodeVisualizer": True,
|
||||
"temperatureGraph": True,
|
||||
"waitForStartOnConnect": False,
|
||||
"alwaysSendChecksum": False,
|
||||
"sdSupport": True,
|
||||
"swallowOkAfterResend": True
|
||||
"waitForStartOnConnect": False, # TODO move to protocol options or reprap protocol
|
||||
"alwaysSendChecksum": True, # TODO move to protocol options
|
||||
"sdSupport": True, # TODO remove (can be always on)
|
||||
"sdAlwaysAvailable": False, # TODO move to protocol options
|
||||
"swallowOkAfterResend": True, # TODO remove (must always be done!)
|
||||
"repetierTargetTemp": False # TODO remove (built into repetier protocol implementation)
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
"timelapse": None,
|
||||
"timelapse_tmp": None,
|
||||
"logs": None,
|
||||
"virtualSd": None
|
||||
"virtualSd": None,
|
||||
"watched": None,
|
||||
"plugins": None,
|
||||
"slicingProfiles": None,
|
||||
"printerProfiles": None
|
||||
},
|
||||
"temperature": {
|
||||
"profiles":
|
||||
[
|
||||
{"name": "ABS", "extruder" : 210, "bed" : 100 },
|
||||
{"name": "PLA", "extruder" : 180, "bed" : 60 }
|
||||
]
|
||||
"profiles": [
|
||||
{"name": "ABS", "extruder" : 210, "bed" : 100 },
|
||||
{"name": "PLA", "extruder" : 180, "bed" : 60 }
|
||||
]
|
||||
},
|
||||
"printerProfiles": {
|
||||
"default": None,
|
||||
"defaultProfile": {}
|
||||
},
|
||||
"printerParameters": {
|
||||
"movementSpeed": {
|
||||
"x": 6000,
|
||||
"y": 6000,
|
||||
"z": 200,
|
||||
"e": 300
|
||||
},
|
||||
"pauseTriggers": [],
|
||||
"invertAxes": []
|
||||
"defaultExtrusionLength": 5
|
||||
},
|
||||
"appearance": {
|
||||
"name": "",
|
||||
@@ -97,6 +147,7 @@ default_settings = {
|
||||
},
|
||||
"accessControl": {
|
||||
"enabled": True,
|
||||
"salt": None,
|
||||
"userManager": "octoprint.users.FilebasedUserManager",
|
||||
"userfile": None,
|
||||
"autologinLocal": False,
|
||||
@@ -108,33 +159,55 @@ default_settings = {
|
||||
"path": "/default/path/to/cura",
|
||||
"config": "/default/path/to/your/cura/config.ini"
|
||||
},
|
||||
"slicing": {
|
||||
"enabled": True,
|
||||
"defaultSlicer": "cura",
|
||||
"defaultProfiles": None
|
||||
},
|
||||
"events": {
|
||||
"systemCommandTrigger": {
|
||||
"enabled": False
|
||||
},
|
||||
"gcodeCommandTrigger": {
|
||||
"enabled": False
|
||||
}
|
||||
"enabled": True,
|
||||
"subscriptions": []
|
||||
},
|
||||
"api": {
|
||||
"enabled": False,
|
||||
"key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
"enabled": True,
|
||||
"key": None,
|
||||
"allowCrossOrigin": False,
|
||||
"apps": {}
|
||||
},
|
||||
"terminalFilters": [
|
||||
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T:)" },
|
||||
{ "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" },
|
||||
{ "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" }
|
||||
],
|
||||
"plugins": {},
|
||||
"devel": {
|
||||
"stylesheet": "css",
|
||||
"virtualPrinter": {
|
||||
"enabled": False,
|
||||
"okAfterResend": False,
|
||||
"forceChecksum": False,
|
||||
"okWithLinenumber": False
|
||||
"okWithLinenumber": False,
|
||||
"numExtruders": 1,
|
||||
"includeCurrentToolInTemps": True,
|
||||
"movementSpeed": {
|
||||
"x": 6000,
|
||||
"y": 6000,
|
||||
"z": 200,
|
||||
"e": 300
|
||||
},
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"smoothieTemperatureReporting": False,
|
||||
"extendedSdFileList": False,
|
||||
"throttle": 0.01,
|
||||
"waitOnLongMoves": False,
|
||||
"rxBuffer": 64,
|
||||
"txBuffer": 40,
|
||||
"commandBuffer": 4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
valid_boolean_trues = ["true", "yes", "y", "1"]
|
||||
valid_boolean_trues = [True, "true", "yes", "y", "1"]
|
||||
|
||||
class Settings(object):
|
||||
|
||||
@@ -145,6 +218,7 @@ class Settings(object):
|
||||
|
||||
self._config = None
|
||||
self._dirty = False
|
||||
self._mtime = None
|
||||
|
||||
self._init_settings_dir(basedir)
|
||||
|
||||
@@ -152,7 +226,11 @@ class Settings(object):
|
||||
self._configfile = configfile
|
||||
else:
|
||||
self._configfile = os.path.join(self.settings_dir, "config.yaml")
|
||||
self.load()
|
||||
self.load(migrate=True)
|
||||
|
||||
if self.get(["api", "key"]) is None:
|
||||
self.set(["api", "key"], ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes))
|
||||
self.save(force=True)
|
||||
|
||||
def _init_settings_dir(self, basedir):
|
||||
if basedir is not None:
|
||||
@@ -160,6 +238,9 @@ class Settings(object):
|
||||
else:
|
||||
self.settings_dir = _resolveSettingsDir(APPNAME)
|
||||
|
||||
if not os.path.isdir(self.settings_dir):
|
||||
os.makedirs(self.settings_dir)
|
||||
|
||||
def _getDefaultFolder(self, type):
|
||||
folder = default_settings["folder"][type]
|
||||
if folder is None:
|
||||
@@ -168,31 +249,220 @@ class Settings(object):
|
||||
|
||||
#~~ load and save
|
||||
|
||||
def load(self):
|
||||
def load(self, migrate=False):
|
||||
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
|
||||
with open(self._configfile, "r") as f:
|
||||
self._config = yaml.safe_load(f)
|
||||
# chamged from else to handle cases where the file exists, but is empty / 0 bytes
|
||||
self._mtime = self._last_modified()
|
||||
# changed from else to handle cases where the file exists, but is empty / 0 bytes
|
||||
if not self._config:
|
||||
self._config = {}
|
||||
|
||||
if migrate:
|
||||
self._migrateConfig()
|
||||
|
||||
def _migrateConfig(self):
|
||||
dirty = False
|
||||
for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters):
|
||||
dirty = migrate() or dirty
|
||||
if dirty:
|
||||
self.save(force=True)
|
||||
|
||||
def _migrate_printer_parameters(self):
|
||||
default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict()
|
||||
dirty = False
|
||||
|
||||
if "printerParameters" in self._config:
|
||||
printer_parameters = self._config["printerParameters"]
|
||||
|
||||
if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters:
|
||||
default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict())
|
||||
if "movementSpeed" in printer_parameters:
|
||||
for axis in ("x", "y", "z", "e"):
|
||||
if axis in printer_parameters["movementSpeed"]:
|
||||
default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis]
|
||||
del self._config["printerParameters"]["movementSpeed"]
|
||||
if "invertedAxes" in printer_parameters:
|
||||
for axis in ("x", "y", "z", "e"):
|
||||
if axis in printer_parameters["invertedAxes"]:
|
||||
default_profile["axes"][axis]["inverted"] = True
|
||||
del self._config["printerParameters"]["invertedAxes"]
|
||||
|
||||
if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters:
|
||||
if not "extruder" in default_profile:
|
||||
default_profile["extruder"] = dict()
|
||||
|
||||
if "numExtruders" in printer_parameters:
|
||||
default_profile["extruder"]["count"] = printer_parameters["numExtruders"]
|
||||
del self._config["printerParameters"]["numExtruders"]
|
||||
if "extruderOffsets" in printer_parameters:
|
||||
extruder_offsets = []
|
||||
for offset in printer_parameters["extruderOffsets"]:
|
||||
if "x" in offset and "y" in offset:
|
||||
extruder_offsets.append((offset["x"], offset["y"]))
|
||||
default_profile["extruder"]["offsets"] = extruder_offsets
|
||||
del self._config["printerParameters"]["extruderOffsets"]
|
||||
|
||||
if "bedDimensions" in printer_parameters:
|
||||
bed_dimensions = printer_parameters["bedDimensions"]
|
||||
if not "volume" in default_profile:
|
||||
default_profile["volume"] = dict()
|
||||
|
||||
if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]:
|
||||
default_profile["volume"]["formFactor"] = "circular"
|
||||
default_profile["volume"]["width"] = 2 * bed_dimensions["r"]
|
||||
default_profile["volume"]["depth"] = default_profile["volume"]["width"]
|
||||
elif "x" in bed_dimensions or "y" in bed_dimensions:
|
||||
default_profile["volume"]["formFactor"] = "rectangular"
|
||||
if "x" in bed_dimensions:
|
||||
default_profile["volume"]["width"] = bed_dimensions["x"]
|
||||
if "y" in bed_dimensions:
|
||||
default_profile["volume"]["depth"] = bed_dimensions["y"]
|
||||
del self._config["printerParameters"]["bedDimensions"]
|
||||
|
||||
dirty = True
|
||||
|
||||
if dirty:
|
||||
if not "printerProfiles" in self._config:
|
||||
self._config["printerProfiles"] = dict()
|
||||
self._config["printerProfiles"]["defaultProfile"] = default_profile
|
||||
return dirty
|
||||
|
||||
def _migrate_reverse_proxy_config(self):
|
||||
if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]):
|
||||
prefix = ""
|
||||
if "baseUrl" in self._config["server"]:
|
||||
prefix = self._config["server"]["baseUrl"]
|
||||
del self._config["server"]["baseUrl"]
|
||||
|
||||
scheme = ""
|
||||
if "scheme" in self._config["server"]:
|
||||
scheme = self._config["server"]["scheme"]
|
||||
del self._config["server"]["scheme"]
|
||||
|
||||
if not "reverseProxy" in self._config["server"] or not isinstance(self._config["server"]["reverseProxy"], dict):
|
||||
self._config["server"]["reverseProxy"] = dict()
|
||||
if prefix:
|
||||
self._config["server"]["reverseProxy"]["prefixFallback"] = prefix
|
||||
if scheme:
|
||||
self._config["server"]["reverseProxy"]["schemeFallback"] = scheme
|
||||
self._logger.info("Migrated reverse proxy configuration to new structure")
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def _migrate_event_config(self):
|
||||
if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]):
|
||||
self._logger.info("Migrating config (event subscriptions)...")
|
||||
|
||||
# migrate event hooks to new format
|
||||
placeholderRe = re.compile("%\((.*?)\)s")
|
||||
|
||||
eventNameReplacements = {
|
||||
"ClientOpen": "ClientOpened",
|
||||
"TransferStart": "TransferStarted"
|
||||
}
|
||||
payloadDataReplacements = {
|
||||
"Upload": {"data": "{file}", "filename": "{file}"},
|
||||
"Connected": {"data": "{port} at {baudrate} baud"},
|
||||
"FileSelected": {"data": "{file}", "filename": "{file}"},
|
||||
"TransferStarted": {"data": "{remote}", "filename": "{remote}"},
|
||||
"TransferDone": {"data": "{remote}", "filename": "{remote}"},
|
||||
"ZChange": {"data": "{new}"},
|
||||
"CaptureStart": {"data": "{file}"},
|
||||
"CaptureDone": {"data": "{file}"},
|
||||
"MovieDone": {"data": "{movie}", "filename": "{gcode}"},
|
||||
"Error": {"data": "{error}"},
|
||||
"PrintStarted": {"data": "{file}", "filename": "{file}"},
|
||||
"PrintDone": {"data": "{file}", "filename": "{file}"},
|
||||
}
|
||||
|
||||
def migrateEventHook(event, command):
|
||||
# migrate placeholders
|
||||
command = placeholderRe.sub("{__\\1}", command)
|
||||
|
||||
# migrate event names
|
||||
if event in eventNameReplacements:
|
||||
event = eventNameReplacements["event"]
|
||||
|
||||
# migrate payloads to more specific placeholders
|
||||
if event in payloadDataReplacements:
|
||||
for key in payloadDataReplacements[event]:
|
||||
command = command.replace("{__%s}" % key, payloadDataReplacements[event][key])
|
||||
|
||||
# return processed tuple
|
||||
return event, command
|
||||
|
||||
disableSystemCommands = False
|
||||
if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]:
|
||||
disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"]
|
||||
|
||||
disableGcodeCommands = False
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"]
|
||||
|
||||
disableAllCommands = disableSystemCommands and disableGcodeCommands
|
||||
newEvents = {
|
||||
"enabled": not disableAllCommands,
|
||||
"subscriptions": []
|
||||
}
|
||||
|
||||
if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]:
|
||||
for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "system"}
|
||||
if disableSystemCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]:
|
||||
for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]:
|
||||
if not ("event" in trigger and "command" in trigger):
|
||||
continue
|
||||
|
||||
newTrigger = {"type": "gcode"}
|
||||
if disableGcodeCommands and not disableAllCommands:
|
||||
newTrigger["enabled"] = False
|
||||
|
||||
newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"])
|
||||
newTrigger["command"] = newTrigger["command"].split(",")
|
||||
newEvents["subscriptions"].append(newTrigger)
|
||||
|
||||
self._config["events"] = newEvents
|
||||
self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"]))
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def save(self, force=False):
|
||||
if not self._dirty and not force:
|
||||
return
|
||||
return False
|
||||
|
||||
with open(self._configfile, "wb") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self.load()
|
||||
return True
|
||||
|
||||
def _last_modified(self):
|
||||
stat = os.stat(self._configfile)
|
||||
return stat.st_mtime
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, asdict=False):
|
||||
def get(self, path, asdict=False, defaults=None, merged=False):
|
||||
import octoprint.util as util
|
||||
|
||||
if len(path) == 0:
|
||||
return None
|
||||
|
||||
config = self._config
|
||||
defaults = default_settings
|
||||
if defaults is None:
|
||||
defaults = default_settings
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
@@ -218,6 +488,8 @@ class Settings(object):
|
||||
for key in keys:
|
||||
if key in config.keys():
|
||||
value = config[key]
|
||||
if merged and key in defaults:
|
||||
value = util.dict_merge(defaults[key], value)
|
||||
elif key in defaults:
|
||||
value = defaults[key]
|
||||
else:
|
||||
@@ -236,8 +508,8 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path):
|
||||
value = self.get(path)
|
||||
def getInt(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -247,8 +519,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path):
|
||||
value = self.get(path)
|
||||
def getFloat(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -258,13 +530,17 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path):
|
||||
value = self.get(path)
|
||||
def getBoolean(self, path, defaults=None):
|
||||
value = self.get(path, defaults=defaults)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return value.lower() in valid_boolean_trues
|
||||
if isinstance(value, (int, float)):
|
||||
return value != 0
|
||||
if isinstance(value, (str, unicode)):
|
||||
return value.lower() in valid_boolean_trues
|
||||
return value is not None
|
||||
|
||||
def getBaseFolder(self, type):
|
||||
if type not in default_settings["folder"].keys():
|
||||
@@ -329,12 +605,16 @@ class Settings(object):
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False):
|
||||
def set(self, path, value, force=False, defaults=None):
|
||||
if len(path) == 0:
|
||||
return
|
||||
|
||||
if self._mtime is not None and self._last_modified() != self._mtime:
|
||||
self.load()
|
||||
|
||||
config = self._config
|
||||
defaults = default_settings
|
||||
if defaults is None:
|
||||
defaults = default_settings
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
@@ -359,9 +639,9 @@ class Settings(object):
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False):
|
||||
def setInt(self, path, value, force=False, defaults=None):
|
||||
if value is None:
|
||||
self.set(path, None, force)
|
||||
self.set(path, None, force=force, defaults=defaults)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -372,9 +652,9 @@ class Settings(object):
|
||||
|
||||
self.set(path, intValue, force)
|
||||
|
||||
def setFloat(self, path, value, force=False):
|
||||
def setFloat(self, path, value, force=False, defaults=None):
|
||||
if value is None:
|
||||
self.set(path, None, force)
|
||||
self.set(path, None, force=force, defaults=defaults)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -385,13 +665,13 @@ class Settings(object):
|
||||
|
||||
self.set(path, floatValue, force)
|
||||
|
||||
def setBoolean(self, path, value, force=False):
|
||||
def setBoolean(self, path, value, force=False, defaults=None):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, force)
|
||||
self.set(path, value, force=force, defaults=defaults)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, force)
|
||||
self.set(path, True, force=force, defaults=defaults)
|
||||
else:
|
||||
self.set(path, False, force)
|
||||
self.set(path, False, force=force, defaults=defaults)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
|
||||
Whitespace-only changes.
@@ -1,69 +0,0 @@
|
||||
__author__ = "Ross Hendrickson savorywatt"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
class CuraFactory(object):
|
||||
|
||||
@staticmethod
|
||||
def create_slicer(path=None):
|
||||
"""Utilizes the factory pattern to setup a CuraEngine object
|
||||
|
||||
:param path: :class: `str`
|
||||
"""
|
||||
if path:
|
||||
return Cura(path)
|
||||
|
||||
current_settings = settings(init=True)
|
||||
path = current_settings.get(["cura", "path"])
|
||||
|
||||
return Cura(path)
|
||||
|
||||
|
||||
class Cura(object):
|
||||
|
||||
def __init__(self, cura_path):
|
||||
|
||||
if not cura_path:
|
||||
raise Exception("Unable to create CuraEngine - no path specified")
|
||||
|
||||
self.cura_path = cura_path
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def process_file(
|
||||
self, config, gcode, file_path, call_back=None,
|
||||
call_back_args=None):
|
||||
|
||||
"""Wraps around the main.cpp processFile method.
|
||||
|
||||
:param config: :class: `string` :path to a cura config file:
|
||||
:param gcode: :class: `string :path to write out the gcode generated:
|
||||
:param file_path: :class: `string :path to the STL to be sliced:
|
||||
:note: This will spawn a thread to handle the subprocess call and allow
|
||||
us to be able to have a call back
|
||||
"""
|
||||
import threading
|
||||
|
||||
def start_thread(call_back, call_back_args, call_args, cwd):
|
||||
import subprocess
|
||||
self._logger.info("Running %r in %s" % (call_args, cwd))
|
||||
try:
|
||||
subprocess.check_call(call_args, cwd=cwd)
|
||||
call_back(*call_back_args)
|
||||
except subprocess.CalledProcessError as (e):
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % e.returncode)
|
||||
call_back_args.append("Got returncode %r" % e.returncode)
|
||||
call_back(*call_back_args)
|
||||
|
||||
executable = self.cura_path
|
||||
(workingDir, ignored) = os.path.split(executable)
|
||||
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
|
||||
|
||||
thread = threading.Thread(target=start_thread, args=(call_back,
|
||||
call_back_args, args, workingDir))
|
||||
|
||||
thread.start()
|
||||
@@ -1,31 +0,0 @@
|
||||
|
||||
|
||||
import unittest
|
||||
from mock import patch
|
||||
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
from octoprint.slicers.cura import Cura
|
||||
|
||||
class CuraFactoryTestCase(unittest.TestCase):
|
||||
|
||||
|
||||
def test_cura_factory(self):
|
||||
|
||||
fake_path = 'my/temp/path'
|
||||
result = CuraFactory.create_slicer(fake_path)
|
||||
|
||||
self.assertEqual(fake_path, result.cura_path)
|
||||
|
||||
|
||||
@patch('threading.Thread')
|
||||
def test_cura_engine_process_file(self, thread):
|
||||
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
|
||||
|
||||
cura = CuraFactory.create_slicer(path)
|
||||
file_path = './cura/tests/test.stl'
|
||||
config_path = './cura/tests/config'
|
||||
gcode_filename = './cura/tests/output.gcode'
|
||||
|
||||
cura.process_file(config_path, gcode_filename, file_path)
|
||||
self.assertTrue(thread.called)
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import octoprint.plugin
|
||||
import octoprint.events
|
||||
from octoprint.settings import settings
|
||||
|
||||
|
||||
class SlicingProfile(object):
|
||||
def __init__(self, slicer, name, data, display_name=None, description=None):
|
||||
self.slicer = slicer
|
||||
self.name = name
|
||||
self.data = data
|
||||
self.display_name = display_name
|
||||
self.description = description
|
||||
|
||||
|
||||
class TemporaryProfile(object):
|
||||
def __init__(self, save_profile, profile, overrides=None):
|
||||
self.save_profile = save_profile
|
||||
self.profile = profile
|
||||
self.overrides = overrides
|
||||
|
||||
def __enter__(self):
|
||||
import tempfile
|
||||
temp_profile = tempfile.NamedTemporaryFile(prefix="slicing-profile-temp-", suffix=".profile", delete=False)
|
||||
temp_profile.close()
|
||||
|
||||
self.temp_path = temp_profile.name
|
||||
self.save_profile(self.temp_path, self.profile, overrides=self.overrides)
|
||||
return self.temp_path
|
||||
|
||||
def __exit__(self, type, value, traceback):
|
||||
import os
|
||||
try:
|
||||
os.remove(self.temp_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
class SlicingCancelled(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class SlicingManager(object):
|
||||
def __init__(self, profile_path, printer_profile_manager):
|
||||
self._profile_path = profile_path
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
self._slicers = dict()
|
||||
self._slicer_names = dict()
|
||||
self._load_slicers()
|
||||
|
||||
self._progress_callbacks = []
|
||||
self._last_progress_report = None
|
||||
|
||||
def register_progress_callback(self, callback):
|
||||
self._progress_callbacks.append(callback)
|
||||
|
||||
def unregister_progress_callback(self, callback):
|
||||
self._progress_callbacks.remove(callback)
|
||||
|
||||
def _load_slicers(self):
|
||||
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
for name, plugin in plugins.items():
|
||||
if plugin.is_slicer_configured():
|
||||
self._slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
|
||||
@property
|
||||
def slicing_enabled(self):
|
||||
return len(self.configured_slicers) > 0
|
||||
|
||||
@property
|
||||
def registered_slicers(self):
|
||||
return self._slicers.keys()
|
||||
|
||||
@property
|
||||
def configured_slicers(self):
|
||||
return map(lambda slicer: slicer.get_slicer_properties()["type"], filter(lambda slicer: slicer.is_slicer_configured(), self._slicers.values()))
|
||||
|
||||
@property
|
||||
def default_slicer(self):
|
||||
slicer_name = settings().get(["slicing", "defaultSlicer"])
|
||||
if slicer_name in self.configured_slicers:
|
||||
return slicer_name
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_slicer(self, slicer, require_configured=True):
|
||||
return self._slicers[slicer] if slicer in self._slicers and (not require_configured or self._slicers[slicer].is_slicer_configured()) else None
|
||||
|
||||
def slice(self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, printer_profile_id=None, position=None):
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
if callback_kwargs is None:
|
||||
callback_kwargs = dict()
|
||||
|
||||
if not slicer_name in self.configured_slicers:
|
||||
if not slicer_name in self.registered_slicers:
|
||||
error = "No such slicer: {slicer_name}".format(**locals())
|
||||
else:
|
||||
error = "Slicer not configured: {slicer_name}".format(**locals())
|
||||
callback_kwargs.update(dict(_error=error))
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
return False, error
|
||||
|
||||
slicer = self.get_slicer(slicer_name)
|
||||
|
||||
printer_profile = None
|
||||
if printer_profile_id is not None:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
def slicer_worker(slicer, model_path, machinecode_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs):
|
||||
try:
|
||||
slicer_name = slicer.get_slicer_properties()["type"]
|
||||
with self.temporary_profile(slicer_name, name=profile_name, overrides=overrides) as profile_path:
|
||||
ok, result = slicer.do_slice(
|
||||
model_path,
|
||||
printer_profile,
|
||||
machinecode_path=machinecode_path,
|
||||
profile_path=profile_path,
|
||||
position=position,
|
||||
on_progress=on_progress,
|
||||
on_progress_args=on_progress_args,
|
||||
on_progress_kwargs=on_progress_kwargs
|
||||
)
|
||||
|
||||
if not ok:
|
||||
callback_kwargs.update(dict(_error=result))
|
||||
elif result is not None and isinstance(result, dict) and "analysis" in result:
|
||||
callback_kwargs.update(dict(_analysis=result["analysis"]))
|
||||
except SlicingCancelled:
|
||||
callback_kwargs.update(dict(_cancelled=True))
|
||||
finally:
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
|
||||
import threading
|
||||
slicer_worker_thread = threading.Thread(target=slicer_worker,
|
||||
args=(slicer, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs))
|
||||
slicer_worker_thread.daemon = True
|
||||
slicer_worker_thread.start()
|
||||
return True, None
|
||||
|
||||
def cancel_slicing(self, slicer_name, source_path, dest_path):
|
||||
if not slicer_name in self.registered_slicers:
|
||||
return
|
||||
slicer = self.get_slicer(slicer_name)
|
||||
slicer.cancel_slicing(dest_path)
|
||||
|
||||
def load_profile(self, slicer, name):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
try:
|
||||
path = self.get_profile_path(slicer, name, must_exist=True)
|
||||
except IOError:
|
||||
return None
|
||||
return self._load_profile_from_path(slicer, path)
|
||||
|
||||
def save_profile(self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None):
|
||||
if not slicer in self.registered_slicers:
|
||||
return
|
||||
|
||||
if not isinstance(profile, SlicingProfile):
|
||||
if isinstance(profile, dict):
|
||||
profile = SlicingProfile(slicer, name, profile, display_name=display_name, description=description)
|
||||
else:
|
||||
raise ValueError("profile must be a SlicingProfile")
|
||||
else:
|
||||
profile.slicer = slicer
|
||||
profile.name = name
|
||||
if display_name is not None:
|
||||
profile.display_name = display_name
|
||||
if description is not None:
|
||||
profile.description = description
|
||||
|
||||
path = self.get_profile_path(slicer, name)
|
||||
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
|
||||
return profile
|
||||
|
||||
def temporary_profile(self, slicer, name=None, overrides=None):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
profile = self._get_default_profile(slicer)
|
||||
if name:
|
||||
try:
|
||||
profile = self.load_profile(slicer, name)
|
||||
except IOError:
|
||||
profile = self._get_default_profile(slicer)
|
||||
else:
|
||||
if profile is None:
|
||||
profile = self._get_default_profile(slicer)
|
||||
|
||||
return TemporaryProfile(self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides)
|
||||
|
||||
def delete_profile(self, slicer, name):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
path = self.get_profile_path(slicer, name)
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return
|
||||
os.remove(path)
|
||||
|
||||
def all_profiles(self, slicer):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
profiles = dict()
|
||||
slicer_profile_path = self.get_slicer_profile_path(slicer)
|
||||
for entry in os.listdir(slicer_profile_path):
|
||||
if not entry.endswith(".profile") or entry.startswith("."):
|
||||
# we are only interested in profiles and no hidden files
|
||||
continue
|
||||
|
||||
path = os.path.join(slicer_profile_path, entry)
|
||||
profile_name = entry[:-len(".profile")]
|
||||
|
||||
profiles[profile_name] = self._load_profile_from_path(slicer, path)
|
||||
return profiles
|
||||
|
||||
def get_slicer_profile_path(self, slicer):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
path = os.path.join(self._profile_path, slicer)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_profile_path(self, slicer, name, must_exist=False):
|
||||
if not slicer in self.registered_slicers:
|
||||
return None
|
||||
|
||||
if not name:
|
||||
return None
|
||||
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
|
||||
if not os.path.realpath(path).startswith(self._profile_path):
|
||||
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
|
||||
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
|
||||
raise IOError("Profile {name} doesn't exist".format(**locals()))
|
||||
return path
|
||||
|
||||
def _sanitize(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
def _load_profile_from_path(self, slicer, path):
|
||||
return self.get_slicer(slicer).get_slicer_profile(path)
|
||||
|
||||
def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None):
|
||||
self.get_slicer(slicer).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides)
|
||||
|
||||
def _get_default_profile(self, slicer):
|
||||
default_profiles = settings().get(["slicing", "defaultProfiles"])
|
||||
if default_profiles and slicer in default_profiles:
|
||||
try:
|
||||
return self.load_profile(slicer, default_profiles[slicer])
|
||||
except:
|
||||
pass
|
||||
|
||||
return self.get_slicer(slicer).get_slicer_default_profile()
|
||||
|
||||
|
||||
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user