├── LICENSE ├── README.md ├── screenshots ├── README.md ├── screen_1.PNG └── screen_2.PNG └── web_dwc2.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DO NOT USE THIS ANYMORE! 2 | # This is only here for refference. please use: 3 | [Socket version](https://github.com/Stephan3/dwc2-for-klipper-socket) 4 | 5 | 6 | -------------------------------------------------- 7 | 8 | # dwc2-for-klipper 9 | 10 | A translator between [DWC2](https://github.com/Duet3D/DuetWebControl) and Klipper 11 | 12 | ![Alt text](screenshots/screen_1.PNG?raw=true "screen 1") 13 | ![Alt text](screenshots/screen_2.PNG?raw=true "screen 2") 14 | 15 | ## What works 16 | 17 | * printing from Klipper's virtual sdcard 18 | * pause / cancel prints (resume?) 19 | * babystepping feature using Klipper's ```SET_GCODE_OFFSET Z_ADJUST``` 20 | * editing Klipper's configuration. Its displayed as `config.g` in system section. So the web interface restarts Klipper after saving. 21 | * Klipper macros are imported as virtual files and can be accesed from the dashboard 22 | * uploads and downloads of gcodes 23 | * gcode analysis using regex to determine duration / layerhight / firstlayer / filamentusage and others 24 | * the math for printtime left based on whatever, showing layerhistory, detecting layerchanges etc. (needs working slicer regex) 25 | * settings of web interface are saved and loaded correctly 26 | * homing / extruding / moving 27 | * heater control 28 | * setting fanspeed / extrusionmultiplier / speedfactor during print in status window 29 | * heightmap is working (needs manual `BED_MESH_CALIBATE`). It is kept only for displaying, even after `BED_MESH_CLEAR` 30 | * webcam integration works now 31 | * with mjpeg-streamer add the streaming URL to settings; example: http://192.168.2.20:8080/?action=stream 32 | * With YouTube Live; example: https://webcam.io/support/howto-embed-youtube-live/ 33 | * pause/resume/cancel macros are working now - see Things You Should Know below 34 | * plugin for Cura 4.0 does work, just enter URL; for example: http://192.168.2.188:4750/ 35 | 36 | ## What is not working 37 | 38 | * ~~webcam integration~~ 39 | * ~~heightmap~~ 40 | * printsimulation 41 | * actual machinespeed, only displaying the requested values 42 | * klipper does not have this feedback (yet)? due to its lookahead feature 43 | * can we calc this? movelength/junction/acceleration is there 44 | * ~~cancel/pause/resume macros. I will do this soon~~ 45 | * ~~rrf/dwc cura plugin~~ 46 | * ... 47 | 48 | ## Things you should know 49 | 50 | * Klipper messages are marked as warnings (yellow). 51 | * Normaly Klipper knows ok and error 52 | * Klipper's `printer.cfg` is displayed as a virtual file (`config.g`) in system section 53 | * restart after configuration edits works 54 | * The macros you define in `printer.cfg` are displayed as virtual files wthin DWC's macros 55 | * For pause and resume macros you can use: 56 | * Klipper gcode macros `pause_print`, `resume_print`, `cancel_print` (not case sensitive) 57 | * DWC macros `pause.g`, `resume.g`, `cancel.g` - this is in line with RRF 58 | * DWC macros are overriding Klipper's macros 59 | * ... 60 | 61 | ## Installation 62 | 63 | ### Prerequisites 64 | 65 | Python 2, Tornado, gunzip, unzip and wget. 66 | 67 | #### On ArchLinux: 68 | 69 | ``` 70 | sudo pacman -Syu python2 python2-tornado wget gzip 71 | ``` 72 | 73 | Maybe you´ll need to change the startup system for Klipper to access `~/klipper/klippy/klippy.py`. 74 | 75 | #### On Debian-based systems such as Octopi or Ubuntu: 76 | 77 | I asume here that you used the Octopi install script from Kevin's GitHub repository. 78 | 79 | ``` 80 | sudo apt install wget gzip tar 81 | ``` 82 | 83 | Then switch to your klipper user and: 84 | 85 | ``` 86 | sudo systemctl stop klipper 87 | cd ~ 88 | mv klipper klipper_backup 89 | PYTHONDIR="${HOME}/klippy-env" 90 | virtualenv ${PYTHONDIR} 91 | ${PYTHONDIR}/bin/pip install tornado==5.1.1 92 | 93 | git clone https://github.com/KevinOConnor/klipper.git 94 | git clone https://github.com/Stephan3/dwc2-for-klipper.git 95 | ln -s ~/dwc2-for-klipper/web_dwc2.py ~/klipper/klippy/extras/web_dwc2.py 96 | 97 | mkdir -p ~/sdcard/dwc2/web 98 | mkdir -p ~/sdcard/sys 99 | cd ~/sdcard/dwc2/web 100 | wget https://github.com/Duet3D/DuetWebControl/releases/download/3.1.1/DuetWebControl-SD.zip 101 | unzip *.zip && for f_ in $(find . | grep '.gz');do gunzip ${f_};done 102 | sudo systemctl start klipper 103 | ``` 104 | 105 | #### If you want backwards compatibility to DWC1: 106 | 107 | ``` 108 | cd ~/sdcard/dwc2/web 109 | wget https://github.com/chrishamm/DuetWebControl/releases/download/1.22.5/DuetWebControl-1.22.5.zip 110 | unzip DuetWebContro*.zip 111 | for f_ in $(find . | grep '.gz');do gunzip ${f_};done 112 | ``` 113 | 114 | ### Klipper config example: 115 | 116 | ``` 117 | [virtual_sdcard] 118 | path: /home/pi/sdcard 119 | 120 | [web_dwc2] 121 | # optional - defaulting to Klipper 122 | printer_name: Reiner Calmund 123 | # optional - defaulting to 127.0.0.1 124 | listen_adress: 0.0.0.0 125 | # needed - use above 1024 as nonroot 126 | listen_port: 4750 127 | # optional defaulting to dwc2/web. Its a folder relative to your virtual sdcard. 128 | web_path: dwc2/web 129 | ``` 130 | -------------------------------------------------------------------------------- /screenshots/README.md: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /screenshots/screen_1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stephan3/dwc2-for-klipper/6461e6a8e1a9b8714018df4ed01751e4bb40c385/screenshots/screen_1.PNG -------------------------------------------------------------------------------- /screenshots/screen_2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stephan3/dwc2-for-klipper/6461e6a8e1a9b8714018df4ed01751e4bb40c385/screenshots/screen_2.PNG -------------------------------------------------------------------------------- /web_dwc2.py: -------------------------------------------------------------------------------- 1 | # A Json api to get data from klippy through http 2 | # 3 | # This file may be distributed under the terms of the GNU GPLv3 license. 4 | 5 | import logging 6 | import json 7 | import threading 8 | from multiprocessing import Process, Queue 9 | # for webserver 10 | import tornado.web 11 | import tornado.gen 12 | import base64 13 | import uuid 14 | import os 15 | import datetime 16 | import re 17 | import time 18 | import util 19 | import shutil 20 | import gcode as kgcode 21 | import serial 22 | 23 | # 24 | class web_dwc2: 25 | 26 | ## 27 | # Stuff arround klippers extras logic 28 | ## 29 | # init who? 30 | def __init__(self, config): 31 | 32 | self.klipper_ready = False 33 | self.popup = None 34 | self.message = None 35 | # get config 36 | self.config = config 37 | self.adress = config.get( 'listen_adress', "127.0.0.1" ) 38 | self.port = config.getint( "listen_port", 4711 ) 39 | self.webpath = config.get( 'web_path', "dwc2/web" ) 40 | self.printername = config.get( 'printer_name', "Klipper" ) 41 | # klippy objects 42 | self.current_tool = -1 43 | self.bed_mesh = None 44 | self.printer = config.get_printer() 45 | self.reactor = self.printer.get_reactor() 46 | self.gcode = self.printer.lookup_object('gcode') 47 | self.gcode_io = self.printer.lookup_object("gcode_io") 48 | self.configfile = self.printer.lookup_object('configfile').read_main_config() 49 | self.stepper_enable = self.printer.load_object(config, "stepper_enable") 50 | # gcode execution needs 51 | self.gcode_queue = [] # containing gcode user pushes from dwc2 52 | self.gcode_reply = [] # contains the klippy replys 53 | self.klipper_macros = [] 54 | self.mutex = self.reactor.mutex() 55 | # once klipper is ready start pre_flight function - not happy with this. If klipper fails to launch -> no web if? 56 | self.printer.register_event_handler("klippy:ready", self.handle_ready) 57 | self.printer.register_event_handler("klippy:disconnect", self.shutdown) 58 | self.start_time = time.time() 59 | # grab stuff from config file 60 | self.klipper_config = self.printer.get_start_args()['config_file'] 61 | self.sdpath = self.configfile.getsection("virtual_sdcard").get("path", None) 62 | self.sdpath = os.path.normpath(os.path.expanduser(self.sdpath)) 63 | if not self.sdpath: 64 | logging.error( "DWC2 failed to start, no sdcard configured" ) 65 | return 66 | self.kin_name = self.configfile.getsection("printer").get("kinematics") 67 | self.web_root = self.sdpath + "/" + self.webpath 68 | if not os.path.isfile( self.web_root + "/" + "index.html" ): 69 | logging.error( "DWC2 failed to start, no webif found in " + self.web_root ) 70 | return 71 | self.gcode.register_output_handler(self.gcode_response) 72 | # manage client sessions 73 | self.sessions = {} 74 | self.status_0 = {} 75 | self.status_1 = {} 76 | self.status_2 = {} 77 | self.status_3 = {} 78 | self.file_infos = {} # just read files once 79 | self.dwc2() 80 | logging.basicConfig(level=logging.DEBUG) 81 | # function once reactor calls, once klipper feels good 82 | def handle_ready(self): 83 | # klippy related 84 | self.current_tool = 0 85 | self.chamber = self.printer.lookup_object('chamber', None) 86 | self.heater_bed = self.printer.lookup_object('heater_bed', None) 87 | self.fan = self.printer.lookup_object('fan', None) 88 | self.sdcard = self.printer.lookup_object('virtual_sdcard', None) 89 | self.toolhead = self.printer.lookup_object('toolhead', None) 90 | # hopeflly noone get more than 4 extruders up :D 91 | self.extruders = [ self.printer.lookup_object('extruder', None) ] 92 | for i in range(1,10): 93 | app = self.printer.lookup_object('extruder%d' % (i,), None) 94 | if app: 95 | self.extruders.append(app) 96 | self.kinematics = self.toolhead.get_kinematics() 97 | 98 | # print data for tracking layers during print 99 | self.print_data = {} # printdata/layertimes etc 100 | self.klipper_ready = True 101 | self.get_klipper_macros() 102 | # registering command 103 | self.gcode.register_command( 'M292', self.cmd_M292, 104 | desc="okay button in DWC2") 105 | # reactor calls this on klippy restart 106 | def shutdown(self): 107 | # kill the thread here 108 | logging.info( "DWC2 shuting down - as klippy is shutdown" ) 109 | self.ioloop.stop() 110 | self.http_server.stop() 111 | self.sessions = {} 112 | 113 | ## 114 | # Webserver and related 115 | ## 116 | # launch webserver 117 | def dwc2(self): 118 | def tornado_logger(req): 119 | fressehaltn = [] 120 | fressehaltn = [ "/favicon.ico", "/rr_status?type=1", "/rr_status?type=2", "/rr_status?type=3", "/rr_reply", "/rr_config" ] 121 | values = [str(time.time())[-8:], req.request.remote_ip, req.request.method, req.request.uri] 122 | if req.request.uri not in fressehaltn: 123 | logging.info("DWC2:" + " - ".join(values)) # bind this to debug later 124 | def launch_tornado(application): 125 | #time.sleep(10) # delay startup so dwc2 can timeout 126 | logging.info( "DWC2 starting at: http://" + str(self.adress) + ":" + str(self.port) ) 127 | self.http_server = tornado.httpserver.HTTPServer( application, max_buffer_size=500*1024*1024 ) 128 | self.http_server.listen( self.port ) 129 | self.ioloop = tornado.ioloop.IOLoop.current() 130 | self.ioloop.start() 131 | def debug_console(self): 132 | logging.debug( "Start debbug console:\n") 133 | import pdb; pdb.set_trace() 134 | # 135 | cookie_secret = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes) # random cookie 136 | # define the threading aplication 137 | application = tornado.web.Application( 138 | [ 139 | tornado.web.url(r"/css/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/css/"}), 140 | tornado.web.url(r"/js/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/js/"}), 141 | tornado.web.url(r"/fonts/(.*)", tornado.web.StaticFileHandler, {"path": self.web_root + "/fonts/"}), 142 | tornado.web.url(r"/(rr_.*)", self.req_handler, { "web_dwc2": self } ), 143 | tornado.web.url(r"/.*", self.dwc_handler,{"p_": self.web_root}, name="main"), 144 | ], 145 | cookie_secret=cookie_secret, 146 | log_function=tornado_logger) 147 | self.tornado = threading.Thread( target=launch_tornado, args=(application,) ) 148 | self.tornado.daemon = True 149 | self.tornado.start() 150 | 151 | #dbg = threading.Thread( target=debug_console, args=(self,) ) 152 | #dbg.start() 153 | # the main webpage to serve the client browser itself 154 | class dwc_handler(tornado.web.RequestHandler): 155 | 156 | def initialize(self, p_): 157 | self.web_root = p_ 158 | 159 | def get(self): 160 | def index(): 161 | rq_path = self.web_root + "/index.html" 162 | self.render( rq_path ) 163 | 164 | if self.request.uri == "/": # redirect ti index.html(dwc2) 165 | index() 166 | elif ".htm" in self.request.uri: # covers others like dwc1 167 | self.render( self.web_root + self.request.uri ) 168 | elif ".json" in self.request.uri: # covers dwc1 settingsload 169 | if os.path.isfile(self.web_root + self.request.uri): 170 | pass 171 | else: 172 | self.write( { "err": 1 } ) 173 | elif os.path.isfile(self.web_root + self.request.uri): 174 | with open(self.web_root + self.request.uri, "rb") as f: 175 | self.write( f.read() ) 176 | self.finish() 177 | 178 | else: 179 | logging.warn( "DWC2 - unhandled request in dwc_handler: " + self.request.uri + " redirecting to index.") 180 | index() 181 | #for handling request dwc2 is sending 182 | class req_handler(tornado.web.RequestHandler): 183 | 184 | def initialize(self, web_dwc2): 185 | 186 | self.web_dwc2 = web_dwc2 187 | self.repl_ = {"err":1} 188 | 189 | @tornado.gen.coroutine 190 | def get(self, *args): 191 | 192 | if self.request.remote_ip not in self.web_dwc2.sessions.keys() and "rr_connect" not in self.request.uri and self.request.remote_ip != '127.0.0.1': 193 | # response 408 timeout to force the webif reload after klippy restarts us 194 | self.clear() 195 | self.set_status(408) 196 | self.finish() 197 | return 198 | 199 | # dwc connect request 200 | if "rr_connect" in self.request.uri: 201 | self.repl_ = self.web_dwc2.rr_connect(self) 202 | # there is no rr_configfile so return empty 203 | elif "rr_configfile" in self.request.uri: 204 | self.repl_ = { "err" : 0 } 205 | elif "rr_config" in self.request.uri: 206 | self.repl_ = self.web_dwc2.rr_config() 207 | # filehandling - delete files/folders 208 | elif "rr_delete" in self.request.uri: 209 | self.repl_ = self.web_dwc2.rr_delete( self ) 210 | # disconnect 211 | elif "/rr_disconnect" in self.request.uri: 212 | self.repl_ = { "err" : 0 } 213 | # filehandling . download 214 | elif "rr_download" in self.request.uri: 215 | self.repl_ = self.web_dwc2.rr_download(self) 216 | # filehandling - dirlisting 217 | elif "rr_filelist" in self.request.uri: 218 | self.repl_ = self.web_dwc2.rr_filelist(self) 219 | # filehandling - dirlisting for dwc 1 220 | elif "rr_files" in self.request.uri: 221 | self.repl_ = self.web_dwc2.rr_files(self) 222 | # filehandling - fileinfo / gcodeinfo 223 | elif "rr_fileinfo" in self.request.uri: 224 | self.repl_ = yield self.web_dwc2.rr_fileinfo(self) 225 | # gcode request 226 | elif "rr_gcode" in self.request.uri: 227 | self.repl_ = self.web_dwc2.rr_gcode( self ) 228 | return 229 | # filehandling - dircreation 230 | elif "rr_mkdir" in self.request.uri: 231 | self.web_dwc2.rr_mkdir(self) 232 | return 233 | elif "rr_move" in self.request.uri: 234 | self.repl_ = self.web_dwc2.rr_move(self) 235 | # gcode reply 236 | elif "rr_reply" in self.request.uri: 237 | self.web_dwc2.rr_reply(self) 238 | return 239 | # status replys 240 | elif "rr_status" in self.request.uri: 241 | 242 | if not self.web_dwc2.klipper_ready: 243 | self.web_dwc2.rr_status_0() 244 | self.repl_ = self.web_dwc2.status_0 245 | 246 | else: 247 | # there are 3 types of status requests: 248 | t_ = int( self.get_argument('type') ) 249 | 250 | if t_ == 1: 251 | self.web_dwc2.rr_status_1() 252 | self.repl_ = self.web_dwc2.status_1 253 | 254 | elif t_ == 2: 255 | self.web_dwc2.rr_status_2() 256 | self.repl_ = self.web_dwc2.status_2 257 | 258 | elif t_ == 3: 259 | self.web_dwc2.rr_status_3() 260 | self.repl_ = self.web_dwc2.status_3 261 | 262 | else: 263 | logging.warn(" DWC2 - error in rr_status \n" + str(t_) ) 264 | 265 | 266 | if self.repl_ == {"err":1}: 267 | logging.warn("DWC2 - unhandled ?GET? " + self.request.uri) 268 | 269 | try: 270 | if self.repl_: 271 | self.write( json.dumps(self.repl_) ) 272 | except Exception as e: 273 | logging.warn( "DWC2 - error in write: " + str(e) ) 274 | 275 | def post(self, *args): 276 | 277 | # filehandling - uploads 278 | if "rr_upload" in self.request.uri: 279 | self.repl_ = self.web_dwc2.rr_upload(self) 280 | 281 | try: 282 | self.write( json.dumps(self.repl_) ) 283 | except Exception as e: 284 | logging.warn( "DWC2 - error in write: " + str(e) ) 285 | 286 | def decode_argument(self, value, name=None): 287 | return value.encode('UTF-8') if isinstance(value, unicode) else value 288 | 289 | ## 290 | # All the crazy shit dc42 fiddled together in c 291 | ## 292 | # dwc rr_connect 293 | def rr_connect(self, web_): 294 | 295 | # better error? 296 | repl_ = { 297 | "err":0, 298 | "sessionTimeout":8000, # config value? 299 | "boardType":"unknown" # has klippy this data? 300 | } 301 | 302 | user_cookie = web_.request.headers.get("Cookie") 303 | user_ip = web_.request.remote_ip 304 | 305 | self.sessions[user_ip] = user_cookie 306 | 307 | return repl_ 308 | # dwc rr_config 309 | def rr_config(self): 310 | 311 | try: 312 | max_acc = self.toolhead.max_accel 313 | max_vel = self.toolhead.max_velocity 314 | rails_ = self.kinematics.rails 315 | extru_ = self.extruders 316 | except Exception as e: 317 | max_acc = [] 318 | max_vel = [] 319 | rails_ = [] 320 | extru_ = [] 321 | ax_ = [[],[]] 322 | for r_ in rails_: 323 | 324 | min_pos, max_pos = r_.get_range() 325 | ax_[0].append(min_pos) 326 | ax_[1].append(max_pos) 327 | 328 | repl_ = { 329 | "axisMins": [ x for x in ax_[0] ], 330 | "axisMaxes": [ x for x in ax_[1] ], 331 | "accelerations": [ max_acc for x in ax_[0] ], 332 | "currents": [ 0 for x in ax_[0] ] + [ 0 for ex_ in extru_ if ex_ is not None ] , # can we fetch data from tmc drivers here ? 333 | "firmwareElectronics": util.get_cpu_info(), 334 | "firmwareName": "Klipper", 335 | "firmwareVersion": self.printer.get_start_args()['software_version'], 336 | "dwsVersion": self.printer.get_start_args()['software_version'], 337 | "firmwareDate": "2018-12-24b1", # didnt get that from klippy 338 | "idleCurrentFactor": 30, 339 | "idleTimeout": 30, 340 | "minFeedrates": [ 5 for x in ax_[0] ] + [ 5 for ex_ in extru_ if ex_ is not None ] , 341 | "maxFeedrates": [ max_vel for x in ax_[0] ] + [ min(75,max_vel) for ex_ in extru_ if ex_ is not None ] # unitconversion ? 342 | } 343 | 344 | return repl_ 345 | # simple dir/fileremover 346 | def rr_delete(self, web_): 347 | 348 | # lazymode_ 349 | path_ = self.sdpath + web_.get_argument('name').replace("0:", "") 350 | 351 | if os.path.isdir(path_): 352 | shutil.rmtree(path_) 353 | 354 | if os.path.isfile(path_): 355 | os.remove(path_) 356 | 357 | if path_ in self.file_infos.keys(): 358 | self.file_infos.pop(path_, None) 359 | 360 | return {'err': 0} 361 | # dwc rr_download - lacks logging 362 | def rr_download(self, web_): 363 | 364 | path_ = self.sdpath + web_.get_argument('name').replace("0:", "") 365 | 366 | # ovverride for config file 367 | if "/sys/" in path_ and "config.g" in web_.get_argument('name').replace("0:", ""): 368 | path_ = self.klipper_config 369 | 370 | # handle heigthmap 371 | if 'heightmap.csv' in path_: 372 | repl_ = self.get_heigthmap() 373 | if repl_: 374 | with open(path_, "w") as f: 375 | for line in repl_: 376 | f.write( line + '\n') 377 | 378 | if os.path.isfile(path_): 379 | 380 | # handles regular files 381 | web_.set_header( 'Content-Type', 'application/force-download' ) 382 | web_.set_header( 'Content-Disposition', 'attachment; filename=%s' % os.path.basename(path_) ) 383 | 384 | with open(path_, "rb") as f: 385 | web_.write( f.read() ) 386 | 387 | else: 388 | return {"err":1} 389 | # dwc rr_files - dwc1 thing 390 | def rr_files(self, web_): 391 | 392 | path_ = self.sdpath + web_.get_argument('dir').replace("0:", "") 393 | 394 | repl_ = { 395 | "dir": web_.get_argument('dir') , 396 | "first": web_.get_argument('first', 0) , 397 | "files": [] , 398 | "next": 0 , 399 | "err": 0 400 | } 401 | 402 | # if rrf is requesting directory, it has to be there. 403 | if not os.path.exists(path_): 404 | os.makedirs(path_) 405 | 406 | # append elements to files list matching rrf syntax 407 | for el_ in os.listdir(path_): 408 | el_path = path_ + "/" + el_ 409 | repl_['files'].append( "*" + str(el_) if os.path.isdir(el_path) else str(el_) ) 410 | 411 | return repl_ 412 | # dwc rr_filelist 413 | def rr_filelist(self, web_): 414 | 415 | path_ = self.sdpath + web_.get_argument('dir').replace("0:", "") 416 | 417 | # creating the infoblock 418 | repl_ = { 419 | "dir": web_.get_argument('dir') , 420 | "first": web_.get_argument('first', 0) , 421 | "files": [] , 422 | "next": 0 423 | } 424 | 425 | # if rrf is requesting directory, it has to be there. 426 | if not os.path.exists(path_): 427 | os.makedirs(path_) 428 | 429 | # whitespace uploads via nfs/samba 430 | for file in os.listdir(path_): 431 | os.rename(os.path.join(path_, file), os.path.join(path_, file.replace(' ', '_'))) 432 | 433 | # append elements to files list matching rrf syntax 434 | for el_ in os.listdir(path_): 435 | el_path = path_ + "/" + str(el_) 436 | repl_['files'].append({ 437 | "type": "d" if os.path.isdir(el_path) else "f" , 438 | "name": str(el_) , 439 | "size": os.stat(el_path).st_size , 440 | "date": datetime.datetime.fromtimestamp(os.stat(el_path).st_mtime).strftime("%Y-%m-%dT%H:%M:%S") 441 | }) 442 | 443 | # add klipper macros as virtual files 444 | if "/macros" in web_.get_argument('dir').replace("0:", ""): 445 | for macro_ in self.klipper_macros: 446 | 447 | repl_['files'].append({ 448 | "type": "f" , 449 | "name": macro_ , 450 | "size": 1 , 451 | "date": datetime.datetime.fromtimestamp(os.stat(self.klipper_config).st_mtime).strftime("%Y-%m-%dT%H:%M:%S") 452 | }) 453 | 454 | # virtual config file 455 | elif "/sys" in web_.get_argument('dir').replace("0:", ""): 456 | 457 | repl_['files'].append({ 458 | "type": "f", 459 | "name": "config.g" , 460 | "size": os.stat(self.klipper_config).st_size , 461 | "date": datetime.datetime.fromtimestamp(os.stat(self.klipper_config).st_mtime).strftime("%Y-%m-%dT%H:%M:%S") 462 | }) 463 | 464 | return repl_ 465 | # dwc fileinfo - getting gcode info 466 | @tornado.gen.coroutine 467 | def rr_fileinfo(self, web_): 468 | 469 | try: 470 | path_ = self.sdpath + web_.get_argument('name').replace("0:", "") 471 | except: 472 | path_ = self.sdcard.current_file.name 473 | 474 | if not os.path.isfile(path_): 475 | return { "err": 1 } 476 | 477 | if not path_ in self.file_infos.keys(): 478 | dict_ = Queue() 479 | proc_ = Process(target=self.read_gcode, args=(path_,dict_)) 480 | proc_.start() 481 | proc_.join(5) 482 | self.file_infos[path_] = dict_.get() 483 | 484 | return self.file_infos[path_] 485 | # dwc rr_gcode - append to gcode_queue 486 | def rr_gcode(self, web_): 487 | 488 | # handover to klippy as: [ "G28", "M114", "G1 X150", etc... ] 489 | gcodes = str( web_.get_argument('gcode') ).replace('0:', '').replace('"', '').split("\n") 490 | 491 | rrf_commands = { 492 | 'G10': self.cmd_G10 , # set heaters temp 493 | 'M0': self.cmd_M0 , # cancel SD print 494 | 'M24': self.cmd_M24 , # resume sdprint 495 | 'M25': self.cmd_M25 , # pause print 496 | 'M32': self.cmd_M32 , # Start sdprint 497 | 'M98': self.cmd_M98 , # run macro 498 | 'M106': self.cmd_M106 , # set fan 499 | 'M120': self.cmd_M120 , # save gcode state 500 | 'M121': self.cmd_M121 , # restore gcode state 501 | 'M140': self.cmd_M140 , # set bedtemp(limit to 0 mintemp) 502 | 'M290': self.cmd_M290 , # set babysteps 503 | 'M999': self.cmd_M999 # issue restart 504 | } 505 | 506 | # allow - set heater, cancelprint, set bed, ,pause, resume, set fan, set speedfactor, set extrusion multipler, babystep, ok in popup 507 | midprint_allow = [ 'DUMP_TMC', 'G10', 'GET_POSITION', 'HELP', 'M0', 'M140', 'M24', 'M25', 'M104', 'M106', 'M107', 'M112', 'M114', 'M115', 'M140', 'M204', 'M220', 'M221', 'M290', 'M292', 'QUERY_FILAMENT_SENSOR', 'SET_TMC_CURRENT', 'SET_PIN', 508 | 'SET_PRESSURE_ADVANCE', 'SET_VELOCITY_LIMIT', 'T' ] 509 | 510 | # Handle emergencys - just do it now 511 | for code in gcodes: 512 | if 'M112' in code: 513 | self.cmd_M112(0) 514 | 515 | # start to prepare commands 516 | while gcodes: 517 | 518 | # parse commands 519 | params, gcmd = self.parse_params(gcodes.pop(0)) 520 | 521 | # defaulting to original 522 | handover = params['#original'] 523 | 524 | # handle toolchanges 525 | if re.match('^T(-)?\d$', params['#command']): 526 | self.current_tool = abs(int(params['T'])) 527 | if params['#command'] == 'T-1': 528 | continue 529 | 530 | # prevent midprint accidents 531 | stat_ = self.get_printer_status() 532 | if stat_ in [ 'P', 'D', 'R' ] and params['#command'] not in midprint_allow : 533 | web_.write( json.dumps({'buff': 0, 'err': 0}) ) 534 | continue 535 | 536 | # rewrite rrfs specials to klipper readable format 537 | if params['#command'] in rrf_commands.keys(): 538 | func_ = rrf_commands.get(params['#command']) 539 | handover = func_(params) 540 | if handover == 0: 541 | self.gcode_reply.append("ok\n") 542 | 543 | # if we set things directly in klipper we dont need to pipe gcodes 544 | if handover: 545 | self.gcode_queue.append(handover) 546 | 547 | web_.write( json.dumps({'buff': 1, 'err': 0}) ) 548 | web_.finish() 549 | self.reactor.register_callback(self.gcode_reactor_callback,waketime=self.reactor.monotonic() + 0.1) 550 | # dwc rr_move - backup printer.cfg 551 | def rr_move(self, web_): 552 | 553 | if "/sys/" in web_.get_argument('old').replace("0:", "") and "config.g" in web_.get_argument('old').replace("0:", ""): 554 | src_ = self.klipper_config 555 | dst_ = self.klipper_config + ".backup" 556 | 557 | else: 558 | src_ = self.sdpath + web_.get_argument('old').replace("0:", "") 559 | dst_ = self.sdpath + web_.get_argument('new').replace("0:", "") 560 | 561 | try: 562 | shutil.move( src_ , dst_) 563 | except Exception as e: 564 | return {"err": 1} 565 | 566 | return {"err": 0} 567 | # dwc rr_mkdir 568 | def rr_mkdir(self, web_): 569 | 570 | path_ = self.sdpath + web_.get_argument('dir').replace("0:", "").replace(' ', '_') 571 | 572 | if not os.path.exists(path_): 573 | os.makedirs(path_) 574 | return {'err': 0} 575 | 576 | return {'err': 1} 577 | # dwc rr_reply - fetces gcodes 578 | def rr_reply(self, web_): 579 | while self.gcode_reply: 580 | msg = self.gcode_reply.pop(0).replace("!!", "Error: ").replace("//", "Warning: ") 581 | web_.write( msg ) 582 | # rr_status_0 if klipper is down/failed to start 583 | def rr_status_0(self): 584 | 585 | # just put in things really needed to make dwc2 happy 586 | if self.status_0.get("output", {}).get("message", None) : 587 | self.status_0.update({ "output": {} }) 588 | self.message = None 589 | 590 | self.status_0.update({ 591 | "status": self.get_printer_status(), 592 | "seq": len(self.gcode_reply), 593 | "coords": { 594 | "xyz": [] , 595 | "machine": [] , 596 | "extr": [] 597 | }, 598 | "speeds": {}, 599 | "sensors": { 600 | "fanRPM": 0 601 | }, 602 | "params": { 603 | "fanPercent": [] , 604 | "extrFactors": [] 605 | } , 606 | "temps": { 607 | "bed": { "active": 0 }, 608 | "state": [], 609 | "extra": [{}], 610 | "current": [], 611 | "tools": { 612 | "active": [] 613 | }, 614 | "names": [] 615 | } , 616 | "probe": {} , 617 | "axisNames": "" , 618 | "tools": [] , 619 | "volumes": 1, 620 | "mountedVolumes": 1 , 621 | "name": self.printername 622 | }) 623 | 624 | if self.popup: 625 | self.status_0.update( 626 | self.popup 627 | ) 628 | # dwc rr_status 1 629 | def rr_status_1(self): 630 | now = self.reactor.monotonic() + 0.25 631 | 632 | extr_stat = self.get_extr_stats(now) 633 | bed_stats = self.get_bed_stats(now) 634 | gcode_stats = self.gcode.get_status(now) 635 | 636 | if self.fan: 637 | fan_stats = [ self.fan.get_status(now) ] # this can be better 638 | else: 639 | fan_stats = [] 640 | 641 | if self.status_1.get("output", {}).get("message", None) : 642 | self.status_1.update({ "output": {} }) 643 | self.message = None 644 | 645 | self.status_1.update({ 646 | "status": self.get_printer_status(), 647 | "coords": { 648 | "axesHomed": self.get_axes_homed(), 649 | "xyz": self.toolhead.get_position()[:3] , 650 | "machine": [ 0, 0, 0 ], # what ever this is? no documentation. 651 | "extr": self.toolhead.get_position()[3:] 652 | }, 653 | "speeds": { 654 | "requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] , 655 | "top": 0 # not available on klipepr 656 | }, 657 | "currentTool": self.current_tool, # must be at least 1 ! learned the hardway.... 658 | "params": { 659 | "atxPower": 0, 660 | "fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] , 661 | "speedFactor": gcode_stats['speed_factor'] * 100, 662 | "extrFactors": [ gcode_stats['extrude_factor'] * 100 ], 663 | "babystep": gcode_stats['homing_zpos'] 664 | }, 665 | "seq": len(self.gcode_reply), 666 | "sensors": { 667 | "probeValue": 0, 668 | "fanRPM": 0 669 | }, 670 | "temps": { 671 | "bed": { 672 | "current": bed_stats['actual'] , 673 | "active": bed_stats['target'] , 674 | "state": bed_stats['state'] , 675 | "heater": 0 676 | }, 677 | #"chamber": { 678 | # "current": 19.5, 679 | # "active": 0, 680 | # "state": 0, 681 | # "heater": 2 682 | #}, 683 | "current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] , 684 | "state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] , 685 | "tools": { 686 | "active": [ [ ex_['target'] ] for ex_ in extr_stat ], 687 | "standby": [ [ 0 ] for ex_ in extr_stat ] 688 | }, 689 | "extra": [ 690 | { 691 | "name": "*MCU", 692 | "temp": 0 693 | } 694 | ] 695 | }, 696 | "time": time.time() - self.start_time , 697 | #https://github.com/chrishamm/DuetWebControl/blob/92daf5d98db5def091a3f1a9d4324e1b953fc649/src/store/machine/connector/PollConnector.js#L470 698 | #"output": { 699 | # "message": "Titten!" 700 | #} 701 | #"output": { 702 | # "msgBox": { 703 | # "mode": 2, 704 | # "title": "testtitle", 705 | # "msg": "hello world", 706 | # "timeout": 5000, # can be zero? 707 | # "controls": 0 708 | # } 709 | #} # ok is M292 710 | }) 711 | 712 | if self.message: 713 | self.status_1.update( 714 | self.message 715 | ) 716 | 717 | if self.popup: 718 | self.status_1.update( 719 | self.popup 720 | ) 721 | 722 | if self.chamber: 723 | chamber_stats = self.chamber.get_status(0) 724 | self.status_1['temps'].update({ 725 | "chamber": { 726 | "current": chamber_stats.get("temp") , 727 | "active": chamber_stats.get("target", -1) , 728 | "state": chamber_stats.get("state") , 729 | "heater": 2 , # extruders + bett ? 730 | }, 731 | "current": self.status_1['temps']['current'] + [ chamber_stats.get("temp") ], 732 | "state": self.status_1['temps']['state'] + [ chamber_stats.get("state") ] , 733 | }) 734 | # dwc rr_status 2 735 | def rr_status_2(self): 736 | now = self.reactor.monotonic() + 0.25 737 | 738 | extr_stat = self.get_extr_stats(now) 739 | bed_stats = self.get_bed_stats(now) 740 | gcode_stats = self.gcode.get_status(now) 741 | if self.fan: 742 | fan_stats = [ self.fan.get_status(now) ] # this can be better 743 | else: 744 | fan_stats = [] 745 | 746 | if self.status_2.get("output", {}).get("message", None) : 747 | self.status_2.update({ "output": {} }) 748 | self.message = None 749 | 750 | # dummy data 751 | self.status_2.update({ 752 | "status": self.get_printer_status() , 753 | "coords": { 754 | "axesHomed": self.get_axes_homed() , 755 | "xyz": self.toolhead.get_position()[:3] , 756 | "machine": [ 0, 0, 0 ] , 757 | "extr": self.toolhead.get_position()[3:] 758 | }, 759 | "speeds": { 760 | "requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] , 761 | "top": 0 # not available on klipepr 762 | }, 763 | "currentTool": self.current_tool, 764 | "params": { 765 | "atxPower": 0 , 766 | "fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] , 767 | "fanNames": [ "" for fan_ in fan_stats ], 768 | "speedFactor": gcode_stats['speed_factor'] * 100, 769 | "extrFactors": [ gcode_stats['extrude_factor'] * 100 ], 770 | "babystep": gcode_stats['homing_zpos'] 771 | }, 772 | "seq": len(self.gcode_reply), 773 | "sensors": { 774 | "probeValue": 0, 775 | "fanRPM": 0 776 | }, 777 | "temps": { 778 | "bed": { 779 | "current": bed_stats['actual'] , 780 | "active": bed_stats['target'] , 781 | "state": bed_stats['state'] , 782 | "heater": 0 783 | }, 784 | #"chamber": { 785 | # "current": 19.6, 786 | # "active": 0, 787 | # "state": 0, 788 | # "heater": 2 789 | #}, 790 | "current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] , 791 | "state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] , 792 | "names": [ "Bed" ] + [ ex_['name'] for ex_ in extr_stat ] , 793 | "tools": { 794 | "active": [ [ ex_['target'] ] for ex_ in extr_stat ], 795 | "standby": [ [ 0 ] for ex_ in extr_stat ] 796 | }, 797 | "extra": [ 798 | { 799 | "name": "*MCU", 800 | "temp": 0 801 | } 802 | ] 803 | }, 804 | "time": time.time() - self.start_time, 805 | "coldExtrudeTemp": max( [ ex_['min_extrude_temp'] for ex_ in extr_stat ] + [0] ), 806 | "coldRetractTemp": max( [ ex_['min_extrude_temp'] for ex_ in extr_stat ] + [0] ), 807 | "compensation": "None", 808 | "controllableFans": len( fan_stats ), 809 | "tempLimit": max( [ ex_['max_temp'] for ex_ in extr_stat ] + [0] ), 810 | "endstops": 4088, # what does this do? 811 | "firmwareName": "Klipper", 812 | "geometry": self.kin_name, 813 | "axes": len(self.get_axes_homed()), 814 | "totalAxes": len(self.get_axes_homed()) + len( [ 1 for ex_ in extr_stat ] ), 815 | "axisNames": "XYZ", #+ "".join([ "U" for ex_ in extr_stat ]), 816 | "volumes": 1, 817 | "mountedVolumes": 1, 818 | "name": self.printername, 819 | "probe": { 820 | "threshold": 100, 821 | "height": 0, 822 | "type": 8 823 | }, 824 | "tools": [ 825 | { 826 | "number": extr_stat.index(ex_), 827 | "name": ex_['name'], 828 | "heaters": [ extr_stat.index(ex_) + 1 ] , 829 | "drives": [ extr_stat.index(ex_) ] , 830 | "axisMap": [ 1 ], 831 | "fans": 1, 832 | "filament": "", 833 | "offsets": [ 0, 0, 0 ] 834 | } for ex_ in extr_stat ] 835 | , 836 | #"mcutemp": { 837 | # "min": 30.1, 838 | # "cur": 36.8, 839 | # "max": 37 840 | #}, 841 | #"vin": { 842 | # "min": 24.2, 843 | # "cur": 24.3, 844 | # "max": 24.5 845 | #} 846 | #https://github.com/chrishamm/DuetWebControl/blob/92daf5d98db5def091a3f1a9d4324e1b953fc649/src/store/machine/connector/PollConnector.js#L470 847 | #"output": { 848 | # "message": "Titten!" 849 | #} 850 | #"output": { 851 | # "msgBox": { 852 | # "mode": 2, 853 | # "title": "testtitle", 854 | # "msg": "hello world", 855 | # "timeout": 5000, # can be zero? 856 | # "controls": 1 857 | # } 858 | #} 859 | }) 860 | 861 | if self.message: 862 | self.status_2.update( 863 | self.message 864 | ) 865 | 866 | if self.popup: 867 | self.status_2.update( 868 | self.popup 869 | ) 870 | 871 | if self.chamber: 872 | chamber_stats = self.chamber.get_status(0) 873 | self.status_2['temps'].update({ 874 | "chamber": { 875 | "current": chamber_stats.get("temp") , 876 | "active": chamber_stats.get("target", -1) , 877 | "state": chamber_stats.get("state") , 878 | "heater": 2 , # extruders + bett ? 879 | }, 880 | "current": self.status_2['temps']['current'] + [ chamber_stats.get("temp") ], 881 | "state": self.status_2['temps']['state'] + [ chamber_stats.get("state") ] , 882 | "names": self.status_2['temps']['names'] + [ "Chamber" ] 883 | }) 884 | # dwc rr_status 3 885 | def rr_status_3(self): 886 | 887 | if self.status_3.get("output", {}).get("message", None) : 888 | self.status_3.update({ "output": {} }) 889 | self.message = None 890 | 891 | now = self.reactor.monotonic() + 0.25 892 | 893 | self.extr_stat = self.get_extr_stats(now) 894 | extr_stat = self.extr_stat 895 | bed_stats = self.get_bed_stats(now) 896 | gcode_stats = self.gcode.get_status(now) 897 | if self.fan: 898 | fan_stats = [ self.fan.get_status(now) ] # this can be better 899 | else: 900 | fan_stats = [] 901 | 902 | self.status_3.update({ 903 | "status": self.get_printer_status() , 904 | "coords": { 905 | "axesHomed": self.get_axes_homed() , 906 | "xyz": self.toolhead.get_position()[:3] , 907 | "machine": [ 0, 0, 0 ] , 908 | "extr": self.toolhead.get_position()[3:] 909 | }, 910 | "speeds": { 911 | "requested": gcode_stats['speed'] / 60 * gcode_stats['speed_factor'] , 912 | "top": 0 # not available on klipepr 913 | }, 914 | "currentTool": self.current_tool , 915 | "params": { 916 | "atxPower": 0 , 917 | "fanPercent": [ fan_['speed']*100 for fan_ in fan_stats ] , 918 | "fanNames": [ "" for fan_ in fan_stats ], 919 | "speedFactor": gcode_stats['speed_factor'] * 100, 920 | "extrFactors": [ gcode_stats['extrude_factor'] * 100 ], 921 | "babystep": gcode_stats['homing_zpos'] 922 | }, 923 | "seq": len(self.gcode_reply), 924 | "sensors": { 925 | "probeValue": 0, 926 | "fanRPM": 0 927 | }, 928 | "temps": { 929 | "bed": { 930 | "current": bed_stats['actual'] , 931 | "active": bed_stats['target'] , 932 | "state": bed_stats['state'] , 933 | "heater": 0 934 | }, 935 | "current": [ bed_stats['actual'] ] + [ ex_['actual'] for ex_ in extr_stat ] , 936 | "state": [ bed_stats['state'] ] + [ ex_['state'] for ex_ in extr_stat ] , 937 | "names": [ "Bed" ] + [ ex_['name'] for ex_ in extr_stat ], 938 | "tools": { 939 | "active": [ [ ex_['target'] ] for ex_ in extr_stat ], 940 | "standby": [ [ 0 ] for ex_ in extr_stat ] 941 | }, 942 | "extra": [ 943 | { 944 | "name": "*MCU", 945 | "temp": 0 946 | } 947 | ] 948 | }, 949 | "time": time.time() - self.start_time, 950 | "currentLayer": self.print_data.get('curr_layer', 1) , 951 | "currentLayerTime": self.print_data.get('curr_layer_dur', 1), 952 | "extrRaw": [ sum([ ex_['pos'] for ex_ in extr_stat ]) - self.print_data.get('extr_start', 1) ], 953 | "fractionPrinted": self.sdcard.get_status(now).get('progress', 0) , # percent done 954 | "filePosition": self.sdcard.file_position, 955 | "firstLayerDuration": self.print_data.get('firstlayer_dur', 1) if self.print_data.get('firstlayer_dur', 0) > 0 else self.print_data.get('curr_layer_dur', 1), 956 | "firstLayerHeight": self.file_infos.get('running_file', {}).get('firstLayerHeight', 0.2), 957 | "printDuration": self.print_data.get('print_dur', 1) , 958 | "warmUpDuration": self.print_data.get('heat_time', 1), 959 | "timesLeft": { 960 | "file": self.print_data['tleft_file'], 961 | "filament": self.print_data['tleft_filament'], 962 | "layer": self.print_data['tleft_layer'] 963 | } 964 | }) 965 | 966 | if self.message: 967 | self.status_3.update( 968 | self.message 969 | ) 970 | 971 | if self.popup: 972 | self.status_3.update( 973 | self.popup 974 | ) 975 | 976 | if self.chamber: 977 | chamber_stats = self.chamber.get_status(0) 978 | self.status_3['temps'].update({ 979 | "chamber": { 980 | "current": chamber_stats.get("temp") , 981 | "active": chamber_stats.get("target", -1) , 982 | "state": chamber_stats.get("state") , 983 | "heater": 2 , # extruders + bett ? 984 | }, 985 | "current": self.status_3['temps']['current'] + [ chamber_stats.get("temp") ], 986 | "state": self.status_3['temps']['state'] + [ chamber_stats.get("state") ] , 987 | "names": self.status_3['temps']['names'] + [ "Chamber" ] 988 | }) 989 | # dwc rr_upload - uploading files to sdcard 990 | def rr_upload(self, web_): 991 | 992 | path_ = self.sdpath + web_.get_argument('name').replace("0:", "").replace(' ', '_') 993 | dir_ = os.path.dirname(path_) 994 | 995 | ret_ = {"err":1} 996 | 997 | if not os.path.exists(dir_): 998 | os.makedirs(dir_) 999 | 1000 | # klipper config ecxeption 1001 | if "/sys/" in path_ and "config.g" in web_.get_argument('name'): 1002 | path_ = self.klipper_config 1003 | 1004 | with open(path_.replace(" ","_"), 'w') as out: 1005 | out.write(web_.request.body) 1006 | 1007 | if os.path.isfile(path_): 1008 | ret_ = {"err":0} 1009 | 1010 | return ret_ 1011 | 1012 | ## 1013 | # Gcode execution related stuff 1014 | ## 1015 | 1016 | # rrf G10 command - set heaterstemp 1017 | def cmd_G10(self, params): 1018 | command_ = str("M104 T%d S%0.2f" % ( int(params['P']), int(params['S']) ) ) 1019 | return command_ 1020 | # rrf M0 - cancel print from sd 1021 | def cmd_M0(self, params): 1022 | 1023 | self.sdcard.must_pause_work = True # pause print -> sdcard postion is saved in virtual sdcard 1024 | self.sdcard.file_position = 0 # reset fileposition 1025 | self.sdcard.work_timer = None # reset worktimer 1026 | self.sdcard.current_file = None # 1027 | self.printfile = None 1028 | self.cancel_macro() 1029 | # let user define a cancel/pause print macro`? 1030 | return 0 1031 | # rrf M24 - start/resume print from sdcard 1032 | def cmd_M24(self, params): 1033 | if self.sdcard.file_position > 0: 1034 | self.resume_macro() 1035 | else: 1036 | self.print_data = { 1037 | "print_start": time.time() , 1038 | "print_dur": 0 , 1039 | "extr_start": sum(self.toolhead.get_position()[3:]) , 1040 | "firstlayer_dur": 0 , 1041 | "curr_layer": 1 , 1042 | "curr_layer_start": 0 , 1043 | "curr_layer_dur" : 0 , 1044 | "heat_time": 0 , 1045 | "last_zposes": [ self.toolhead.get_position()[3] for n_ in range(10) ] , 1046 | "last_switch_z": 0, 1047 | "tleft_file": 99999999999, 1048 | "tleft_filament": 99999999999, 1049 | "tleft_layer": 99999999999, 1050 | "layercount": self.file_infos.get('running_file', {}).get('layercount', 1), 1051 | "filament": self.file_infos.get('running_file', {}).get( "filament", 1) 1052 | } 1053 | self.reactor.register_callback(self.update_printdata, waketime=self.reactor.monotonic() + 2) 1054 | return 'M24' 1055 | # rrf M25 - pause print 1056 | def cmd_M25(self, params): 1057 | self.sdcard.do_pause() 1058 | self.pause_macro() 1059 | # rrf M32 - start print from sdcard 1060 | def cmd_M32(self, params): 1061 | 1062 | # file dwc1 - 'zzz/simplify3D41.gcode' 1063 | # file dwc2 - '/gcodes/zzz/simplify3D41.gcode' 1064 | logging.info( "this works for me" ) 1065 | file = '/'.join(params['#original'].split(' ')[1:]) 1066 | if '/gcodes/' not in file: # DWC 1 work arround 1067 | fullpath = self.sdpath + '/gcodes/' + params['#original'].split()[1] 1068 | else: 1069 | fullpath = self.sdpath + file 1070 | 1071 | # load a file to scurrent_file if its none 1072 | if not self.sdcard.current_file: 1073 | if os.path.isfile(fullpath): 1074 | self.printfile = open(fullpath, 'rb') # get file object as klippy would do 1075 | self.printfile.seek(0, os.SEEK_END) 1076 | self.printfile.seek(0) 1077 | self.sdcard.current_file = self.printfile # set it as current file 1078 | self.sdcard.file_position = 0 # postions / size 1079 | self.sdcard.file_size = os.stat(fullpath).st_size 1080 | else: 1081 | raise 'gcodefile' + fullpath + ' not found' 1082 | 1083 | self.file_infos['running_file'] = self.rr_fileinfo('knackwurst').result() 1084 | return self.cmd_M24(params) 1085 | # rrf run macro 1086 | def cmd_M98(self, params): 1087 | 1088 | path = self.sdpath + "/" + "/".join(params['#original'].split("/")[1:]) 1089 | 1090 | if not os.path.exists(path): 1091 | # now we know its no macro file 1092 | klipma = params['#original'].split("/")[-1].replace("\"", "") 1093 | if klipma in self.klipper_macros: 1094 | return klipma 1095 | else: 1096 | return 0 1097 | else: 1098 | # now we know its a macro from dwc 1099 | with open( path ) as f: 1100 | lines = f.readlines() 1101 | 1102 | for line in [x.strip() for x in lines]: 1103 | self.gcode_queue.append(line) 1104 | 1105 | return 0 1106 | # rrf M106 translation to klipper scale 1107 | def cmd_M106(self, params): 1108 | 1109 | if float(params['S']) < 1.01: 1110 | command = str( params['#command'] + " S" + str(int( float(params['S']) * 255 )) ) 1111 | else: 1112 | command = str( params['#command'] + " S" + str(int( float(params['S']) )) ) 1113 | 1114 | if float(params['S']) < .05: 1115 | command = str("M107") 1116 | 1117 | return command 1118 | # fo ecxecuting m112 now! 1119 | def cmd_M112(self, params): 1120 | self.printer.invoke_shutdown('Emergency Stop from DWC 2') 1121 | # save states butttons 1122 | def cmd_M120(self, params): 1123 | return "SAVE_GCODE_STATE NAME=DWC_BOTTON" 1124 | # restore states butttons 1125 | def cmd_M121(self, params): 1126 | return "RESTORE_GCODE_STATE NAME=DWC_BOTTON MOVE=0" 1127 | # set heatbed 1128 | def cmd_M140(self, params): 1129 | 1130 | command_ = str("M140 S%d" % ( int(params['S']) ) ) 1131 | return command_ 1132 | # setting babysteps: 1133 | def cmd_M290(self, params): 1134 | 1135 | if self.get_axes_homed()[2] == 0: 1136 | return 0 1137 | 1138 | mm_step = float( params['Z'] ) 1139 | command_ = 'SET_GCODE_OFFSET Z_ADJUST=' + str(mm_step) + ' MOVE=1' 1140 | 1141 | return command_ 1142 | # Ok button in DWC webif 1143 | def cmd_M292(self, params): 1144 | self.popup = None 1145 | # rrf restart command 1146 | def cmd_M999(self, params): 1147 | #needs0 otherwise the printer gets restarted after emergency buttn is pressed 1148 | return "RESTART" 1149 | # launch custom cancel macro 1150 | def cancel_macro(self): 1151 | macro_path = self.sdpath + '/macros/' + 'cancel.g' 1152 | 1153 | if os.path.isfile(macro_path): 1154 | 1155 | with open( macro_path ) as f: 1156 | lines = f.readlines() 1157 | 1158 | for line in [x.strip() for x in lines]: 1159 | self.gcode_queue.append(line) 1160 | 1161 | elif 'CANCEL_PRINT' in self.klipper_macros: 1162 | self.gcode_queue.append('CANCEL_PRINT') 1163 | 1164 | if self.gcode_queue: 1165 | self.reactor.register_callback(self.gcode_reactor_callback) 1166 | # getting response by callback 1167 | def gcode_response(self, msg): 1168 | 1169 | if self.klipper_ready: 1170 | if re.match('(B|T\d):\d+.\d\s/\d+.\d+', msg): return # filters tempmessages during heatup 1171 | 1172 | self.gcode_reply.append(msg) 1173 | # recall for gcode ecxecution is needed ( threadsafeness ) 1174 | def gcode_reactor_callback(self, eventtime): 1175 | 1176 | handover = self.gcode_queue 1177 | self.gcode_queue = [] 1178 | 1179 | with self.mutex: 1180 | self.gcode._process_commands( handover ) 1181 | 1182 | return eventtime 1183 | # launch individual pause macro 1184 | def pause_macro(self): 1185 | # store old XYZ position somewhere ? 1186 | macro_path = self.sdpath + '/macros/' + 'pause.g' 1187 | 1188 | if os.path.isfile(macro_path): 1189 | 1190 | with open( macro_path ) as f: 1191 | lines = f.readlines() 1192 | 1193 | for line in [x.strip() for x in lines]: 1194 | self.gcode_queue.append(line) 1195 | 1196 | elif 'PAUSE_PRINT' in self.klipper_macros: 1197 | self.gcode_queue.append('PAUSE_PRINT') 1198 | 1199 | if self.gcode_queue: 1200 | self.reactor.register_callback(self.gcode_reactor_callback) 1201 | # parses gcode commands into params -took from johns work 1202 | def parse_params(self, line, low_=False): 1203 | args_r = re.compile('([A-Z_]+|[A-Z*/])') 1204 | # Ignore comments and leading/trailing spaces 1205 | line = origline = line.strip() 1206 | cpos = line.find(';') 1207 | if cpos >= 0: 1208 | line = line[:cpos] 1209 | # Break line into parts and determine command 1210 | parts = args_r.split(line.upper()) 1211 | numparts = len(parts) 1212 | cmd = "" 1213 | if numparts >= 3 and parts[1] != 'N': 1214 | cmd = parts[1] + parts[2].strip() 1215 | elif numparts >= 5 and parts[1] == 'N': 1216 | # Skip line number at start of command 1217 | cmd = parts[3] + parts[4].strip() 1218 | # Build gcode "params" dictionary 1219 | params = { parts[i]: parts[i+1].strip() for i in range(1, numparts, 2) } 1220 | params['#original'] = origline 1221 | params['#command'] = parts[1] + parts[2].strip() 1222 | 1223 | gcmd = kgcode.GCodeCommand(self.gcode, cmd, origline, params, True) 1224 | 1225 | return params, gcmd 1226 | # launch individual resume macro 1227 | def resume_macro(self): 1228 | 1229 | macro_path = self.sdpath + '/macros/' + 'resume.g' 1230 | 1231 | if os.path.isfile(macro_path): 1232 | 1233 | with open( macro_path ) as f: 1234 | lines = f.readlines() 1235 | 1236 | for line in [x.strip() for x in lines]: 1237 | self.gcode_queue.append(line) 1238 | 1239 | elif 'RESUME_PRINT' in self.klipper_macros: 1240 | self.gcode_queue.append('RESUME_PRINT') 1241 | 1242 | if self.gcode_queue: 1243 | self.reactor.register_callback(self.gcode_reactor_callback) 1244 | 1245 | ## 1246 | # Helper functions getting/parsing data 1247 | ## 1248 | 1249 | # transforming klippers heigthmap into dwc readable format 1250 | def get_heigthmap(self): 1251 | # translates the klipper heighthmap to dwc format 1252 | # lets asume user is intelegent enough to probe with correct probe offset 1253 | def calc_mean(matrix_): 1254 | 1255 | matrix_tolist = [] 1256 | for line in matrix_: 1257 | matrix_tolist += line 1258 | 1259 | return float(sum(matrix_tolist)) / len(matrix_tolist) 1260 | 1261 | def calc_stdv(matrix_): 1262 | from math import sqrt 1263 | matrix_tolist = [] 1264 | for line in matrix_: 1265 | matrix_tolist += line 1266 | 1267 | mean = float(sum(matrix_tolist)) / len(matrix_tolist) 1268 | return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, matrix_tolist))) / len(matrix_tolist)) # Stackoverflow - liked that native short solution 1269 | 1270 | # 1271 | bed_mesh = self.printer.lookup_object('bed_mesh', None) 1272 | 1273 | if bed_mesh.z_mesh: 1274 | 1275 | hmap = [] 1276 | #z_matrix = bed_mesh.z_mesh.mesh_matrix 1277 | z_matrix = bed_mesh.z_mesh.probed_matrix 1278 | mesh_data = bed_mesh.z_mesh # see def print_mesh in bed_mesh.py line 572 1279 | 1280 | meane_ = round( calc_mean(z_matrix), 3) 1281 | stdev_ = round( calc_stdv(z_matrix) , 3) 1282 | 1283 | #import pdb; pdb.set_trace() 1284 | 1285 | hmap.append( 'RepRapFirmware height map file v2 generated at ' + str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M')) + ', mean error ' + str(meane_) + ', deviation ' + str(stdev_)) 1286 | hmap.append('xmin,xmax,ymin,ymax,radius,xspacing,yspacing,xnum,ynum') 1287 | xspace_ = ( mesh_data.mesh_x_max - mesh_data.mesh_x_min ) / mesh_data.mesh_x_count 1288 | yspace_ = ( mesh_data.mesh_y_max - mesh_data.mesh_y_min ) / mesh_data.mesh_y_count 1289 | hmap.append( str(mesh_data.mesh_x_min) + ',' + str(mesh_data.mesh_x_max) + ',' + str(mesh_data.mesh_y_min) + ',' + str(mesh_data.mesh_y_max) + \ 1290 | ',-1.00,' + str(xspace_) + ',' + str(yspace_) + ',' + str(mesh_data.mesh_x_count) + ',' + str(mesh_data.mesh_y_count) ) 1291 | 1292 | for line in z_matrix: 1293 | red_by_offset = map(lambda x: x-meane_,line) 1294 | hmap.append( ' ' + ', '.join( map(str, red_by_offset) )) 1295 | 1296 | return hmap 1297 | 1298 | else: 1299 | self.gcode.respond_info("Bed has not been probed") 1300 | 1301 | return 1302 | # delivering printer states, webif can use 1303 | def get_printer_status(self): 1304 | 1305 | # case 'F': return 'updating'; 1306 | # case 'O': return 'off'; 1307 | # case 'H': return 'halted'; 1308 | # case 'D': return 'pausing'; 1309 | # case 'S': return 'paused'; 1310 | # case 'R': return 'resuming'; 1311 | # case 'P': return 'processing'; ?printing? 1312 | # case 'M': return 'simulating'; 1313 | # case 'B': return 'busy'; 1314 | # case 'T': return 'changingTool'; 1315 | # case 'I': return 'idle'; 1316 | 1317 | state = 'I' 1318 | 1319 | if 'Printer is ready' != self.printer.get_state_message()[0]: 1320 | self.klipper_ready = False 1321 | return 'O' 1322 | 1323 | if self.gcode_io.is_processing_data: 1324 | state = 'B' 1325 | 1326 | if self.sdcard.current_file: 1327 | if self.sdcard.must_pause_work: 1328 | state = 'D' if self.sdcard.work_timer else 'S' 1329 | elif self.sdcard.current_file and self.sdcard.work_timer: 1330 | state = 'P' 1331 | 1332 | return state 1333 | # import klipper macros as virtual files 1334 | def get_klipper_macros(self): 1335 | 1336 | for key_ in self.gcode.gcode_help.keys(): 1337 | 1338 | if self.gcode.gcode_help[key_] == "G-Code macro": 1339 | 1340 | self.klipper_macros.append( key_.upper() ) 1341 | # same what gcode.py is doing 1342 | def get_axes_homed(self): 1343 | # self.toolhead.get_next_move_time() - self.reactor.monotonic() 1344 | homed = [] 1345 | stepper_names = [s.get_name() for s in self.kinematics.get_steppers()] 1346 | for name in stepper_names: 1347 | 1348 | if self.stepper_enable.lookup_enable(name).is_motor_enabled(): 1349 | homed.append(1) 1350 | else: 1351 | homed.append(0) 1352 | if not homed: 1353 | homed = [0,0,0] 1354 | return homed 1355 | # stats for extruders 1356 | def get_extr_stats(self, now): 1357 | 1358 | # position - self.extruders[0].extrude_pos 1359 | # temps - self.extruders[0].heater.get_status(self.reactor.monotonic()) - {'temperature': 21.225501996279693, 'target': 0.0} 1360 | # temps - self.extruders[0].heater.stats(self.reactor.monotonic()) 1361 | extr_stats = [] 1362 | 1363 | for ex_ in self.extruders: 1364 | 1365 | if ex_ is not None: 1366 | 1367 | status = ex_.heater.get_status(now) 1368 | 1369 | app_ = { 1370 | 'name': re.sub('\d', '', ex_.name) + str( self.extruders.index(ex_) ) , 1371 | 'pos': ex_.stepper.get_commanded_position() , 1372 | 'actual': status['temperature'] , 1373 | 'target': status['target'] , 1374 | 'state': 0 if status['target'] < 20 else 2 , 1375 | 'min_extrude_temp': ex_.heater.min_extrude_temp , 1376 | 'max_temp': ex_.heater.max_temp 1377 | } 1378 | 1379 | extr_stats.append( app_ ) 1380 | return extr_stats 1381 | # stats for a heatedbed 1382 | def get_bed_stats(self, now): 1383 | 1384 | if self.heater_bed is not None: 1385 | 1386 | # // 0: off, 1: standby, 2: active, 3: fault (same for bed) 1387 | # {'temperature': 25.99274317011324, 'target': 0.0} 1388 | status = self.heater_bed.get_status(now) 1389 | 1390 | ret_ = { 1391 | "actual": status['temperature'] , 1392 | "target": status['target'] , 1393 | "state": 0 if status['target'] < 20 else 2 1394 | } 1395 | else: 1396 | ret_ = { 1397 | "actual": 0 , 1398 | "target": 0 , 1399 | "state": 0 1400 | } 1401 | return ret_ 1402 | # read and parse gcode files 1403 | def read_gcode(self, path_, dict_): 1404 | 1405 | # looks complicated but should be good maintainable 1406 | # the heigth of all objects - regex 1407 | objects_h = [ 1408 | '\sZ\\d+.\\d*' , # kisslicer 1409 | '' , # Slic3r 1410 | '\sZ\\d+.\\d*' , # S3d 1411 | 'G1\sZ\d*\.\d*' , # Slic3r PE 1412 | '\sZ\\d+.\\d*' , # Cura 1413 | '\sZ\d+.\d{3}' , # ideamaker 1414 | 'G1\sZ\d*\.\d*' , # PrusaSlicer 1415 | 'G1\sZ\d*\.\d*' # SuperSlicer 1416 | ] 1417 | 1418 | # heigth of the first layer 1419 | first_h = [ 1420 | 'first_layer_thickness_mm\s=\s\d+\.\d+' , # kisslicers setting 1421 | '; first_layer_height =' , # Slic3r 1422 | '\sZ\\d+.\\d*' , # Simplify3d 1423 | 'G1\sZ\d*\.\d*' , # Slic3r PE 1424 | '\sZ\\d+.\\d\s' , # Cura 1425 | ';LAYER:0\n;Z:\d+.\d{3}', # ideamaker 1426 | 'G1\sZ\d*\.\d*' , # PrusaSlicer 1427 | '; first_layer_height =' # SuperSlicer 1428 | ] 1429 | 1430 | # the heigth of layers 1431 | layer_h = [ 1432 | 'layer_thickness_mm\s=\s\d+\.\d+' , # kisslicer 1433 | '' , # Slic3r 1434 | ';\s+layerHeight.*' , # S3d 1435 | '; layer_height = \d.\d+' , # Slic3r PE 1436 | ';Layer height: \d.\d+' , # Cura 1437 | ';Z:\d+.\d{3}', # ideamaker 1438 | '; layer_height = \d.\d+' , # PrusaSlicer 1439 | '; layer_height = \d.\d+' # SuperSlicer 1440 | ] 1441 | # slicers estimate print time 1442 | time_e = [ 1443 | '\s\s\d*\.\d*\sminutes' , # Kisslicer 1444 | '; estimated printing time' , # Slic3r 1445 | ';\s+Build time:.*' , # S3d 1446 | '\d+h?\s?\d+m\s\d+s' , # Slic3r PE 1447 | ';TIME:\\d+' , # Cura 1448 | ';Print Time:\s\d+\.?\d+', # ideamaker 1449 | '\d+h?\s?\d+m\s\d+s' , # PrusaSlicer 1450 | '\d+h?\s?\d+m\s\d+s' # SuperSlicer 1451 | ] 1452 | # slicers filament usage 1453 | filament = [ 1454 | 'Ext.*=.*mm' , # Kisslicer 1455 | ';.*filament used =' , # Slic3r 1456 | ';.*Filament length: \d+.*\(' , # S3d 1457 | '.*filament\sused\s=\s.*mm' , # Slic3r PE ; filament used = 1458 | ';Filament used: \d*.\d+m' , # Cura 1459 | ';Material#1 Used:\s\d+\.?\d+', # ideamaker 1460 | '.*filament\sused\s.mm.\s=\s[0-9\.]+' , # PrusaSlicer 1461 | '.*filament\sused\s.mm.\s=\s[0-9\.]+' # SuperSlicer 1462 | ] 1463 | # slicernames 1464 | slicers = [ 1465 | 'KISSlicer' , 1466 | '^Slic3r$' , 1467 | 'Simplify3D\(R\).*' , 1468 | 'Slic3r Prusa Edition\s.*\so', 1469 | 'Cura_SteamEngine.*' , 1470 | 'ideaMaker\s([0-9]*\..*,)', 1471 | 'PrusaSlicer', 1472 | 'SuperSlicer' 1473 | ] 1474 | # 1475 | meta = { "slicer": "Slicer is not implemented" } 1476 | 1477 | def calc_time(in_): 1478 | if in_ == -1: return in_ 1479 | 1480 | h_str = re.search(re.compile('(\d+(\s)?hours|\d+(\s)?h)'),in_) 1481 | m_str = re.search(re.compile('(([0-9]*\.[0-9]+)\sminutes|\d+(\s)?m)'),in_) 1482 | s_str = re.search(re.compile('(\d+(\s)?seconds|\d+(\s)?s)'),in_) 1483 | dursecs = 0 1484 | if h_str: 1485 | dursecs += float( max( re.findall('([0-9]*\.?[0-9]+)' , ''.join(h_str.group()) ) ) ) *3600 1486 | if m_str: 1487 | dursecs += float( max( re.findall('([0-9]*\.?[0-9]+)' , ''.join(m_str.group()) ) ) ) *60 1488 | if s_str: 1489 | dursecs += float( max( re.findall('([0-9]*\.?[0-9]+)' , ''.join(s_str.group()) ) ) ) 1490 | if dursecs == 0: 1491 | dursecs = float( max( re.findall('([0-9]*\.?[0-9]+)' , in_) ) ) 1492 | 1493 | return dursecs 1494 | 1495 | # read 20k bytes from each side 1496 | f_size = os.stat(path_).st_size 1497 | seek_amount = min( f_size , 20000 ) 1498 | 1499 | with open(path_, 'rb') as f: 1500 | cont_ = f.readlines(seek_amount) # gimme the first chunk 1501 | f.seek(0, os.SEEK_END) # find the end 1502 | f.seek(seek_amount*-1,os.SEEK_CUR) # back up some 1503 | cont_ = cont_+ f.readlines() # read the remainder 1504 | 1505 | pile = " ".join(cont_) 1506 | 1507 | # determine slicer 1508 | sl = -1 1509 | 1510 | for regex in slicers: 1511 | # resource gunner ? 1512 | if re.compile(regex).search(pile): 1513 | meta['slicer'] = re.search(re.compile(regex),pile).group() 1514 | sl = slicers.index(regex) 1515 | break 1516 | # only grab metadata if we found a slicer 1517 | if sl > -1 : 1518 | if objects_h[sl] != "": 1519 | try: 1520 | matches = re.findall(objects_h[sl], pile ) 1521 | meta['objects_h'] = max( [ float(mat_) for mat_ in re.findall("\d*\.\d*", ' '.join(matches) ) ] ) 1522 | except: 1523 | pass 1524 | if layer_h[sl] != "": 1525 | try: 1526 | matches = re.findall(layer_h[sl], pile ) 1527 | meta['layer_h'] = min( [ float(mat_) for mat_ in re.findall("\d*\.\d*", ' '.join(matches) ) ] ) 1528 | except: 1529 | pass 1530 | if first_h[sl] != "": 1531 | try: 1532 | matches = re.findall(first_h[sl], pile ) 1533 | meta['first_h'] = min( [ float(mat_) for mat_ in re.findall("\d*\.\d*", ' '.join(matches) ) ] ) 1534 | except: 1535 | pass 1536 | if time_e[sl] != "": 1537 | try: 1538 | matches = re.findall(time_e[sl], pile ) 1539 | meta['time_e'] = calc_time(max( matches )) # bring time to seconds 1540 | except: 1541 | pass 1542 | if filament[sl] != "": 1543 | try: 1544 | matches = re.findall(filament[sl], pile ) 1545 | meta['filament'] = max( [ float(mat_) for mat_ in re.findall("\d*\.\d*", ' '.join(matches) ) ] ) 1546 | meta['filament'] = (meta['filament'],meta['filament']*1000)[sl==4] # cura is in m -> translate 1547 | except: 1548 | pass 1549 | 1550 | else: 1551 | self.gcode_reply.append("Your Slicer is not yet implemented.") 1552 | 1553 | # put it in rrf format 1554 | repl_ = { 1555 | "size": int(os.stat(path_).st_size) , 1556 | "lastModified": str(datetime.datetime.utcfromtimestamp( os.stat(path_).st_mtime ).strftime("%Y-%m-%dT%H:%M:%S")) , 1557 | "height": float( meta.get("objects_h",1 ) ) , 1558 | "firstLayerHeight": meta.get("first_h",1 ) , 1559 | "layerHeight": float( meta.get("layer_h",1) ) , 1560 | "printTime": int( meta.get("time_e",1) ) , # in seconds 1561 | "filament": [ float( meta.get("filament",1) ) ] , # in mm 1562 | "generatedBy": str( meta.get("slicer","<< Slicer not implemented >>") ) , 1563 | "fileName": '0:' + str(path_).replace(self.sdpath, '') , 1564 | "layercount": ( float(meta.get("objects_h",1)) - meta.get("first_h",1) ) / float(meta.get("layer_h",1) ) + 1 , 1565 | "err": 0 1566 | } 1567 | 1568 | dict_.put(repl_) 1569 | # setting message 1570 | def set_message(self, msg='msg'): 1571 | self.message = { 1572 | "output": { 1573 | "message": msg 1574 | } 1575 | } 1576 | # setting up a popup 1577 | def set_popup(self, title='Action failed ', msg='Some command just failed.', timeout=0): 1578 | self.popup = { "output": { 1579 | "msgBox": { 1580 | "mode": 2, 1581 | "title": title + str(time.time()) , 1582 | "msg": msg, 1583 | "timeout": timeout, 1584 | "controls": 0 1585 | } 1586 | } # ok is M292 1587 | } 1588 | # permanent loop if we are in printing state 1589 | def update_printdata(self, eventtime): 1590 | if self.get_printer_status() in ['S', 'P', 'D']: 1591 | self.reactor.register_callback(self.update_printdata, waketime=self.reactor.monotonic() + 0.6) 1592 | else: 1593 | return 1594 | now = self.reactor.monotonic() 1595 | 1596 | gcode_stats = self.gcode.get_status(now) 1597 | # first out, actual in - a rolling list 1598 | self.print_data['last_zposes'].pop(0) 1599 | self.print_data['last_zposes'].append(gcode_stats['last_zpos']) 1600 | self.print_data['filament_used'] = max( sum(self.toolhead.get_position()[3:]) - self.print_data['extr_start'], 1) 1601 | 1602 | if self.print_data['curr_layer_start'] == 0 \ 1603 | and self.print_data['filament_used'] > 50: 1604 | # now we know firstlayer started + heating ended 1605 | self.print_data.update({ 1606 | 'curr_layer_start': time.time() , 1607 | 'heat_time': time.time() - self.print_data.get('print_start', 0) , 1608 | 'last_switch_z': gcode_stats['last_zpos'] 1609 | }) 1610 | 1611 | else: 1612 | if self.print_data['last_switch_z'] != gcode_stats['last_zpos'] and self.print_data['filament_used'] > 50 \ 1613 | and (min( self.print_data.get('last_zposes', [2]) )+1) / (max( self.print_data.get('last_zposes', [1]) )+1) == 1 : 1614 | 1615 | if self.print_data['firstlayer_dur'] == 0: 1616 | self.print_data['firstlayer_dur'] = self.print_data['curr_layer_dur'] 1617 | self.print_data.update({ 1618 | 'curr_layer_start': time.time() , 1619 | 'curr_layer_dur': 0 , 1620 | 'curr_layer': self.print_data['curr_layer'] + 1 , 1621 | 'last_switch_z': gcode_stats['last_zpos'] 1622 | }) 1623 | 1624 | 1625 | if self.print_data['curr_layer_start'] == 0: 1626 | self.print_data['curr_layer_dur'] = 0 1627 | else: 1628 | self.print_data['curr_layer_dur'] = time.time() - self.print_data['curr_layer_start'] 1629 | 1630 | self.print_data['print_dur'] = time.time() - self.print_data['print_start'] 1631 | # timeleft calc 1632 | t_elapsed = self.print_data['print_dur'] 1633 | file_done = self.sdcard.get_status(now).get('progress', 0) 1634 | self.print_data['tleft_file'] = (1-file_done) * t_elapsed / max(.0001, file_done) 1635 | # 1636 | layer_done = self.print_data['curr_layer'] 1637 | self.print_data['tleft_layer'] = ( self.print_data['layercount'] - layer_done ) * t_elapsed / layer_done 1638 | # 1639 | f_need = sum(self.print_data['filament']) 1640 | f_used = max( sum(self.toolhead.get_position()[3:]) - self.print_data['extr_start'], 1) 1641 | self.print_data['tleft_filament'] = ( f_need - f_used ) * t_elapsed / f_used 1642 | 1643 | def dict_compare(self, d1, d2): 1644 | 1645 | # self.dict_compare( self.status_1 , self.status_2 ) 1646 | for key_ in d1.keys(): 1647 | 1648 | if d1.get(key_) != d2.get(key_) : 1649 | 1650 | print( key_ + " is different in d2.:\nd1:") 1651 | print( json.dumps(d1.get(key_)) ) 1652 | print("vs d2 :") 1653 | print( json.dumps(d2.get(key_)) ) 1654 | print("\n") 1655 | 1656 | def load_config(config): 1657 | return web_dwc2(config) 1658 | --------------------------------------------------------------------------------