diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 61f5b2c..60a0921 100644 --- a/README.md +++ b/README.md @@ -1,151 +1,198 @@ -# OctoPrint-Enclosure - -**Control pretty much everything that you might want to do on your raspberry pi / octoprint / enclosure** - -Here is a list of possibilities: -* Temperature sensor on your enclosure or near your printer -* Heater on your enclosure and keep the temperature nice and high for large ABS -* Active cooling for good PLA printing -* Mechanical buttons to pause and resume printer jobs -* Multiple filament sensors for dual or more extrusion -* Alarm when enclosure temperature reaches some sort of value - -Find the plugin useful? Buy me a coffe. -[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/VitorHenrique/2) - -Check pictures and more information on thingiverse: http://www.thingiverse.com/thing:2245493 - -**Software** - -Install the plugin using the Plugin Manager bundled with OctoPrint, you can search for the Enclosure plugin or just use the url: https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/master.zip. - -To control the encosure temperature or get temperature trigged events, you need to install and configure a temperature sensor. This plugin can support DHT11, DHT22, AM2302, DS18B20, SI7021, BME280 and TMP102 temperature sensors. - -* For the DHT11, DHT22 and AM2302 follow this steps: - -Wire the sensor following the wiring diagram on the pictures on thingiverse, you can use any GPIO pin. - -For DHT11 and DHT22 sensors, don't forget to connect a 4.7K - 10K resistor from the data pin to VCC. Also, be aware that DHT sensors some times can not work reliably on linux, this is a limitation of reading DHT sensors from Linux--there's no guarantee the program will be given enough priority and time by the Linux kernel to reliably read the sensor. Another common issue is the power supply. you need a constant and good 3.3V, sometimes a underpowered raspberry pi will not have a solid 3.3V power supply, so you could try powering the sensor with 5V and using a level shifter on the read pin. - -You need to install Adafruit library to use the temperature sensor on raspberry pi. - -Open raspberry pi terminal and type: - -
cd ~
-git clone https://github.com/adafruit/Adafruit_Python_DHT.git
-cd Adafruit_Python_DHT
-sudo apt-get update
-sudo apt-get install build-essential python-dev python-openssl
-sudo python setup.py install
- -You can test the library by using: - -
cd examples
-sudo ./AdafruitDHT.py 2302 4
- -Note that the first argument is the temperature sensor (11, 22, or 2302), and the second argument is the GPIO that the sensor was connected. - -* For the DS18B20 sensor: - -Follow the wiring diagram on the pictures on thingiverse. The DS18B20 uses "1-wire" communication protocol, you need to use 4.7K to 10K resistor from the data pin to VCC, DS18B20 only works on GPIO pin number 4. You also need to add OneWire support for your raspberry pi. - -Start by adding the following line to /boot/config.txt - -
dtoverlay=w1-gpio
- -You should be able to test your sensor by rebooting your system with sudo reboot. When the Pi is back up and you're logged in again, type the commands you see below into a terminal window. When you are in the 'devices' directory, the directory starting '28-' may have a different name, so cd to the name of whatever directory is there. - -
sudo modprobe w1-gpio
-sudo modprobe w1-therm
-cd /sys/bus/w1/devices
-ls
-cd 28-xxxx (change this to match what serial number pops up)
-cat w1_slave
- -The response will either have YES or NO at the end of the first line. If it is yes, then the temperature will be at the end of the second line, in 1/000 degrees C. - -* GPIO - -This release uses RPi.GPIO to control IO of raspberry pi, it should install and work automatically. If it doesn't please update your octoprint with the latest release of octopi. - -**Hardware** - -You can use relays / mosfets to control you lights, heater, lockers etc... If toy want to control mains voltage I recomend using PowerSwitch Tail II. - -* Relay - -The relays module that I used can be found [here](https://www.amazon.com/gp/product/B0057OC6D8?psc=1&redirect=true&ref_=oh_aui_search_detailpage). Those relays are active low, that means that they will turn on when you put LOW on the output of your pin. In order to not fry your Raspberry Pi pay attention on your wiring connection: remove the jumper link and connect 3.3v to VCC, 5V to JD-VCC and Ground to GND. - -* Heater - -For heating my enclosure I got a $15 lasko inside my enclosure. I opened it and added a relay to the mains wire. If you’re uncomfortable soldering or dealing with high voltage, please check out the [PowerSwitch Tail II](http://www.powerswitchtail.com/Pages/default.aspx) . The PowerSwitch Tail II is fully enclosed, making it a lot safer. - -**CAUTION: VOLTAGE ON MAINS WIRE CAN KILL YOU, ONLY ATTEMPT TO DO THIS IF YOU KNOW WHAT YOU ARE DOING, AND DO AT YOUR OWN RISK** - -**CAUTION 2: THIS HEATER IS NOT INTENDED TO FUNCTION THIS WAY AND IT MIGHT BE A FIRE HAZARD. DO IT AT YOUR OWN RISK** - -* Cooler - -You can get a [5V small fan](https://www.amazon.com/gp/product/B003FO0LG6/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) and control it over a relay. - -* Filament sensor - -You have the ability to add a filament sensor to the enclosure, it will automatically pause the print and run a gcode command to change the filament if you run out of filament, I can be any type of filament sensor, the sensor should connect to ground if is set as an "active low" when the filament run out or 3.3v if the sensor is set as "active high" when detected the end of filament, it does not matter if it is normally open or closed, that will only interfere on your wiring. I'm using the following sensor: - -http://www.thingiverse.com/thing:1698397 - -**Configuration** - -You need to enable what do you want the plugin to control. - -Open the setting screen and find the plugin configuration. You can enable temperature reading and temperature control, You must select the type of sensor that you are using and the GPIO pin that is connected to. - -For temperature control you can enable automatically starting up the temperature control once the print starts with a set temperature. - -Outputs are meant to control anything, lights, locker, extra enclosure fans etc... You can even use a PowerSwitch Tail II and completely shut down your printer after the print job is done. You can add delays and automatically start and shutdown the GPIO. - -Inputs have basically three different types: - -* Temperature -* Printer -* GPIO - -Temperature inputs will control a GPIO output after a certain temperature is met. This is useful if you want to add some sort of alarm near your printer, or even build some fire extinguisher on your enclosure. Note that I'm not responsible for any damage caused by fires, you should have proper smoke detectors on your house installed by professionals. - -Printer inputs will trigger Printer actions when the configured GPIO receives a signal. The actions can be Resume and Pause a print job or Change Filament. You can use the "change filament" action and set up the input GPIO according to your filament sensor, for example, if your filament sensor connects to ground when detects the end of the filament, you should choose PULL UP resistors and detect the event on the falling edge. -You can also add mechanical buttons to pause, resume and change filaments near or printer for convenience. - -GPIO events will control GPIO outputs when a condition is met, for example detect a press of a button. -You can use this to control any previous configured OUTPUTS, basically being able to control your lights / fan using mechanical buttons instead of the octoprint interface. - -**Road map** -There are still SOME features that I'll add to this plugin: -* Control neopixels \ dotstart -* Enable GCODE control for each setting - -Let me know about improvements that you might think. - -**Tab Order** - -I often use more this plugin than the time lapse tab, so having the plugin appear before the timelapse is better for me. - -You can do this by changing the config.yaml file as instructed on [octoprint documentation ](http://docs.octoprint.org/en/master/configuration/config_yaml.html). Unless defined differently via the command line config.yaml is located at ~/.octoprint. - -You just need to add the following section: - -``` -appearance: - components: - order: - tab: - - temperature - - control - - gcodeviewer - - terminal - - plugin_enclosure -      - timelapse -``` - - - - +# OctoPrint-Enclosure + +**Control pretty much everything that you might want to do on your raspberry pi / octoprint / enclosure** + +Here is a list of possibilities: +* Add temperature sensors on your enclosure or near your printer +* Add active heaters on your enclosure and keep the temperature nice and high for large ABS +* PWM controlled outputs +* PWM controlled outputs based on temperature sensor +* Active cooling for good PLA printing +* Schedule GPIO's to turn on and off with a fixed period of time during printing. +* Mechanical buttons to pause and resume printer jobs +* Mechanical buttons to send GCODE to the printer +* Mechanical buttons to control raspberry pi GPIO +* Multiple filament sensors for dual or more extruders +* Alarm when enclosure temperature reaches some sort of value +* Notifications using IFTTT when events happen (temperature trigger / print events / etc) +* Add sub-menus on navbar to quick access outputs and temperature sensors + +Find the plugin useful? Buy me a coffee +[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/VitorHenrique/2) + +Having problems with the plugin? check the [troubleshooting guide](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/Troubleshooting-Guide) + +Check pictures on thingiverse: http://www.thingiverse.com/thing:2245493 + +**Software** + +Install the plugin using the Plugin Manager bundled with OctoPrint, you can search for the Enclosure plugin or just use the url: https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/master.zip. + +To control the encosure temperature or get temperature trigged events, you need to install and configure a temperature sensor. This plugin can support DHT11, DHT22, AM2302, DS18B20, SI7021, BME280 and TMP102 temperature sensors. + +* For the DHT11, DHT22 and AM2302 follow this steps: + +Wire the sensor following the wiring diagram on the pictures on thingiverse, you can use any GPIO pin. + +For DHT11 and DHT22 sensors, don't forget to connect a 4.7K - 10K resistor from the data pin to VCC. Also, be aware that DHT sensors some times can not work reliably on linux, this is a limitation of reading DHT sensors from Linux--there's no guarantee the program will be given enough priority and time by the Linux kernel to reliably read the sensor. Another common issue is the power supply. you need a constant and good 3.3V, sometimes a underpowered raspberry pi will not have a solid 3.3V power supply, so you could try powering the sensor with 5V and using a level shifter on the read pin. + +You need to install Adafruit library to use the temperature sensor on raspberry pi. + +Open raspberry pi terminal and type: + +
cd ~
+git clone https://github.com/adafruit/Adafruit_Python_DHT.git
+cd Adafruit_Python_DHT
+sudo apt-get update
+sudo apt-get install build-essential python-dev python-openssl
+sudo python setup.py install
+ +You can test the library by using: + +
cd examples
+sudo ./AdafruitDHT.py 2302 4
+ +Note that the first argument is the temperature sensor (11, 22, or 2302), and the second argument is the GPIO that the sensor was connected. + +* For the DS18B20 sensor: + +Follow the wiring diagram on the pictures on thingiverse. The DS18B20 uses "1-wire" communication protocol, you need to use 4.7K to 10K resistor from the data pin to VCC, DS18B20 only works on GPIO pin number 4 by default. You also need to add OneWire support for your raspberry pi. + +Start by adding the following line to /boot/config.txt + +
dtoverlay=w1-gpio
+ +You should be able to test your sensor by rebooting your system with sudo reboot. When the Pi is back up and you're logged in again, type the commands you see below into a terminal window. When you are in the 'devices' directory, the directory starting '28-' may have a different name, so cd to the name of whatever directory is there. + +
sudo modprobe w1-gpio
+sudo modprobe w1-therm
+cd /sys/bus/w1/devices
+ls
+cd 28-xxxx (change this to match what serial number pops up)
+cat w1_slave
+ +The response will either have YES or NO at the end of the first line. If it is yes, then the temperature will be at the end of the second line, in 1/000 degrees C. + +Copy the serial number, you will need to configure the plugin + +* For the SI7021, BME280 and TMP102 sensors + +Enable I2C on your raspberry pi, depending on raspi-config version, step by step can be different: + +
Run sudo raspi-config
+Use the down arrow to select 9 Advanced Options
+Arrow down to A7 I2C
+Select yes when it asks you to enable I2C
+Also select yes when it asks about automatically loading the kernel module
+Use the right arrow to select the button
+Select yes when it asks to reboot
+
+ +Install some packages: + +
sudo apt-get install i2c-tools python-pip
+ +Find the address of the sensor: + +
i2cdetect -y 1
+ +* GPIO + +This release uses RPi.GPIO to control IO of raspberry pi, it should install and work automatically. If it doesn't please update your octoprint with the latest release of octopi. + +**Hardware** + +You can use relays / mosfets to control you lights, heater, lockers etc... If you want to control mains voltage I recommend using PowerSwitch Tail II. + +* Relay + +The relays module that I used can be found [here](https://www.amazon.com/gp/product/B0057OC6D8?psc=1&redirect=true&ref_=oh_aui_search_detailpage). Those relays are active low, that means that they will turn on when you put LOW on the output of your pin. In order to not fry your Raspberry Pi pay attention on your wiring connection: remove the jumper link and connect 3.3v to VCC, 5V to JD-VCC and Ground to GND. + +* Heater + +For heating my enclosure I got a $15 lasko inside my enclosure. I opened it and added a relay to the mains wire. If you’re uncomfortable soldering or dealing with high voltage, please check out the [PowerSwitch Tail II](http://www.powerswitchtail.com/Pages/default.aspx) . The PowerSwitch Tail II is fully enclosed, making it a lot safer. + +**CAUTION: VOLTAGE ON MAINS WIRE CAN KILL YOU, ONLY ATTEMPT TO DO THIS IF YOU KNOW WHAT YOU ARE DOING, AND DO AT YOUR OWN RISK** + +**CAUTION 2: THIS HEATER IS NOT INTENDED TO FUNCTION THIS WAY AND IT MIGHT BE A FIRE HAZARD. DO IT AT YOUR OWN RISK** + +* Cooler + +You can get a [5V small fan](https://www.amazon.com/gp/product/B003FO0LG6/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) and control it over a relay. + +* Filament sensor + +You have the ability to add a filament sensor to the enclosure, it will automatically pause the print and run a gcode command to change the filament if you run out of filament, I can be any type of filament sensor, the sensor should connect to ground if is set as an "active low" when the filament run out or 3.3v if the sensor is set as "active high" when detected the end of filament, it does not matter if it is normally open or closed, that will only interfere on your wiring. I'm using the following sensor: + +http://www.thingiverse.com/thing:1698397 + +**Configuration** + +You need to enable what do you want the plugin to control. Settings from plugin version < 3.6 are not compatible anymore, you will loose all settings after upgrading the plugin. + +There are mainly two types of configuration on the plugin, Inputs and Outputs. + +Outputs are meant to control THINGS (temperature, lights, locker, extra enclosure fans etc...) You can even use a PowerSwitch Tail II and completely shut down your printer after the print job is done. + +Outputs can be set to the following types: + +* Regular GPIO +* PWM GPIO +* Neopixel Control via Microcontroler +* Neopixel Control directly from raspberry pi +* Temperature and Humidity Control +* Temperature Alarm +* Gcode Output + +Most outputs create UI elements on enclosure plugin tab that let you set values / turn on or off gpios etc. You have the ability to automatically turn on or off outputs when the printer starts or finishes. You can even specify a hour on HH:MM 24 hour format, events will only be schedule when the print starts, and will only be triggered for the very next time that hour occur. + +Temperature Alarm will control another GPIO output after a certain temperature is met. This is useful if you want to add some sort of alarm near your printer, or even build some fire extinguisher on your enclosure. Note that I'm not responsible for any damage caused by fires, you should have proper smoke detectors on your house installed by professionals. + +Inputs are methods that trigger actions or input values to the plugin (temperature sensor, GPIO trigger) + +Inputs can be of two different types: + +* Temperature Sensors +* GPIO + +Temperature Sensors will be used to input temperature and humidity data, they can be linked to a especial output like temperature control and temperature alarm. + +GPIO inputs will trigger events for the plugin, this feature can be used to add buttons to the enclosure and cause pressing those buttons to act on the printer or other pre-configured outputs. + +After selecting GPIO for the input type, and selecting output control on the action type, the button will be able to turn on / off or toggle linked regular outputs, basically being able to control your lights / fan using mechanical buttons instead of the octoprint interface. You can also use buttons to send g-code commands. + +Selecting print control on the action type will trigger printer actions when the configured GPIO receives a signal. The actions can be Resume and Pause a print job or Change Filament. You can use the "change filament" action and set up the input GPIO according to your filament sensor, for example, if your filament sensor connects to ground when detects the end of the filament, you should choose PULL UP resistors and detect the event on the falling edge. +You can also add mechanical buttons to pause, resume and change filaments near your printer for convenience. + +**Advanced Area** + +If you want to enable notifications check the following [issue](https://github.com/vitormhenrique/OctoPrint-Enclosure/issues/36) + +You can control outputs using a simple [API](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/API-Control) + +Or use [g-code](https://github.com/vitormhenrique/OctoPrint-Enclosure/wiki/G-CODE-Control) commands + +**Tab Order** + +I often use more this plugin than the time-lapse tab, so having the plugin appear before the timelapse is better for me. + +You can do this by changing the config.yaml file as instructed on [octoprint documentation ](http://docs.octoprint.org/en/master/configuration/config_yaml.html). Unless defined differently via the command line config.yaml is located at ~/.octoprint. + +You just need to add the following section: + +``` +appearance: + components: + order: + tab: + - temperature + - control + - gcodeviewer + - terminal + - plugin_enclosure +      - timelapse +``` + + + + diff --git a/extras/octoprint_neopixel/octoprint_neopixel.ino b/extras/octoprint_neopixel/octoprint_neopixel.ino index 67ecd8e..d35c4a1 100644 --- a/extras/octoprint_neopixel/octoprint_neopixel.ino +++ b/extras/octoprint_neopixel/octoprint_neopixel.ino @@ -30,7 +30,7 @@ bool gotData = false; int command = 0; int neopixelPin = 0; int neopixelLeds = 0; -int neopixelBrightness = 0; +int neopixel_brightness = 0; int redValue = 0; int greenValue = 0; int blueValue = 0; @@ -51,8 +51,8 @@ void receiveEvent(int byteCount){ DEBUG_PRINTLN(neopixelLeds); DEBUG_PRINT("BRIGHTNESS "); - neopixelBrightness = Wire.read(); - DEBUG_PRINTLN(neopixelBrightness); + neopixel_brightness = Wire.read(); + DEBUG_PRINTLN(neopixel_brightness); DEBUG_PRINT("RED "); redValue = Wire.read(); @@ -75,7 +75,7 @@ void setup() { Wire.begin(I2CADDRESS); #ifdef DEBUG Serial.begin(115200); - while (!Serial) ; + while (!Serial); Serial.println("Debuging..."); #endif Wire.onReceive(receiveEvent); @@ -85,7 +85,7 @@ void loop() { if(gotData){ strip.setPin(neopixelPin); - strip.setBrightness(neopixelBrightness); + strip.setBrightness(neopixel_brightness); strip.updateLength(neopixelLeds); strip.updateType(LED_TYPE); strip.begin(); diff --git a/octoprint_enclosure/__init__.py b/octoprint_enclosure/__init__.py index 1355134..c12cadc 100644 --- a/octoprint_enclosure/__init__.py +++ b/octoprint_enclosure/__init__.py @@ -6,615 +6,1064 @@ from subprocess import Popen, PIPE import octoprint.plugin import RPi.GPIO as GPIO import flask -import sched import time import sys import glob import os -import datetime +from datetime import datetime +from datetime import timedelta import octoprint.util import requests +import inspect +import threading +import json -scheduler = sched.scheduler(time.time, time.sleep) class EnclosurePlugin(octoprint.plugin.StartupPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.EventHandlerPlugin): - - previousTempControlStatus = False - currentTempControlStatus = False - enclosureSetTemperature=0.0 - enclosureCurrentTemperature=0.0 - enclosureCurrentHumidity=0.0 - lastFilamentEndDetected=0 - temperature_reading = [] - temperature_control = [] + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.EventHandlerPlugin): rpi_outputs = [] rpi_inputs = [] - previous_rpi_outputs = [] + waiting_temperature = [] + rpi_outputs_not_changed = [] notifications = [] + pwm_intances = [] + event_queue = [] + temp_hum_control_status = [] + temperature_sensor_data = [] + last_filament_end_detected = [] + print_complete = False - PWM_INSTANCES = [] - disable_temeprature_log = True + def start_timer(self): + """ + Function to start timer that checks enclosure temperature + """ - def startTimer(self): - self._checkTempTimer = RepeatedTimer(10, self.checkEnclosureTemp, None, None, True) - self._checkTempTimer.start() + self._check_temp_timer = RepeatedTimer( + 10, self.check_enclosure_temp, None, None, True) + self._check_temp_timer.start() + + @staticmethod + def to_float(value): + """Converts value to flow + + Arguments: + value {any} -- value to be + + Returns: + float -- value converted + """ - def toFloat(self, value): try: val = float(value) return val except: return 0 - def toInt(self, value): + @staticmethod + def to_int(value): try: val = int(value) return val except: return 0 - #~~ StartupPlugin mixin - def on_after_startup(self): + @staticmethod + def is_hour(value): + try: + datetime.strptime(value, '%H:%M') + return True + except: + return False - self.PWM_INSTANCES = [] - self.temperature_reading = self._settings.get(["temperature_reading"]) - self.temperature_control = self._settings.get(["temperature_control"]) + @staticmethod + def create_date(value): + temp_string = datetime.now().strftime( + '%m/%d/%Y') + " " + value + return datetime.strptime(temp_string, '%m/%d/%Y %H:%M') + + @staticmethod + def constrain(n, minn, maxn): + return max(min(maxn, n), minn) + + @staticmethod + def get_gcode_value(command_string, gcode): + semicolon = command_string.find(';') + if not semicolon == -1: + command_string = command_string[:semicolon] + + for command in command_string.split(' '): + index = command.upper().find(gcode.upper()) + if not index == -1: + return command.replace(gcode, '').upper() + return -1 + + # ~~ StartupPlugin mixin + def on_after_startup(self): + self.pwm_intances = [] + self.event_queue = [] + self.rpi_outputs_not_changed = [] self.rpi_outputs = self._settings.get(["rpi_outputs"]) self.rpi_inputs = self._settings.get(["rpi_inputs"]) self.notifications = self._settings.get(["notifications"]) - self.fixData() - self.previous_rpi_outputs = [] - self.startTimer() - self.startGPIO() - # self.clearGPIO() - self.configureGPIO() - self.updateOutputUI() + self.generate_temp_hum_control_status() + self.setup_gpio() + self.configure_gpio() + self.update_ui() + self.start_outpus_with_server() + self.start_timer() + self.print_complete = False - #~~ Blueprintplugin mixin - @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTemperature", methods=["GET"]) - def setEnclosureTemperature(self): - self.enclosureSetTemperature = flask.request.values["enclosureSetTemp"] - if self._settings.get(["debug"]) == True: - self._logger.info("DEBUG -> Seting enclosure temperature: %s",self.enclosureSetTemperature) - self.handleTemperatureControl() - return flask.jsonify(enclosureSetTemperature=self.enclosureSetTemperature,enclosureCurrentTemperature=self.enclosureCurrentTemperature) + def get_settings_version(self): + return 4 - @octoprint.plugin.BlueprintPlugin.route("/getEnclosureSetTemperature", methods=["GET"]) - def getEnclosureSetTemperature(self): - return str(self.enclosureSetTemperature) + def on_settings_migrate(self, target, current=None): + self._logger.warn("######### settings not compatible #########") + self._logger.warn("######### current settings version %s target settings version %s #########", + current, target) + self._settings.set(["rpi_outputs"], []) + self._settings.set(["rpi_inputs"], []) + self.rpi_outputs = self._settings.get(["rpi_outputs"]) + self.rpi_inputs = self._settings.get(["rpi_inputs"]) + + # ~~ Blueprintplugin mixin + @octoprint.plugin.BlueprintPlugin.route("/setEnclosureTempHum", methods=["GET"]) + def set_enclosure_temp_humidity(self): + set_value = self.to_float( + flask.request.values["set_temperature"]) + index_id = self.to_int(flask.request.values["index_id"]) + + for temp_hum_control in [item for item in self.rpi_outputs if item['index_id'] == index_id]: + temp_hum_control['temp_ctr_set_value'] = set_value + + self.handle_temp_hum_control() + return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/clearGPIOMode", methods=["GET"]) - def clearGPIOMode(self): + def clear_gpio_mode(self): GPIO.cleanup() return flask.jsonify(success=True) - @octoprint.plugin.BlueprintPlugin.route("/getUpdateBtnStatus", methods=["GET"]) - def getUpdateBtnStatus(self): - self.updateOutputUI() - return flask.make_response("Ok.", 200) + @octoprint.plugin.BlueprintPlugin.route("/updateUI", methods=["GET"]) + def update_ui_requested(self): + self.update_ui() + return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/getOutputStatus", methods=["GET"]) - def getOutputStatus(self): - getOutputStatusresult = '' + def get_output_status(self): + gpio_status = [] for rpi_output in self.rpi_outputs: - pin = self.toInt(rpi_output['gpioPin']) - if rpi_output['outputType']=='regular': - val = GPIO.input(pin) if not rpi_output['activeLow'] else (not GPIO.input(pin)) - if getOutputStatusresult: - getOutputStatusresult = getOutputStatusresult + ', ' - getOutputStatusresult = getOutputStatusresult + '"' + str(pin) + '": ' + str(val).lower() - return '{' + getOutputStatusresult + '}' - - - @octoprint.plugin.BlueprintPlugin.route("/getEnclosureTemperature", methods=["GET"]) - def getEnclosureTemperature(self): - return str(self.enclosureCurrentTemperature) + if rpi_output['output_type'] == 'regular': + pin = self.to_int(rpi_output['gpio_pin']) + val = GPIO.input(pin) if not rpi_output['active_low'] else ( + not GPIO.input(pin)) + index = self.to_int(rpi_output['index_id']) + # result.append(dict(index_id=rpi_output['index_id'], value=val)) + gpio_status.append(dict(index_id=index, status=val)) + return flask.Response(json.dumps(gpio_status), mimetype='application/json') @octoprint.plugin.BlueprintPlugin.route("/setIO", methods=["GET"]) - def setIO(self): - io = flask.request.values["io"] - value = True if flask.request.values["status"] == "on" else False + def set_io(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False for rpi_output in self.rpi_outputs: - if self.toInt(io) == self.toInt(rpi_output['gpioPin']): - val = (not value) if rpi_output['activeLow'] else value - self.writeGPIO(self.toInt(io), val) + if self.to_int(index) == self.to_int(rpi_output['index_id']): + val = (not value) if rpi_output['active_low'] else value + self.write_gpio(self.to_int(rpi_output['gpio_pin']), val) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/setAutoStartUp", methods=["GET"]) + def set_auto_startup(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + + if not value: + sufix = 'auto_startup' + queue_id = '{0!s}_{1!s}'.format(index, sufix) + self.stop_queue_item(queue_id) + for output in self.rpi_outputs: + if self.to_int(index) == self.to_int(output['index_id']): + output['auto_startup'] = value + self._logger.info( + "Setting auto startup for output %s to : %s", index, value) + self._settings.set(["rpi_outputs"], self.rpi_outputs) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/setAutoShutdown", methods=["GET"]) + def set_auto_shutdown(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + + if not value: + sufix = 'auto_shutdown' + queue_id = '{0!s}_{1!s}'.format(index, sufix) + self.stop_queue_item(queue_id) + + for output in self.rpi_outputs: + if self.to_int(index) == self.to_int(output['index_id']): + output['auto_shutdown'] = value + self._logger.info( + "Setting auto shutdown for output %s to : %s", index, value) + self._settings.set(["rpi_outputs"], self.rpi_outputs) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/setFilamentSensor", methods=["GET"]) + def set_filament_sensor(self): + index = flask.request.values["index_id"] + value = True if flask.request.values["status"] == 'true' else False + for sensor in self.rpi_inputs: + if self.to_int(index) == self.to_int(sensor['index_id']): + sensor['filament_sensor_enabled'] = value + self._logger.info( + "Setting filament sensor for input %s to : %s", index, value) + self._settings.set(["rpi_inputs"], self.rpi_inputs) return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setPWM", methods=["GET"]) - def setPWM(self): - io = flask.request.values["io"] - pwmVal = flask.request.values["pwmVal"] - self.writePWM(self.toInt(io),self.toInt(pwmVal)) - return flask.make_response("Ok.", 200) + def set_pwm(self): + set_value = self.to_int(flask.request.values["new_duty_cycle"]) + index_id = self.to_int(flask.request.values["index_id"]) + for rpi_output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: + rpi_output['duty_cycle'] = set_value + rpi_output['new_duty_cycle'] = "" + gpio = self.to_int(rpi_output['gpio_pin']) + self.write_pwm(gpio, set_value) + return flask.jsonify(success=True) + + @octoprint.plugin.BlueprintPlugin.route("/sendGcodeCommand", methods=["GET"]) + def requested_gcode_command(self): + gpio_index = self.to_int(flask.request.values["index_id"]) + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( + r_out['index_id']) == gpio_index].pop() + self.send_gcode_command(rpi_output['gcode']) + return flask.jsonify(success=True) @octoprint.plugin.BlueprintPlugin.route("/setNeopixel", methods=["GET"]) - def setNeopixel(self): - io = flask.request.values["io"] + def set_neopixel(self): + """ set_neopixel method get request from octoprint and send the comand to arduino or neopixel""" + gpio_index = self.to_int(flask.request.values["index_id"]) red = flask.request.values["red"] green = flask.request.values["green"] blue = flask.request.values["blue"] for rpi_output in self.rpi_outputs: - if self.toInt(io) == self.toInt(rpi_output['gpioPin']) and rpi_output['outputType']=='neopixel': - ledCount = rpi_output['neopixelCount'] - ledBrightness = rpi_output['neopixelBrightness'] - address = rpi_output['microAddress'] - self.sendNeopixelCommand(io,ledCount,ledBrightness,red,green,blue,address) - return flask.make_response("Ok.", 200) + if gpio_index == self.to_int(rpi_output['index_id']): + led_count = rpi_output['neopixel_count'] + led_brightness = rpi_output['neopixel_brightness'] + address = rpi_output['microcontroller_address'] - #~~ Plugin Internal methods - def fixData(self): - for rpi_output in self.rpi_outputs: - if not 'outputType' in rpi_output: - rpi_output['outputType'] = 'regular' - if not 'frequency' in rpi_output: - rpi_output['frequency'] = 50 - if not 'dutycycle' in rpi_output: - rpi_output['dutycycle'] = 0 - if not 'color' in rpi_output: - rpi_output['color'] = 'rgb(255,0,0)' - if not 'neopixelCount' in rpi_output: - rpi_output['neopixelCount'] = 0 - if not 'microAddress' in rpi_output: - rpi_output['microAddress'] = 0 - if not 'neopixelBrightness' in rpi_output: - rpi_output['neopixelBrightness'] = 255 + neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct' - for temp_reader in self.temperature_reading: - if not 'sensorAddress' in temp_reader: - temp_reader['sensorAddress'] = 0 + self.send_neopixel_command( + self.to_int(rpi_output['gpio_pin']), + led_count, led_brightness, red, green, blue, address, neopixel_dirrect, gpio_index) - self._settings.set(["rpi_outputs"],self.rpi_outputs) - self._settings.set(["temperature_reading"],self.temperature_reading) + return flask.jsonify(success=True) + + def send_neopixel_command(self, led_pin, led_count, led_brightness, red, green, blue, address, + neopixel_dirrect, index_id, queue_id=None): + """Send neopixel command + + Arguments: + led_pin {int} -- GPIO number + ledCount {int} -- number of LEDS + ledBrightness {int} -- brightness from 0 to 255 + red {int} -- red value from 0 to 255 + green {int} -- gren value from 0 to 255 + blue {int} -- blue value from 0 to 255 + address {int} -- i2c address from microcontroler + """ - def sendNeopixelCommand(self,ledPin,ledCount,ledBrightness,red,green,blue,address): try: - script = os.path.dirname(os.path.realpath(__file__)) + "/neopixel.py " - cmd ="sudo python " +script +str(ledPin)+" "+str(ledCount)+" "+str(ledBrightness)+" "+str(red)+" "+str(green)+" "+str(blue)+" "+str(address) - if self._settings.get(["debug"]) == True: + + for rpi_output in self.rpi_outputs: + if self.to_int(index_id) == self.to_int(rpi_output['index_id']): + rpi_output['neopixel_color'] = 'rgb({0!s},{1!s},{2!s})'.format( + red, green, blue) + + if address == '': + address = 0 + + if neopixel_dirrect: + script = os.path.dirname( + os.path.realpath(__file__)) + "/neopixel_direct.py " + else: + script = os.path.dirname( + os.path.realpath(__file__)) + "/neopixel_indirect.py " + + if self._settings.get(["use_sudo"]): + sudo_str = "sudo " + else: + sudo_str = "" + + cmd = sudo_str + "python " + script + str(led_pin) + " " + str(led_count) + " " + str( + led_brightness) + " " + str(red) + " " + str(green) + " " + str(blue) + " " + str(address) + if self._settings.get(["debug"]) is True: self._logger.info("Sending neopixel cmd: %s", cmd) - stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() + Popen(cmd, shell=True) + if queue_id is not None: + self.stop_queue_item(queue_id) except Exception as ex: - template = "An exception of type {0} occurred on sendNeopixelCommand. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def checkEnclosureTemp(self): + def check_enclosure_temp(self): try: - for temp_reader in self.temperature_reading: - if temp_reader['isEnabled']: - if temp_reader['sensorType'] in ["11", "22", "2302"]: - self._logger.info("sensorType dht") - temp, hum = self.readDhtTemp(temp_reader['sensorType'],temp_reader['gpioPin']) - elif temp_reader['sensorType'] == "18b20": - temp = self.read18b20Temp() - hum = 0 - elif temp_reader['sensorType'] == "bme280": - temp, hum = self.readBME280Temp(temp_reader['sensorAddress']) - elif temp_reader['sensorType'] == "si7021": - temp, hum = self.readSI7021Temp(temp_reader['sensorAddress']) - elif temp_reader['sensorType'] == "tmp102": - temp = self.readTmp102Temp(temp_reader['sensorAddress']) - hum = 0 - else: - self._logger.info("sensorType no match") - temp = 0 - hum = 0 - - if temp != -1 and hum != -1: - self.enclosureCurrentTemperature = round(self.toFloat(temp),1) if not temp_reader['useFahrenheit'] else round(self.toFloat(temp)*1.8 + 32,1) - self.enclosureCurrentHumidity = round(self.toFloat(hum),1) - - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: - self._logger.info("Temperature: %s humidity %s", self.enclosureCurrentTemperature,self.enclosureCurrentHumidity) - - self._plugin_manager.send_plugin_message(self._identifier, dict(enclosuretemp=self.enclosureCurrentTemperature,enclosureHumidity=self.enclosureCurrentHumidity)) - self.handleTemperatureControl() - self.handleTemperatureEvents() + sensor_data = [] + for sensor in list(filter(lambda item: item['input_type'] == 'temperature_sensor', self.rpi_inputs)): + temp, hum = self.get_sensor_data(sensor) + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + self._logger.info( + "Sensor %s Temperature: %s humidity %s", sensor['label'], temp, hum) + sensor_data.append( + dict(index_id=sensor['index_id'], temperature=temp, humidity=hum)) + self.temperature_sensor_data = sensor_data + self.handle_temp_hum_control() + self.handle_temperature_events() + self.handle_pwm_linked_temperature() + self.update_ui() except Exception as ex: - template = "An exception of type {0} occurred on checkEnclosureTemp. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def handleTemperatureEvents(self): - for rpi_input in self.rpi_inputs: - if self.toFloat(rpi_input['setTemp']) == 0: + def toggle_output(self, output_index, first_run=False): + for output in [item for item in self.rpi_outputs if item['index_id'] == output_index]: + gpio_pin = self.to_int(output['gpio_pin']) + index_id = self.to_int(output['index_id']) + + if output['output_type'] == 'regular': + if first_run: + current_value = False + else: + current_value = (not GPIO.input( + gpio_pin)) if output['active_low'] else GPIO.input(gpio_pin) + + if current_value: + time_delay = self.to_int(output['toggle_timer_off']) + else: + time_delay = self.to_int(output['toggle_timer_on']) + + if not self.print_complete: + self.write_gpio(gpio_pin, not current_value) + thread = threading.Timer(time_delay, + self.toggle_output, + args=[index_id]) + thread.start() + else: + off_value = True if output['active_low'] else False + self.write_gpio(gpio_pin, off_value) + self.update_ui_outputs() + return + + if output['output_type'] == 'pwm': + for pwm in self.pwm_intances: + if gpio_pin in pwm: + if first_run: + current_pwm_value = 0 + else: + if 'duty_cycle' in pwm: + current_pwm_value = pwm['duty_cycle'] + current_pwm_value = self.to_int( + current_pwm_value) + else: + current_pwm_value = 0 + + if not current_pwm_value == 0: + time_delay = self.to_int( + output['toggle_timer_off']) + write_value = 0 + else: + time_delay = self.to_int(output['toggle_timer_on']) + write_value = self.to_int( + output['default_duty_cycle']) + + if not self.print_complete: + self.write_pwm(gpio_pin, write_value) + thread = threading.Timer(time_delay, + self.toggle_output, + args=[index_id]) + thread.start() + else: + self.write_pwm(self.to_int(output['gpio_pin']), 0) + self.update_ui_outputs() + return + + def update_ui(self): + self.update_ui_outputs() + self.update_ui_current_temperature() + self.update_ui_set_temperature() + self.update_ui_inputs() + + def update_ui_current_temperature(self): + self._plugin_manager.send_plugin_message( + self._identifier, dict(sensor_data=self.temperature_sensor_data)) + + def update_ui_set_temperature(self): + result = [] + for temp_crt_output in list(filter(lambda item: + item['output_type'] == 'temp_hum_control', + self.rpi_outputs)): + set_temperature = self.to_float( + temp_crt_output['temp_ctr_set_value']) + result.append( + dict(index_id=temp_crt_output['index_id'], set_temperature=set_temperature)) + result.append(set_temperature) + self._plugin_manager.send_plugin_message( + self._identifier, dict(set_temperature=result)) + + def stop_queue_item(self, queue_id): + for task in self.event_queue: + if task['queue_id'] == queue_id: + task['thread'].cancel() + self.event_queue.remove(task) + + def update_ui_outputs(self): + try: + regular_status = [] + pwm_status = [] + neopixel_status = [] + temp_control_status = [] + for output in self.rpi_outputs: + index = self.to_int(output['index_id']) + pin = self.to_int(output['gpio_pin']) + startup = output['auto_startup'] + shutdown = output['auto_shutdown'] + + if output['output_type'] == 'regular': + val = GPIO.input(pin) if not output['active_low'] else ( + not GPIO.input(pin)) + regular_status.append( + dict(index_id=index, status=val, auto_startup=startup, auto_shutdown=shutdown)) + if output['output_type'] == 'temp_hum_control': + temp_control_status.append( + dict(index_id=index, auto_startup=startup, auto_shutdown=shutdown)) + if output['output_type'] == 'neopixel_indirect' or output['output_type'] == 'neopixel_direct': + val = output['neopixel_color'] + neopixel_status.append( + dict(index_id=index, color=val, auto_startup=startup, auto_shutdown=shutdown)) + if output['output_type'] == 'pwm': + for pwm in self.pwm_intances: + if pin in pwm: + if 'duty_cycle' in pwm: + pwm_val = pwm['duty_cycle'] + val = self.to_int(pwm_val) + else: + val = 0 + pwm_status.append( + dict(index_id=index, pwm_value=val, auto_startup=startup, auto_shutdown=shutdown)) + self._plugin_manager.send_plugin_message(self._identifier, dict(rpi_output_regular=regular_status, + rpi_output_pwm=pwm_status, + rpi_output_neopixel=neopixel_status, + rpi_output_temp_hum_ctrl=temp_control_status)) + except Exception as ex: + self.log_error(ex) + + def update_ui_inputs(self): + try: + sensor_status = [] + for sensor in self.rpi_inputs: + if sensor['input_type'] == 'gpio' and sensor['action_type'] == 'printer_control' and sensor['printer_action'] == 'filament': + index = self.to_int(sensor['index_id']) + value = sensor['filament_sensor_enabled'] + sensor_status.append( + dict(index_id=index, filament_sensor_enabled=value)) + self._plugin_manager.send_plugin_message( + self._identifier, dict(filament_sensor_status=sensor_status)) + except Exception as ex: + self.log_error(ex) + + def get_sensor_data(self, sensor): + try: + if sensor['temp_sensor_type'] in ["11", "22", "2302"]: + self._logger.info("temp_sensor_type dht") + temp, hum = self.read_dht_temp( + sensor['temp_sensor_type'], sensor['gpio_pin']) + elif sensor['temp_sensor_type'] == "18b20": + temp = self.read_18b20_temp(sensor['ds18b20_serial']) + hum = 0 + elif sensor['temp_sensor_type'] == "bme280": + temp, hum = self.read_bme280_temp( + sensor['temp_sensor_address']) + elif sensor['temp_sensor_type'] == "si7021": + temp, hum = self.read_si7021_temp( + sensor['temp_sensor_address']) + elif sensor['temp_sensor_type'] == "tmp102": + temp = self.read_tmp102_temp( + sensor['temp_sensor_address']) + hum = 0 + else: + self._logger.info("temp_sensor_type no match") + temp = 0 + hum = 0 + if temp != -1 and hum != -1: + temp = round(self.to_float( + temp), 1) if not sensor['use_fahrenheit'] else round(self.to_float(temp) * 1.8 + 32, 1) + hum = round(self.to_float(hum), 1) + return temp, hum + return 0, 0 + except Exception as ex: + self.log_error(ex) + + def handle_temperature_events(self): + for temperature_alarm in [item for item in self.rpi_outputs if item['output_type'] == 'temperature_alarm']: + set_temperature = self.to_float( + temperature_alarm['alarm_set_temp']) + if int(set_temperature) is 0: continue - if rpi_input['eventType']=='temperature' and (self.toFloat(rpi_input['setTemp']) < self.toFloat(self.enclosureCurrentTemperature)): - for rpi_output in self.rpi_outputs: - if self.toInt(rpi_input['controlledIO']) == self.toInt(rpi_output['gpioPin']): - val = GPIO.LOW if rpi_output['activeLow'] else GPIO.HIGH - self.writeGPIO(self.toInt(rpi_output['gpioPin']), val) + linked_data = [item for item in self.temperature_sensor_data if item['index_id'] == + temperature_alarm['linked_temp_sensor']].pop() + sensor_temperature = self.to_float(linked_data['temperature']) + if set_temperature < sensor_temperature: + for rpi_controlled_output in self.rpi_outputs: + if self.to_int(temperature_alarm['controlled_io']) == self.to_int(rpi_controlled_output['index_id']): + val = GPIO.LOW if rpi_controlled_output['active_low'] else GPIO.HIGH + self.write_gpio(self.to_int( + rpi_controlled_output['gpio_pin']), val) for notification in self.notifications: if notification['temperatureAction']: - msg = "Temperature action: enclosure temperature exceed " +rpi_input['setTemp'] - self.sendNotification(msg) + msg = ("Temperature action: enclosure temperature exceed " + + temperature_alarm['alarm_set_temp']) + self.send_notification(msg) - def readDhtTemp(self,sensor,pin): + def read_dht_temp(self, sensor, pin): try: - script = os.path.dirname(os.path.realpath(__file__)) + "/getDHTTemp.py " - cmd ="sudo python " +script+str(sensor)+" "+str(pin) - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + script = os.path.dirname( + os.path.realpath(__file__)) + "/getDHTTemp.py " + if self._settings.get(["use_sudo"]): + sudo_str = "sudo " + else: + sudo_str = "" + cmd = sudo_str + "python " + script + str(sensor) + " " + str(pin) + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("Temperature dht cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("Dht result: %s", stdout) - temp,hum = stdout.split("|") - return (self.toFloat(temp.strip()),self.toFloat(hum.strip())) + temp, hum = stdout.split("|") + return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: - template = "An exception of type {0} occurred on readDhtTemp. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) return (0, 0) - def readBME280Temp(self,address): + def read_bme280_temp(self, address): try: - script = os.path.dirname(os.path.realpath(__file__)) + "/BME280.py " - cmd ="sudo python " +script +str(address) - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + script = os.path.dirname( + os.path.realpath(__file__)) + "/BME280.py " + if self._settings.get(["use_sudo"]): + sudo_str = "sudo " + else: + sudo_str = "" + cmd = sudo_str + "python " + script + str(address) + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("Temperature BME280 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("BME280 result: %s", stdout) - temp,hum = stdout.split("|") - return (self.toFloat(temp.strip()),self.toFloat(hum.strip())) + temp, hum = stdout.split("|") + return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: - template = "An exception of type {0} occurred on readBME280Temp. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) return (0, 0) - def readSI7021Temp(self,address): + def read_si7021_temp(self, address): try: - script = os.path.dirname(os.path.realpath(__file__)) + "/SI7021.py " - cmd ="sudo python " +script +str(address) - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + script = os.path.dirname( + os.path.realpath(__file__)) + "/SI7021.py " + if self._settings.get(["use_sudo"]): + sudo_str = "sudo " + else: + sudo_str = "" + cmd = sudo_str + "python " + script + str(address) + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("Temperature SI7021 cmd: %s", cmd) stdout = (Popen(cmd, shell=True, stdout=PIPE).stdout).read() - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("SI7021 result: %s", stdout) - temp,hum = stdout.split("|") - return (self.toFloat(temp.strip()),self.toFloat(hum.strip())) + temp, hum = stdout.split("|") + return (self.to_float(temp.strip()), self.to_float(hum.strip())) except Exception as ex: - template = "An exception of type {0} occurred on readSI7021Temp. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) return (0, 0) - def read18b20Temp(self): + def read_18b20_temp(self, serial_number): os.system('modprobe w1-gpio') os.system('modprobe w1-therm') - lines = self.readraw18b20Temp() + lines = self.read_raw_18b20_temp(serial_number) while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) - lines = self.readraw18b20Temp() + lines = self.read_raw_18b20_temp(serial_number) equals_pos = lines[1].find('t=') if equals_pos != -1: - temp_string = lines[1][equals_pos+2:] - temp_c = float(temp_string) / 1000.0 + temp_string = lines[1][equals_pos + 2:] + temp_c = float(temp_string) / 1000. + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: + self._logger.info("DS18B20 result: %s", temp_c) return '{0:0.1f}'.format(temp_c) return 0 - def readraw18b20Temp(self): + def read_raw_18b20_temp(self, serial_number): base_dir = '/sys/bus/w1/devices/' - device_folder = glob.glob(base_dir + '28*')[0] + device_folder = glob.glob(base_dir + str(serial_number) + '*')[0] device_file = device_folder + '/w1_slave' - f = open(device_file, 'r') - lines = f.readlines() - f.close() + device_file_result = open(device_file, 'r') + lines = device_file_result.readlines() + device_file_result.close() return lines - def readTmp102Temp(self, address): + def read_tmp102_temp(self, address): try: script = os.path.dirname(os.path.realpath(__file__)) + "/tmp102.py" args = ["python", script, str(address)] - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("Temperature TMP102 cmd: %s", " ".join(args)) proc = Popen(args, stdout=PIPE) stdout, _ = proc.communicate() - if self._settings.get(["debug"]) == True and not self.disable_temeprature_log: + if self._settings.get(["debug"]) is True and self._settings.get(["debug_temperature_log"]) is True: self._logger.info("TMP102 result: %s", stdout) - return self.toFloat(stdout.strip()) + return self.to_float(stdout.strip()) except Exception as ex: - template = "An exception of type {0} occurred on readTmp102Temp. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) return 0 - - def handleTemperatureControl(self): - for control in self.temperature_control: - if control['isEnabled'] == True: - if control['controlType'] == 'heater': - self.currentTempControlStatus = self.toFloat(self.enclosureCurrentTemperature)self.toFloat(self.enclosureSetTemperature) - if self.currentTempControlStatus != self.previousTempControlStatus: - if self.currentTempControlStatus: - self._logger.info("Turning gpio to control temperature on.") - val = False if control['activeLow'] else True - self.writeGPIO(self.toInt(control['gpioPin']),val) - else: - self._logger.info("Turning gpio to control temperature off.") - val = True if control['activeLow'] else False - self.writeGPIO(self.toInt(control['gpioPin']), val) - self.previousTempControlStatus = self.currentTempControlStatus - - def startGPIO(self): + def handle_pwm_linked_temperature(self): try: - currentMode = GPIO.getmode() - setMode = GPIO.BOARD if self._settings.get(["useBoardPinNumber"]) else GPIO.BCM - if currentMode == None: - GPIO.setmode(setMode) - tempstr = "BOARD" if setMode == GPIO.BOARD else "BCM" - self._logger.info("Setting GPIO mode to %s",tempstr) - elif currentMode != setMode: - GPIO.setmode(currentMode) - tempstr = "BOARD" if currentMode == GPIO.BOARD else "BCM" - self._settings.set(["useBoardPinNumber"],True if currentMode == GPIO.BOARD else False) - warn_msg = "GPIO mode was configured before, GPIO mode will be forced to use: " + tempstr + " as pin numbers. Please update GPIO accordingly!" + for pwm_output in list(filter(lambda item: item['output_type'] == 'pwm' and item['pwm_temperature_linked'], self.rpi_outputs)): + gpio_pin = self.to_int(pwm_output['gpio_pin']) + if self._printer.is_printing(): + index_id = self.to_int(pwm_output['index_id']) + linked_id = self.to_int(pwm_output['linked_temp_sensor']) + linked_data = self.get_linked_temp_sensor_data( + linked_id) + current_temp = self.to_float( + linked_data['temperature']) + + duty_a = self.to_float(pwm_output['duty_a']) + duty_b = self.to_float(pwm_output['duty_b']) + temp_a = self.to_float(pwm_output['temperature_a']) + temp_b = self.to_float(pwm_output['temperature_b']) + + try: + calculated_duty = ((current_temp - temp_a) * + (duty_b - duty_a) / (temp_b - temp_a)) + duty_a + except: + calculated_duty = 0 + + if self._settings.get(["debug"]) is True: + self._logger.info( + "Calculated duty for PWM %s is %s", index_id, calculated_duty) + elif self.print_complete: + calculated_duty = self.to_int(pwm_output['duty_cycle']) + else: + calculated_duty = 0 + + self.write_pwm(gpio_pin, self.constrain( + calculated_duty, 0, 100)) + + except Exception as ex: + self.log_error(ex) + + def get_linked_temp_sensor_data(self, linked_id): + try: + linked_data = [ + data for data in self.temperature_sensor_data if data['index_id'] == linked_id].pop() + return linked_data + except: + self._logger.warn( + "No linked temperature sensor found for %s", linked_id) + return None + + def handle_temp_hum_control(self): + try: + for temp_hum_control in list(filter(lambda item: item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + + set_temperature = self.to_float( + temp_hum_control['temp_ctr_set_value']) + temp_deadband = self.to_float( + temp_hum_control['temp_ctr_deadband']) + max_temp = self.to_float( + temp_hum_control['temp_ctr_max_temp']) + + linked_id = temp_hum_control['linked_temp_sensor'] + + previous_status = list(filter( + lambda item: item['index_id'] == temp_hum_control['index_id'], + self.temp_hum_control_status)).pop()['status'] + + if set_temperature == 0: + current_status = False + else: + linked_data = self.get_linked_temp_sensor_data( + linked_id) + + if str(temp_hum_control['temp_ctr_type']) == 'dehumidifier': + current_value = self.to_float(linked_data['humidity']) + temp_deadband = 0 + else: + current_value = self.to_float( + linked_data['temperature']) + + if set_temperature - temp_deadband > current_value: + current_status = True + elif set_temperature + temp_deadband < current_value: + current_status = False + else: + current_status = previous_status + + if str(temp_hum_control['temp_ctr_type']) == 'cooler' or str(temp_hum_control['temp_ctr_type']) == 'dehumidifier': + current_status = not current_status + + if temp_hum_control['temp_ctr_type'] == 'heater' and max_temp > 0.0 and max_temp < current_value: + if self._settings.get(["debug"]) is True: + self._logger.info( + "Maximun temperature reached for temperature control %s", temp_hum_control['index_id']) + temp_hum_control['temp_ctr_set_value'] = 0 + current_status = False + + if current_status != previous_status: + if current_status: + self._logger.info( + "Turning gpio to control temperature on.") + val = False if temp_hum_control['active_low'] else True + self.write_gpio(self.to_int( + temp_hum_control['gpio_pin']), val) + else: + index_id = temp_hum_control['index_id'] + if index_id in self.waiting_temperature: + self.waiting_temperature.remove(index_id) + + if not self.waiting_temperature and self._printer.is_paused(): + self._printer.resume_print() + + self._logger.info( + "Turning gpio to control temperature off.") + val = True if temp_hum_control['active_low'] else False + self.write_gpio(self.to_int( + temp_hum_control['gpio_pin']), val) + for control_status in self.temp_hum_control_status: + if control_status['index_id'] == temp_hum_control['index_id']: + control_status['status'] = current_status + except Exception as ex: + self.log_error(ex) + + def log_error(self, ex): + template = "An exception of type {0} occurred on {1}. Arguments:\n{2!r}" + message = template.format( + type(ex).__name__, inspect.currentframe().f_code.co_name, ex.args) + self._logger.warn(message) + + def setup_gpio(self): + try: + current_mode = GPIO.getmode() + set_mode = GPIO.BOARD if self._settings.get( + ["useBoardPinNumber"]) else GPIO.BCM + if current_mode is None: + outputs = list(filter(lambda item: item['output_type'] == 'regular' or + item['output_type'] == 'pwm' or + item['output_type'] == 'temp_hum_control' or + item['output_type'] == 'neopixel_direct', self.rpi_outputs)) + inputs = list(filter( + lambda item: item['input_type'] == 'gpio', self.rpi_inputs)) + gpios = outputs + inputs + if gpios: + GPIO.setmode(set_mode) + tempstr = "BOARD" if set_mode == GPIO.BOARD else "BCM" + self._logger.info("Setting GPIO mode to %s", tempstr) + elif current_mode != set_mode: + GPIO.setmode(current_mode) + tempstr = "BOARD" if current_mode == GPIO.BOARD else "BCM" + self._settings.set(["useBoardPinNumber"], + True if current_mode == GPIO.BOARD else False) + warn_msg = "GPIO mode was configured before, GPIO mode will be forced to use: " + \ + tempstr + " as pin numbers. Please update GPIO accordingly!" self._logger.info(warn_msg) - self._plugin_manager.send_plugin_message(self._identifier,dict(isMsg=True,msg=warn_msg)) + self._plugin_manager.send_plugin_message( + self._identifier, dict(isMsg=True, msg=warn_msg)) GPIO.setwarnings(False) except Exception as ex: - template = "An exception of type {0} occurred on startGPIO. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def clearGPIO(self): + def clear_gpio(self): try: - for control in self.temperature_control: - if control['isEnabled']: - GPIO.cleanup(self.toInt(control['gpioPin'])) - for rpi_output in self.rpi_outputs: - if self.toInt(rpi_output['gpioPin']) not in self.previous_rpi_outputs: - GPIO.cleanup(self.toInt(rpi_output['gpioPin'])) - for rpi_input in self.rpi_inputs: + + for gpio_out in list(filter(lambda item: item['output_type'] == 'regular' or + item['output_type'] == 'pwm' or + item['output_type'] == 'temp_hum_control' or + item['output_type'] == 'neopixel_direct', self.rpi_outputs)): + gpio_pin = self.to_int(gpio_out['gpio_pin']) + if gpio_pin not in self.rpi_outputs_not_changed: + GPIO.cleanup(gpio_pin) + + for gpio_in in list(filter(lambda item: item['input_type'] == 'gpio', self.rpi_inputs)): try: - GPIO.remove_event_detect(self.toInt(rpi_input['gpioPin'])) + GPIO.remove_event_detect( + self.to_int(gpio_in['gpio_pin'])) except: pass - GPIO.cleanup(self.toInt(rpi_input['gpioPin'])) + GPIO.cleanup(self.to_int(gpio_in['gpio_pin'])) except Exception as ex: - template = "An exception of type {0} occurred on clearGPIO. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def clearChannel(self,channel): + def clear_channel(self, channel): try: - GPIO.cleanup(self.toInt(channel)) + GPIO.cleanup(self.to_int(channel)) except Exception as ex: - template = "An exception of type {0} occurred on clearChannel. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def configureGPIO(self): + def generate_temp_hum_control_status(self): + status = [] + for temp_hum_control in list(filter(lambda item: + item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + status.append( + dict(index_id=temp_hum_control['index_id'], status=False)) + self.temp_hum_control_status = status + + def configure_gpio(self): try: - for control in self.temperature_control: - if control['isEnabled']: - GPIO.setup(self.toInt(control['gpioPin']), GPIO.OUT, initial=GPIO.HIGH if control['activeLow'] else GPIO.LOW) - for rpi_output in self.rpi_outputs: - pin = self.toInt(rpi_output['gpioPin']) - if rpi_output['outputType'] == 'regular': - if self.toInt(rpi_output['gpioPin']) not in self.previous_rpi_outputs : - initialValue = GPIO.HIGH if rpi_output['activeLow'] else GPIO.LOW - GPIO.setup(pin, GPIO.OUT,initial=initialValue) - if rpi_output['outputType'] == 'pwm': - for pwm in (pwm for pwm in self.PWM_INSTANCES if pin in pwm): - self.PWM_INSTANCES.remove(pwm) - self.clearChannel(pin) - GPIO.setup(pin, GPIO.OUT) - p = GPIO.PWM(pin, self.toInt(rpi_output['frequency'])) - self.PWM_INSTANCES.append({pin:p}) - if rpi_output['outputType'] == 'neopixel': - self.clearChannel(pin) - for rpi_input in self.rpi_inputs: - pullResistor = pull_up_down=GPIO.PUD_UP if rpi_input['inputPull'] == 'inputPullUp' else GPIO.PUD_DOWN - GPIO.setup(self.toInt(rpi_input['gpioPin']), GPIO.IN, pullResistor) - if rpi_input['eventType'] == 'gpio' and self.toInt(rpi_input['gpioPin']) != 0: - edge = GPIO.RISING if rpi_input['edge'] == 'rise' else GPIO.FALLING - GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handleGPIOControl, bouncetime=200) - if rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] != 'filament' and self.toInt(rpi_input['gpioPin']) != 0: - edge = GPIO.RISING if rpi_input['edge'] == 'rise' else GPIO.FALLING - GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handlePrinterAction, bouncetime=200) + + for gpio_out in list(filter(lambda item: item['output_type'] == 'regular' or + item['output_type'] == 'temp_hum_control', self.rpi_outputs)): + initial_value = GPIO.HIGH if gpio_out['active_low'] else GPIO.LOW + pin = self.to_int(gpio_out['gpio_pin']) + if pin not in self.rpi_outputs_not_changed: + self._logger.info( + "Setting GPIO pin %s as OUTPUT with initial value: %s", pin, initial_value) + GPIO.setup(pin, GPIO.OUT, initial=initial_value) + for gpio_out_pwm in list(filter(lambda item: item['output_type'] == 'pwm', self.rpi_outputs)): + pin = self.to_int(gpio_out_pwm['gpio_pin']) + self._logger.info( + "Setting GPIO pin %s as PWM", pin) + for pwm in (pwm_dict for pwm_dict in self.pwm_intances if pin in pwm_dict): + self.pwm_intances.remove(pwm) + self.clear_channel(pin) + GPIO.setup(pin, GPIO.OUT) + pwm_instance = GPIO.PWM(pin, self.to_int( + gpio_out_pwm['pwm_frequency'])) + self.pwm_intances.append({pin: pwm_instance}) + for gpio_out_neopixel in list(filter(lambda item: item['output_type'] == 'neopixel_direct', self.rpi_outputs)): + pin = self.to_int(gpio_out_neopixel['gpio_pin']) + self.clear_channel(pin) + + for rpi_input in list(filter(lambda item: item['input_type'] == 'gpio', self.rpi_inputs)): + pull_resistor = GPIO.PUD_UP if rpi_input['input_pull_resistor'] == 'input_pull_up' else GPIO.PUD_DOWN + gpio_pin = self.to_int(rpi_input['gpio_pin']) + GPIO.setup(gpio_pin, GPIO.IN, pull_resistor) + edge = GPIO.RISING if rpi_input['edge'] == 'rise' else GPIO.FALLING + if rpi_input['action_type'] == 'output_control': + self._logger.info( + "Adding GPIO event detect on pin %s with edge: %s", gpio_pin, edge) + GPIO.add_event_detect( + gpio_pin, edge, callback=self.handle_gpio_control, bouncetime=200) + if (rpi_input['action_type'] == 'printer_control' and rpi_input['printer_action'] != 'filament'): + GPIO.add_event_detect( + gpio_pin, edge, callback=self.handle_printer_action, bouncetime=200) + self._logger.info( + "Adding PRINTER CONTROL event detect on pin %s with edge: %s", gpio_pin, edge) except Exception as ex: - template = "An exception of type {0} occurred on configureGPIO. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def handleFilammentDetection(self,channel): + def handle_filamment_detection(self, channel): try: - for rpi_input in self.rpi_inputs: - if channel == self.toInt(rpi_input['gpioPin']) and rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] == 'filament' \ - and ((rpi_input['edge']=='fall') ^ GPIO.input(self.toInt(rpi_input['gpioPin']))): - if time.time() - self.lastFilamentEndDetected > self._settings.get_int(["filamentSensorTimeout"]): + for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and + item['action_type'] == 'printer_control' and + item['printer_action'] == 'filament' and + self.to_int(item['gpio_pin']) == self.to_int(channel), self.rpi_inputs)): + if ((filament_sensor['edge'] == 'fall') ^ (GPIO.input(self.to_int(filament_sensor['gpio_pin']))) and + filament_sensor['filament_sensor_enabled']): + last_detected_time = list(filter(lambda item: item['index_id'] == filament_sensor['index_id'], + self.last_filament_end_detected)).pop()['time'] + if time.time() - last_detected_time > self._settings.get_int(["filament_sensor_timeout"]): self._logger.info("Detected end of filament.") - self.lastFilamentEndDetected = time.time() - for line in self._settings.get(["filamentSensorGcode"]).split('\n'): + for item in self.last_filament_end_detected: + if item['index_id'] == filament_sensor['index_id']: + item['time'] = time.time() + for line in self._settings.get(["filament_sensor_gcode"]).split('\n'): if line: self._printer.commands(line.strip().upper()) - self._logger.info("Sending GCODE command: %s",line.strip( ).upper()) + self._logger.info( + "Sending GCODE command: %s", line.strip().upper()) time.sleep(0.2) for notification in self.notifications: if notification['filamentChange']: - msg = "Filament change action caused by sensor: " + str(rpi_input['label']) - self.sendNotification(msg) + msg = "Filament change action caused by sensor: " + \ + str(filament_sensor['label']) + self.send_notification(msg) else: - self._logger.info("Prevented end of filament detection, filament sensor timeout not elapsed.") + self._logger.info( + "Prevented end of filament detection, filament sensor timeout not elapsed.") except Exception as ex: - template = "An exception of type {0} occurred on handleFilammentDetection. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + self.log_error(ex) - def startFilamentDetection(self): - self.stopFilamentDetection() + def start_filament_detection(self): + self.stop_filament_detection() try: - for rpi_input in self.rpi_inputs: - if rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] == 'filament' and self.toInt(rpi_input['gpioPin']) != 0: - edge = GPIO.RISING if rpi_input['edge'] == 'rise' else GPIO.FALLING - if GPIO.input(self.toInt(rpi_input['gpioPin'])) == (edge == GPIO.RISING): - self._printer.pause_print() - self._logger.info("Started printing with no filament.") + for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and + item['action_type'] == 'printer_control' and + item['printer_action'] == 'filament', self.rpi_inputs)): + edge = GPIO.RISING if filament_sensor['edge'] == 'rise' else GPIO.FALLING + if GPIO.input(self.to_int(filament_sensor['gpio_pin'])) == (edge == GPIO.RISING): + self._printer.pause_print() + self._logger.info("Started printing with no filament.") + else: + self.last_filament_end_detected.append( + dict(index_id=filament_sensor['index_id'], time=0)) + self._logger.info( + "Adding GPIO event detect on pin %s with edge: %s", filament_sensor['gpio_pin'], edge) + GPIO.add_event_detect(self.to_int( + filament_sensor['gpio_pin']), edge, callback=self.handle_filamment_detection, bouncetime=200) + except Exception as ex: + self.log_error(ex) + + def stop_filament_detection(self): + try: + self.last_filament_end_detected = [] + for filament_sensor in list(filter(lambda item: item['input_type'] == 'gpio' and + item['action_type'] == 'printer_control' and + item['printer_action'] == 'filament', self.rpi_inputs)): + GPIO.remove_event_detect( + self.to_int(filament_sensor['gpio_pin'])) + except Exception as ex: + self.log_error(ex) + + def cancel_all_events_on_queue(self): + for task in self.event_queue: + try: + task['thread'].cancel() + except: + self._logger.warn("Failed to stop task %s.", task) + pass + + def handle_gpio_control(self, channel): + try: + if self._settings.get(["debug"]) is True: + self._logger.info( + "GPIO event triggered on channel %s", channel) + rpi_input = [r_inp for r_inp in self.rpi_inputs if self.to_int( + r_inp['gpio_pin']) == self.to_int(channel)].pop() + gpio_pin = self.to_int(rpi_input['gpio_pin']) + controlled_io = self.to_int(rpi_input['controlled_io']) + if (rpi_input['edge'] == 'fall') ^ GPIO.input(gpio_pin): + rpi_output = [r_out for r_out in self.rpi_outputs if self.to_int( + r_out['index_id']) == controlled_io].pop() + if rpi_output['output_type'] == 'regular': + if rpi_input['controlled_io_set_value'] == 'toggle': + val = GPIO.LOW if GPIO.input(self.to_int( + rpi_output['gpio_pin'])) == GPIO.HIGH else GPIO.HIGH else: - GPIO.add_event_detect(self.toInt(rpi_input['gpioPin']), edge, callback= self.handleFilammentDetection, bouncetime=200) + val = GPIO.LOW if rpi_input['controlled_io_set_value'] == 'low' else GPIO.HIGH + self.write_gpio(self.to_int( + rpi_output['gpio_pin']), val) + for notification in self.notifications: + if notification['gpioAction']: + msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str( + rpi_input['controlled_io']) + " to: " + str(rpi_input['controlled_io_set_value']) + self.send_notification(msg) + if rpi_output['output_type'] == 'gcode_output': + self.send_gcode_command(rpi_output['gcode']) + for notification in self.notifications: + if notification['gpioAction']: + msg = "GPIO control action caused by input " + \ + str(rpi_input['label']) + \ + ". Sending GCODE command" + self.send_notification(msg) except Exception as ex: - template = "An exception of type {0} occurred on startFilamentDetection. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) pass - def stopFilamentDetection(self): - try: - for rpi_input in self.rpi_inputs: - if rpi_input['eventType'] == 'printer' and rpi_input['printerAction'] == 'filament': - GPIO.remove_event_detect(self.toInt(rpi_input['gpioPin'])) - except Exception as ex: - template = "An exception of type {0} occurred on stopFilamentDetection. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass + def send_gcode_command(self, command): + for line in command.split('\n'): + if line: + self._printer.commands(line.strip().upper()) + self._logger.info( + "Sending GCODE command: %s", line.strip().upper()) + time.sleep(0.2) - def handleGPIOControl(self,channel): + def handle_printer_action(self, channel): try: for rpi_input in self.rpi_inputs: - if channel == self.toInt(rpi_input['gpioPin']) and rpi_input['eventType']=='gpio' and \ - ((rpi_input['edge']=='fall') ^ GPIO.input(self.toInt(rpi_input['gpioPin']))): - for rpi_output in self.rpi_outputs: - if self.toInt(rpi_input['controlledIO']) == self.toInt(rpi_output['gpioPin']) and rpi_output['outputType']=='regular': - if rpi_input['setControlledIO']=='toggle': - val = GPIO.LOW if GPIO.input(self.toInt(rpi_output['gpioPin']))==GPIO.HIGH else GPIO.HIGH - else: - val = GPIO.LOW if rpi_input['setControlledIO']=='low' else GPIO.HIGH - self.writeGPIO(self.toInt(rpi_output['gpioPin']),val) - for notification in self.notifications: - if notification['gpioAction']: - msg = "GPIO control action caused by input " + str(rpi_input['label']) + ". Setting GPIO" + str(rpi_input['controlledIO']) + " to: " + str(rpi_input['setControlledIO']) - self.sendNotification(msg) - except Exception as ex: - template = "An exception of type {0} occurred on handleGPIOControl. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass - - def handlePrinterAction(self,channel): - try: - for rpi_input in self.rpi_inputs: - if channel == self.toInt(rpi_input['gpioPin']) and rpi_input['eventType']=='printer' and \ - ((rpi_input['edge']=='fall') ^ GPIO.input(self.toInt(rpi_input['gpioPin']))): - if rpi_input['printerAction'] == 'resume': + if (channel == self.to_int(rpi_input['gpio_pin']) and + rpi_input['action_type'] == 'printer_control' and + ((rpi_input['edge'] == 'fall') ^ GPIO.input(self.to_int(rpi_input['gpio_pin'])))): + if rpi_input['printer_action'] == 'resume': self._logger.info("Printer action resume.") self._printer.resume_print() - elif rpi_input['printerAction'] == 'pause': + elif rpi_input['printer_action'] == 'pause': self._logger.info("Printer action pause.") self._printer.pause_print() - elif rpi_input['printerAction'] == 'cancel': + elif rpi_input['printer_action'] == 'cancel': self._logger.info("Printer action cancel.") self._printer.cancel_print() - elif rpi_input['printerAction'] == 'stopTemperatureControl': - self._logger.info("Printer action stoping temperature control.") - self.enclosureSetTemperature = 0; - self.handleTemperatureControl() + elif rpi_input['printer_action'] == 'stop_temp_hum_control': + self._logger.info( + "Printer action stoping temperature control.") + for rpi_output in self.rpi_outputs: + if rpi_output['auto_shutdown'] and rpi_output['output_type'] == 'temp_hum_control': + rpi_output['temp_ctr_set_value'] = 0 + self.handle_temp_hum_control() for notification in self.notifications: - if notification['printerAction']: - msg = "Printer action: " + rpi_input['printerAction'] + " caused by input: " + str(rpi_input['label']) - self.sendNotification(msg) + if notification['printer_action']: + msg = "Printer action: " + \ + rpi_input['printer_action'] + \ + " caused by input: " + str(rpi_input['label']) + self.send_notification(msg) except Exception as ex: - template = "An exception of type {0} occurred on handlePrinterAction. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) pass - def writeGPIO(self,gpio,value): + def write_gpio(self, gpio, value, queue_id=None): try: GPIO.output(gpio, value) - if self._settings.get(["debug"]) == True: - self._logger.info("Writing on gpio: %s value %s", gpio,value) - self.updateOutputUI() + if self._settings.get(["debug"]) is True: + self._logger.info("Writing on gpio: %s value %s", gpio, value) + self.update_ui() + if queue_id is not None: + self.stop_queue_item(queue_id) except Exception as ex: - template = "An exception of type {0} occurred on writeGPIO. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) + template = "An exception of type {0} occurred on {1} when writing on pin {2}. Arguments:\n{3!r}" + message = template.format( + type(ex).__name__, inspect.currentframe().f_code.co_name, gpio, ex.args) self._logger.warn(message) pass - def writePWM(self,gpio,pwmValue): + def write_pwm(self, gpio, pwm_value, queue_id=None): try: - for pwm in self.PWM_INSTANCES: + for pwm in self.pwm_intances: if gpio in pwm: pwm_object = pwm[gpio] - pwm['dutycycle']=pwmValue - pwm_object.stop() - pwm_object.start(pwmValue) - if self._settings.get(["debug"]) == True: - self._logger.info("Writing PWM on gpio: %s value %s", gpio,pwmValue) - self.updateOutputUI() + old_pwm_value = pwm['duty_cycle'] if 'duty_cycle' in pwm else -1 + if not self.to_int(old_pwm_value) == self.to_int(pwm_value): + pwm['duty_cycle'] = pwm_value + pwm_object.stop() + pwm_object.start(pwm_value) + if self._settings.get(["debug"]) is True: + self._logger.info( + "Writing PWM on gpio: %s value %s", gpio, pwm_value) + self.update_ui() + if queue_id is not None: + self.stop_queue_item(queue_id) break except Exception as ex: - template = "An exception of type {0} occurred on writePWM. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) pass - def updateOutputUI(self): - try: - result = [] - result_pwm = [] - - for rpi_output in self.rpi_outputs: - pin = self.toInt(rpi_output['gpioPin']) - if rpi_output['outputType']=='regular': - val = GPIO.input(pin) if not rpi_output['activeLow'] else (not GPIO.input(pin)) - result.append({pin:val}) - if rpi_output['outputType']=='pwm': - # self._logger.info("outputType is PWM") - # self._logger.info("Got pin number: %s",pin) - # self._logger.info("PWM_INSTANCES: %s",self.PWM_INSTANCES) - for pwm in self.PWM_INSTANCES: - if pin in pwm: - if 'dutycycle' in pwm: - pwmVal = pwm['dutycycle']; - val = self.toInt(pwmVal) - else: - val = 100 - result_pwm.append({pin:val}) - # self._logger.info("result_pwm: %s", result_pwm) - self._plugin_manager.send_plugin_message(self._identifier, dict(rpi_output=result,rpi_output_pwm=result_pwm)) - except Exception as ex: - template = "An exception of type {0} occurred on updateOutputUI. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) - pass - - def getOutputList(self): + def get_output_list(self): result = [] for rpi_output in self.rpi_outputs: - result.append(self.toInt(rpi_output['gpioPin'])) + if rpi_output['output_type'] == 'regular': + result.append(self.to_int(rpi_output['gpio_pin'])) return result - def sendNotification(self, message): + def send_notification(self, message): try: - provider = self._settings.get(["notificationProvider"]) + provider = self._settings.get(["notification_provider"]) if provider == 'ifttt': - event = self._settings.get(["event_name"]) - api_key = self._settings.get(["apiKEY"]) - if self._settings.get(["debug"]) == True: - self._logger.info("Sending notification to: %s with msg: %s with key: %s", provider,message,api_key) + event = self._settings.get(["notification_event_name"]) + api_key = self._settings.get(["notification_api_key"]) + if self._settings.get(["debug"]) is True: + self._logger.info( + "Sending notification to: %s with msg: %s with key: %s", provider, message, api_key) try: - res = self.iftttNotification(message,event,api_key) + res = self.ifttt_notification(message, event, api_key) except requests.exceptions.ConnectionError: self._logger.info("Error: Could not connect to IFTTT") except requests.exceptions.HTTPError: @@ -629,188 +1078,380 @@ class EnclosurePlugin(octoprint.plugin.StartupPlugin, try: j = res.json() except ValueError: - self._logger.info('Error: Could not parse server response. Event not sent') + self._logger.info( + 'Error: Could not parse server response. Event not sent') for err in j['errors']: self._logger.info('Error: {}'.format(err['message'])) except Exception as ex: - template = "An exception of type {0} occurred on sendNotification. Arguments:\n{1!r}" - message = template.format(type(ex).__name__, ex.args) - self._logger.warn(message) + self.log_error(ex) pass - def iftttNotification(self,message,event,api_key): - url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format(e=event,k=api_key) + def ifttt_notification(self, message, event, api_key): + url = "https://maker.ifttt.com/trigger/{e}/with/key/{k}/".format( + e=event, k=api_key) payload = {'value1': message} return requests.post(url, data=payload) - #~~ EventPlugin mixin + # ~~ EventPlugin mixin def on_event(self, event, payload): - if event == Events.CONNECTED: - self.updateOutputUI() + self.update_ui() if event == Events.PRINT_RESUMED: - self.startFilamentDetection() + self.start_filament_detection() if event == Events.PRINT_STARTED: - map(scheduler.cancel, scheduler.queue) - self.startFilamentDetection() + self.print_complete = False + self.cancel_all_events_on_queue() + self.start_filament_detection() for rpi_output in self.rpi_outputs: - if rpi_output['autoStartup'] and rpi_output['outputType']=='regular': - value = False if rpi_output['activeLow'] else True - scheduler.enter(self.toFloat(rpi_output['startupTimeDelay']), 1, self.writeGPIO, (self.toInt(rpi_output['gpioPin']),value,)) - if rpi_output['autoStartup'] and rpi_output['outputType']=='pwm': - value = self.toInt(rpi_output['dutycycle']) - scheduler.enter(self.toFloat(rpi_output['startupTimeDelay']), 1, self.writePWM, (self.toInt(rpi_output['gpioPin']),value,)) - if rpi_output['autoStartup'] and rpi_output['outputType']=='neopixel': - gpioPin = rpi_output['gpioPin'] - ledCount = rpi_output['neopixelCount'] - ledBrightness = rpi_output['neopixelBrightness'] - address = rpi_output['microAddress'] - stringColor = rpi_output['color'] - stringColor = stringColor.replace('rgb(','') + if rpi_output['auto_startup']: + delay_seconds = self.get_startup_delay_from_output( + rpi_output) + self.schedule_auto_startup_outputs( + rpi_output, delay_seconds) + if rpi_output['toggle_timer']: + if rpi_output['output_type'] == 'regular' or rpi_output['output_type'] == 'pwm': + self.toggle_output(rpi_output['index_id'], True) + if self.is_hour(rpi_output['shutdown_time']): + shutdown_delay_seconds = self.get_shutdown_delay_from_output( + rpi_output) + self.schedule_auto_shutdown_outputs( + rpi_output, shutdown_delay_seconds) + self.run_tasks() + self.update_ui() - red = stringColor[:stringColor.index(',')] - stringColor = stringColor[stringColor.index(',')+1:] - green = stringColor[:stringColor.index(',')] - stringColor = stringColor[stringColor.index(',')+1:] - blue = stringColor[:stringColor.index(')')] - - scheduler.enter(self.toFloat(rpi_output['startupTimeDelay']), 1, self.sendNeopixelCommand, (gpioPin,ledCount,ledBrightness,red,green,blue,address,)) - scheduler.run() - for control in self.temperature_control: - if control['autoStartup'] == True: - self.enclosureSetTemperature = self.toInt(control['defaultTemp']) - self._plugin_manager.send_plugin_message(self._identifier, dict(enclosureSetTemp=self.enclosureSetTemperature)) - - elif event in (Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED): - self.stopFilamentDetection() - self.enclosureSetTemperature = 0 - self._plugin_manager.send_plugin_message(self._identifier, dict(enclosureSetTemp=self.enclosureSetTemperature)) + elif event == Events.PRINT_DONE: + self.stop_filament_detection() + self.print_complete = True for rpi_output in self.rpi_outputs: - if rpi_output['autoShutdown'] and rpi_output['outputType']=='regular': - value = True if rpi_output['activeLow'] else False - scheduler.enter(self.toFloat(rpi_output['shutdownTimeDelay']), 1, self.writeGPIO, (self.toInt(rpi_output['gpioPin']),value,)) - if rpi_output['autoShutdown'] and rpi_output['outputType']=='pwm': - value = 0 - scheduler.enter(self.toFloat(rpi_output['startupTimeDelay']), 1, self.writePWM, (self.toInt(rpi_output['gpioPin']),value,)) - if rpi_output['autoShutdown'] and rpi_output['outputType']=='neopixel': - gpioPin = rpi_output['gpioPin'] - ledCount = rpi_output['neopixelCount'] - ledBrightness = rpi_output['neopixelBrightness'] - address = rpi_output['microAddress'] - scheduler.enter(self.toFloat(rpi_output['startupTimeDelay']), 1, self.sendNeopixelCommand, (gpioPin,ledCount,0,0,0,0,address,)) - scheduler.run() + shutdown_time = rpi_output['shutdown_time'] + if rpi_output['output_type'] == 'pwm' and rpi_output['pwm_temperature_linked']: + rpi_output['duty_cycle'] = rpi_output['default_duty_cycle'] + if rpi_output['auto_shutdown'] and not self.is_hour(shutdown_time): + delay_seconds = self.to_float(shutdown_time) + self.schedule_auto_shutdown_outputs( + rpi_output, delay_seconds) + if rpi_output['output_type'] == 'temp_hum_control': + rpi_output['temp_ctr_set_value'] = 0 + self.run_tasks() + self.update_ui() + + elif event in (Events.PRINT_CANCELLED, Events.PRINT_FAILED): + self.stop_filament_detection() + self.cancel_all_events_on_queue() if event == Events.PRINT_DONE: for notification in self.notifications: if notification['printFinish']: file_name = os.path.basename(payload["file"]) elapsed_time_in_seconds = payload["time"] - elapsed_time = octoprint.util.get_formatted_timedelta(datetime.timedelta(seconds=elapsed_time_in_seconds)) - msg = "Print job finished: " + file_name + "finished printing in " + file_name,elapsed_time - self.sendNotification(msg) + elapsed_time = octoprint.util.get_formatted_timedelta( + timedelta(seconds=elapsed_time_in_seconds)) + msg = "Print job finished: " + file_name + \ + "finished printing in " + file_name, elapsed_time + self.send_notification(msg) + def run_tasks(self): + for task in self.event_queue: + if not task['thread'].is_alive(): + task['thread'].start() - #~~ SettingsPlugin mixin + def schedule_auto_shutdown_outputs(self, rpi_output, shutdown_delay_seconds): + sufix = 'auto_shutdown' + if rpi_output['output_type'] == 'regular': + value = True if rpi_output['active_low'] else False + self.add_regular_output_to_queue( + shutdown_delay_seconds, rpi_output, value, sufix) + if rpi_output['output_type'] == 'pwm' and not rpi_output['pwm_temperature_linked']: + value = 0 + self.add_pwm_output_to_queue( + shutdown_delay_seconds, rpi_output, value, sufix) + if rpi_output['output_type'] == 'pwm' and rpi_output['pwm_temperature_linked']: + self.schedule_pwm_duty_on_queue( + shutdown_delay_seconds, rpi_output, 0) + if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): + self.add_neopixel_output_to_queue( + rpi_output, shutdown_delay_seconds, 0, 0, 0, sufix) + + def start_outpus_with_server(self): + for rpi_output in self.rpi_outputs: + if rpi_output['startup_with_server']: + gpio = self.to_int(rpi_output['gpio_pin']) + if rpi_output['output_type'] == 'regular': + value = False if rpi_output['active_low'] else True + self.write_gpio(gpio, value) + if rpi_output['output_type'] == 'pwm' and not rpi_output['pwm_temperature_linked']: + value = self.to_int(rpi_output['default_duty_cycle']) + self.write_pwm(gpio, value) + if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): + red, green, blue = self.get_color_from_rgb( + rpi_output['default_neopixel_color']) + led_count = rpi_output['neopixel_count'] + led_brightness = rpi_output['neopixel_brightness'] + address = rpi_output['microcontroller_address'] + index_id = self.to_int(rpi_output['index_id']) + neopixel_dirrect = rpi_output['output_type'] == 'neopixel_direct' + self.send_neopixel_command(self.to_int(rpi_output['gpio_pin']), led_count, led_brightness, red, green, blue, + address, neopixel_dirrect, index_id) + if rpi_output['output_type'] == 'temp_hum_control': + rpi_output['temp_ctr_set_value'] = rpi_output['temp_ctr_default_value'] + + def schedule_auto_startup_outputs(self, rpi_output, delay_seconds): + sufix = 'auto_startup' + if rpi_output['output_type'] == 'regular': + value = False if rpi_output['active_low'] else True + self.add_regular_output_to_queue( + delay_seconds, rpi_output, value, sufix) + if rpi_output['output_type'] == 'pwm' and not rpi_output['pwm_temperature_linked']: + value = self.to_int(rpi_output['default_duty_cycle']) + self.add_pwm_output_to_queue( + delay_seconds, rpi_output, value, sufix) + if (rpi_output['output_type'] == 'neopixel_indirect' or rpi_output['output_type'] == 'neopixel_direct'): + red, green, blue = self.get_color_from_rgb( + rpi_output['default_neopixel_color']) + self.add_neopixel_output_to_queue( + rpi_output, delay_seconds, red, green, blue, sufix) + if rpi_output['output_type'] == 'temp_hum_control': + rpi_output['temp_ctr_set_value'] = rpi_output['temp_ctr_default_value'] + + def get_color_from_rgb(self, stringColor): + stringColor = stringColor.replace('rgb(', '') + red = stringColor[:stringColor.index(',')] + stringColor = stringColor[stringColor.index(',') + 1:] + green = stringColor[:stringColor.index(',')] + stringColor = stringColor[stringColor.index(',') + 1:] + blue = stringColor[:stringColor.index(')')] + return red, green, blue + + def get_shutdown_delay_from_output(self, rpi_output): + shutdown_time = rpi_output['shutdown_time'] + + shut_down_date_time = self.create_date(shutdown_time) + + if shut_down_date_time < datetime.now(): + shut_down_date_time = shut_down_date_time + timedelta(days=1) + + delay_seconds = (shut_down_date_time - datetime.now()).total_seconds() + + return delay_seconds + + def add_neopixel_output_to_queue(self, rpi_output, delay_seconds, red, green, blue, sufix): + gpio_pin = rpi_output['gpio_pin'] + ledCount = rpi_output['neopixel_count'] + ledBrightness = rpi_output['neopixel_brightness'] + address = rpi_output['microcontroller_address'] + neopixel_direct = rpi_output['output_type'] == 'neopixel_direct' + index_id = self.to_int(rpi_output['index_id']) + + queue_id = '{0!s}_{1!s}'.format(index_id, sufix) + + thread = threading.Timer(delay_seconds, + self.send_neopixel_command, + args=[gpio_pin, ledCount, ledBrightness, red, green, blue, address, neopixel_direct, index_id, queue_id]) + + self.event_queue.append(dict(queue_id=queue_id, thread=thread)) + + def add_pwm_output_to_queue(self, delay_seconds, rpi_output, value, sufix): + queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) + + thread = threading.Timer(delay_seconds, + self.write_pwm, + args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) + + self.event_queue.append(dict(queue_id=queue_id, thread=thread)) + + def schedule_pwm_duty_on_queue(self, delay_seconds, rpi_output, value): + queue_id = '{0!s}_{1!s}'.format( + rpi_output['index_id'], "pwm_linked_temp") + thread = threading.Timer(delay_seconds, + self.set_pwm_duty_cycle, + args=[rpi_output, value, queue_id]) + self.event_queue.append(dict(queue_id=queue_id, thread=thread)) + + def set_pwm_duty_cycle(self, rpi_output, value, queue_id): + rpi_output['duty_cycle'] = value + if queue_id is not None: + self.stop_queue_item(queue_id) + + def add_regular_output_to_queue(self, delay_seconds, rpi_output, value, sufix): + queue_id = '{0!s}_{1!s}'.format(rpi_output['index_id'], sufix) + + thread = threading.Timer(delay_seconds, + self.write_gpio, + args=[self.to_int(rpi_output['gpio_pin']), value, queue_id]) + + self.event_queue.append(dict(queue_id=queue_id, thread=thread)) + + def get_startup_delay_from_output(self, rpi_output): + start_up_time = rpi_output['startup_time'] + if self.is_hour(start_up_time): + start_up_date_time = self.create_date(start_up_time) + if start_up_date_time < datetime.now(): + delay_seconds = 0.0 + else: + delay_seconds = (start_up_date_time - + datetime.now()).total_seconds() + else: + delay_seconds = self.to_float( + rpi_output['startup_time']) + return delay_seconds + + # ~~ SettingsPlugin mixin def on_settings_save(self, data): - - self._logger.info("data: %s", data) - - outputsBeforeSave = self.getOutputList() + outputsBeforeSave = self.get_output_list() octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - self.temperature_reading = self._settings.get(["temperature_reading"]) - self.temperature_control = self._settings.get(["temperature_control"]) self.rpi_outputs = self._settings.get(["rpi_outputs"]) self.rpi_inputs = self._settings.get(["rpi_inputs"]) self.notifications = self._settings.get(["notifications"]) - outputsAfterSave = self.getOutputList() + outputsAfterSave = self.get_output_list() commonPins = list(set(outputsBeforeSave) & set(outputsAfterSave)) for pin in (pin for pin in outputsBeforeSave if pin not in commonPins): - self.clearChannel(pin) + self.clear_channel(pin) - self.previous_rpi_outputs = commonPins; - self.clearGPIO() + self.rpi_outputs_not_changed = commonPins + self.clear_gpio() - if self._settings.get(["debug"]) == True: - self._logger.info("temperature_reading: %s", self.temperature_reading) - self._logger.info("temperature_control: %s", self.temperature_control) + if self._settings.get(["debug"]) is True: self._logger.info("rpi_outputs: %s", self.rpi_outputs) self._logger.info("rpi_inputs: %s", self.rpi_inputs) - self.startGPIO() - self.configureGPIO() - + self.setup_gpio() + self.configure_gpio() + self.generate_temp_hum_control_status() def get_settings_defaults(self): return dict( - temperature_reading = [{ 'isEnabled': False, 'gpioPin': 4, 'useFahrenheit':False, 'sensorType':'','sensorAddress':0}], - temperature_control = [{ 'isEnabled': False, 'controlType':'heater', 'gpioPin': 17, 'activeLow': True, 'autoStartup': False,'defaultTemp':0}], - rpi_outputs = [], - rpi_inputs = [], - filamentSensorGcode = "G91 ;Set Relative Mode \n" + - "G1 E-5.000000 F500 ;Retract 5mm\n" + - "G1 Z15 F300 ;move Z up 15mm\n" + - "G90 ;Set Absolute Mode\n " + - "G1 X20 Y20 F9000 ;Move to hold position\n" + - "G91 ;Set Relative Mode\n" + - "G1 E-40 F500 ;Retract 40mm\n" + - "M0 ;Idle Hold\n" + - "G90 ;Set Absolute Mode\n" + - "G1 F5000 ;Set speed limits\n" + - "G28 X0 Y0 ;Home X Y\n" + - "M82 ;Set extruder to Absolute Mode\n" + - "G92 E0 ;Set Extruder to 0", - debug=True, + rpi_outputs=[], + rpi_inputs=[], + filament_sensor_gcode="G91 ;Set Relative Mode \n" + + "G1 E-5.000000 F500 ;Retract 5mm\n" + + "G1 Z15 F300 ;move Z up 15mm\n" + + "G90 ;Set Absolute Mode\n " + + "G1 X20 Y20 F9000 ;Move to hold position\n" + + "G91 ;Set Relative Mode\n" + + "G1 E-40 F500 ;Retract 40mm\n" + + "M0 ;Idle Hold\n" + + "G90 ;Set Absolute Mode\n" + + "G1 F5000 ;Set speed limits\n" + + "G28 X0 Y0 ;Home X Y\n" + + "M82 ;Set extruder to Absolute Mode\n" + + "G92 E0 ;Set Extruder to 0", + use_sudo=True, + debug=False, + gcode_control=False, + debug_temperature_log=False, useBoardPinNumber=False, - filamentSensorTimeout=120, - notificationProvider = "disabled", - apiKEY = "", - event_name="printer_event", - showTempNavbar=False, - notifications=[{'printFinish':True,'filamentChange':True,'printerAction':True,'temperatureAction':True,'gpioAction':True}] + notification_provider="disabled", + notification_api_key="", + notification_event_name="printer_event", + notifications=[{'printFinish': True, 'filamentChange': True, + 'printer_action': True, 'temperatureAction': True, 'gpioAction': True}] ) - #~~ TemplatePlugin + # ~~ TemplatePlugin def get_template_configs(self): return [ - dict(type="settings", custom_bindings=True), - dict(type="tab", custom_bindings=True) + dict(type="settings", custom_bindings=True), + dict(type="tab", custom_bindings=True), + dict(type="navbar", custom_bindings=True, + suffix="_1", classes=["dropdown"]), + dict(type="navbar", custom_bindings=True, + template="enclosure_navbar_input.jinja2", suffix="_2", classes=["dropdown"]) ] - ##~~ AssetPlugin mixin + # ~~ AssetPlugin mixin def get_assets(self): return dict( - js=["js/enclosure.js","js/bootstrap-colorpicker.min.js"], - css=["css/bootstrap-colorpicker.css"] + js=["js/enclosure.js", "js/bootstrap-colorpicker.min.js"], + css=["css/bootstrap-colorpicker.css", "css/enclosure.css"] ) - ##~~ Softwareupdate hook + # ~~ Softwareupdate hook def get_update_information(self): return dict( enclosure=dict( displayName="Enclosure Plugin", displayVersion=self._plugin_version, - # version check: github repository type="github_release", user="vitormhenrique", repo="OctoPrint-Enclosure", current=self._plugin_version, - # update method: pip pip="https://github.com/vitormhenrique/OctoPrint-Enclosure/archive/{target_version}.zip" ) ) + def hook_gcode_queuing(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): + if self._settings.get(["gcode_control"]) is False: + return + + if cmd.strip().startswith("ENC"): + if self._settings.get(["debug"]) is True: + self._logger.info("Gcode queuing: %s", cmd) + index_id = self.to_int(self.get_gcode_value(cmd, 'O')) + for output in [item for item in self.rpi_outputs if item['index_id'] == index_id]: + if output['output_type'] == 'regular': + set_value = self.to_int(self.get_gcode_value(cmd, 'S')) + set_value = self.constrain(set_value, 0, 1) + value = True if set_value == 1 else False + value = (not value) if output['active_low'] else value + self.write_gpio(self.to_int(output['gpio_pin']), value) + comm_instance._log( + "Setting REGULAR output %s to value %s" % (index_id, value)) + return + if output['output_type'] == 'pwm': + set_value = self.to_int(self.get_gcode_value(cmd, 'S')) + set_value = self.constrain(set_value, 0, 100) + output['duty_cycle'] = set_value + self.write_pwm(self.to_int(output['gpio_pin']), set_value) + comm_instance._log( + "Setting PWM output %s to value %s" % (index_id, set_value)) + return + if output['output_type'] == 'neopixel_indirect' or output['output_type'] == 'neopixel_direct': + red = self.get_gcode_value(cmd, 'R') + green = self.get_gcode_value(cmd, 'G') + blue = self.get_gcode_value(cmd, 'B') + + led_count = output['neopixel_count'] + led_brightness = output['neopixel_brightness'] + address = output['microcontroller_address'] + + index_id = self.to_int(output['index_id']) + + neopixel_dirrect = output['output_type'] == 'neopixel_direct' + + self.send_neopixel_command( + self.to_int(output['gpio_pin']), + led_count, led_brightness, red, green, blue, address, neopixel_dirrect, index_id) + comm_instance._log( + "Setting NEOPIXEL output %s to red: %s green: %s blue: %s" % (index_id, red, green, blue)) + return + if output['output_type'] == 'temp_hum_control': + set_value = self.to_float(self.get_gcode_value(cmd, 'S')) + should_wait = self.to_int(self.get_gcode_value(cmd, 'W')) + if should_wait == 1 and self._printer.is_printing(): + self._printer.pause_print() + self.waiting_temperature.append(index_id) + output['temp_ctr_set_value'] = set_value + self.update_ui_set_temperature() + self.handle_temp_hum_control() + comm_instance._log( + "Setting TEMP/HUM control output %s to value %s" % (index_id, set_value)) + return + + __plugin_name__ = "Enclosure Plugin" + def __plugin_load__(): global __plugin_implementation__ __plugin_implementation__ = EnclosurePlugin() global __plugin_hooks__ __plugin_hooks__ = { + "octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.hook_gcode_queuing, "octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information } diff --git a/octoprint_enclosure/neopixel_direct.py b/octoprint_enclosure/neopixel_direct.py new file mode 100644 index 0000000..cb038b2 --- /dev/null +++ b/octoprint_enclosure/neopixel_direct.py @@ -0,0 +1,31 @@ +from neopixel import * +import sys +import time + +LED_INVERT = False +LED_DMA = 5 +LED_FREQ_HZ = 800000 + +if len(sys.argv) == 8: + LED_PIN = int(sys.argv[1]) + LED_COUNT = int(sys.argv[2]) + LED_BRIGHTNESS = int(sys.argv[3]) + red = int(sys.argv[4]) + green = int(sys.argv[5]) + blue = int(sys.argv[6]) + address = int(sys.argv[7], 16) +else: + print("fail") + sys.exit(1) + +strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT) +strip.begin() + +color = Color(green, red, blue) + +for i in range(LED_COUNT): + strip.setPixelColor(i, color) + +strip.show() + +print("ok") diff --git a/octoprint_enclosure/neopixel.py b/octoprint_enclosure/neopixel_indirect.py similarity index 100% rename from octoprint_enclosure/neopixel.py rename to octoprint_enclosure/neopixel_indirect.py diff --git a/octoprint_enclosure/static/css/bootstrap-colorpicker.css b/octoprint_enclosure/static/css/bootstrap-colorpicker.css old mode 100755 new mode 100644 index 2429962..26cb0de --- a/octoprint_enclosure/static/css/bootstrap-colorpicker.css +++ b/octoprint_enclosure/static/css/bootstrap-colorpicker.css @@ -1,230 +1,230 @@ -/*! - * Bootstrap Colorpicker v2.5.1 - * https://itsjavi.com/bootstrap-colorpicker/ - * - * Originally written by (c) 2012 Stefan Petre - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0.txt - * - */ -.colorpicker-saturation { - width: 100px; - height: 100px; - background-image: url("../img/bootstrap-colorpicker/saturation.png"); - cursor: crosshair; - float: left; -} -.colorpicker-saturation i { - display: block; - height: 5px; - width: 5px; - border: 1px solid #000; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - position: absolute; - top: 0; - left: 0; - margin: -4px 0 0 -4px; -} -.colorpicker-saturation i b { - display: block; - height: 5px; - width: 5px; - border: 1px solid #fff; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; -} -.colorpicker-hue, -.colorpicker-alpha { - width: 15px; - height: 100px; - float: left; - cursor: row-resize; - margin-left: 4px; - margin-bottom: 4px; -} -.colorpicker-hue i, -.colorpicker-alpha i { - display: block; - height: 1px; - background: #000; - border-top: 1px solid #fff; - position: absolute; - top: 0; - left: 0; - width: 100%; - margin-top: -1px; -} -.colorpicker-hue { - background-image: url("../img/bootstrap-colorpicker/hue.png"); -} -.colorpicker-alpha { - background-image: url("../img/bootstrap-colorpicker/alpha.png"); - display: none; -} -.colorpicker-saturation, -.colorpicker-hue, -.colorpicker-alpha { - background-size: contain; -} -.colorpicker { - padding: 4px; - min-width: 130px; - margin-top: 1px; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - z-index: 2500; -} -.colorpicker:before, -.colorpicker:after { - display: table; - content: ""; - line-height: 0; -} -.colorpicker:after { - clear: both; -} -.colorpicker:before { - content: ''; - display: inline-block; - border-left: 7px solid transparent; - border-right: 7px solid transparent; - border-bottom: 7px solid #ccc; - border-bottom-color: rgba(0, 0, 0, 0.2); - position: absolute; - top: -7px; - left: 6px; -} -.colorpicker:after { - content: ''; - display: inline-block; - border-left: 6px solid transparent; - border-right: 6px solid transparent; - border-bottom: 6px solid #ffffff; - position: absolute; - top: -6px; - left: 7px; -} -.colorpicker div { - position: relative; -} -.colorpicker.colorpicker-with-alpha { - min-width: 140px; -} -.colorpicker.colorpicker-with-alpha .colorpicker-alpha { - display: block; -} -.colorpicker-color { - height: 10px; - margin-top: 5px; - clear: both; - background-image: url("../img/bootstrap-colorpicker/alpha.png"); - background-position: 0 100%; -} -.colorpicker-color div { - height: 10px; -} -.colorpicker-selectors { - display: none; - height: 10px; - margin-top: 5px; - clear: both; -} -.colorpicker-selectors i { - cursor: pointer; - float: left; - height: 10px; - width: 10px; -} -.colorpicker-selectors i + i { - margin-left: 3px; -} -.colorpicker-element .input-group-addon i, -.colorpicker-element .add-on i { - display: inline-block; - cursor: pointer; - height: 16px; - vertical-align: text-top; - width: 16px; -} -.colorpicker.colorpicker-inline { - position: relative; - display: inline-block; - float: none; - z-index: auto; -} -.colorpicker.colorpicker-horizontal { - width: 110px; - min-width: 110px; - height: auto; -} -.colorpicker.colorpicker-horizontal .colorpicker-saturation { - margin-bottom: 4px; -} -.colorpicker.colorpicker-horizontal .colorpicker-color { - width: 100px; -} -.colorpicker.colorpicker-horizontal .colorpicker-hue, -.colorpicker.colorpicker-horizontal .colorpicker-alpha { - width: 100px; - height: 15px; - float: left; - cursor: col-resize; - margin-left: 0px; - margin-bottom: 4px; -} -.colorpicker.colorpicker-horizontal .colorpicker-hue i, -.colorpicker.colorpicker-horizontal .colorpicker-alpha i { - display: block; - height: 15px; - background: #ffffff; - position: absolute; - top: 0; - left: 0; - width: 1px; - border: none; - margin-top: 0px; -} -.colorpicker.colorpicker-horizontal .colorpicker-hue { - background-image: url("../img/bootstrap-colorpicker/hue-horizontal.png"); -} -.colorpicker.colorpicker-horizontal .colorpicker-alpha { - background-image: url("../img/bootstrap-colorpicker/alpha-horizontal.png"); -} -.colorpicker-right:before { - left: auto; - right: 6px; -} -.colorpicker-right:after { - left: auto; - right: 7px; -} -.colorpicker-no-arrow:before { - border-right: 0; - border-left: 0; -} -.colorpicker-no-arrow:after { - border-right: 0; - border-left: 0; -} -.colorpicker.colorpicker-visible, -.colorpicker-alpha.colorpicker-visible, -.colorpicker-saturation.colorpicker-visible, -.colorpicker-hue.colorpicker-visible, -.colorpicker-selectors.colorpicker-visible { - display: block; -} -.colorpicker.colorpicker-hidden, -.colorpicker-alpha.colorpicker-hidden, -.colorpicker-saturation.colorpicker-hidden, -.colorpicker-hue.colorpicker-hidden, -.colorpicker-selectors.colorpicker-hidden { - display: none; -} -.colorpicker-inline.colorpicker-visible { - display: inline-block; -} +/*! + * Bootstrap Colorpicker v2.5.1 + * https://itsjavi.com/bootstrap-colorpicker/ + * + * Originally written by (c) 2012 Stefan Petre + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + */ +.colorpicker-saturation { + width: 100px; + height: 100px; + background-image: url("../img/bootstrap-colorpicker/saturation.png"); + cursor: crosshair; + float: left; +} +.colorpicker-saturation i { + display: block; + height: 5px; + width: 5px; + border: 1px solid #000; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; + position: absolute; + top: 0; + left: 0; + margin: -4px 0 0 -4px; +} +.colorpicker-saturation i b { + display: block; + height: 5px; + width: 5px; + border: 1px solid #fff; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +.colorpicker-hue, +.colorpicker-alpha { + width: 15px; + height: 100px; + float: left; + cursor: row-resize; + margin-left: 4px; + margin-bottom: 4px; +} +.colorpicker-hue i, +.colorpicker-alpha i { + display: block; + height: 1px; + background: #000; + border-top: 1px solid #fff; + position: absolute; + top: 0; + left: 0; + width: 100%; + margin-top: -1px; +} +.colorpicker-hue { + background-image: url("../img/bootstrap-colorpicker/hue.png"); +} +.colorpicker-alpha { + background-image: url("../img/bootstrap-colorpicker/alpha.png"); + display: none; +} +.colorpicker-saturation, +.colorpicker-hue, +.colorpicker-alpha { + background-size: contain; +} +.colorpicker { + padding: 4px; + min-width: 130px; + margin-top: 1px; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; + z-index: 2500; +} +.colorpicker:before, +.colorpicker:after { + display: table; + content: ""; + line-height: 0; +} +.colorpicker:after { + clear: both; +} +.colorpicker:before { + content: ''; + display: inline-block; + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-bottom-color: rgba(0, 0, 0, 0.2); + position: absolute; + top: -7px; + left: 6px; +} +.colorpicker:after { + content: ''; + display: inline-block; + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-bottom: 6px solid #ffffff; + position: absolute; + top: -6px; + left: 7px; +} +.colorpicker div { + position: relative; +} +.colorpicker.colorpicker-with-alpha { + min-width: 140px; +} +.colorpicker.colorpicker-with-alpha .colorpicker-alpha { + display: block; +} +.colorpicker-color { + height: 10px; + margin-top: 5px; + clear: both; + background-image: url("../img/bootstrap-colorpicker/alpha.png"); + background-position: 0 100%; +} +.colorpicker-color div { + height: 10px; +} +.colorpicker-selectors { + display: none; + height: 10px; + margin-top: 5px; + clear: both; +} +.colorpicker-selectors i { + cursor: pointer; + float: left; + height: 10px; + width: 10px; +} +.colorpicker-selectors i + i { + margin-left: 3px; +} +.colorpicker-element .input-group-addon i, +.colorpicker-element .add-on i { + display: inline-block; + cursor: pointer; + height: 16px; + vertical-align: text-top; + width: 16px; +} +.colorpicker.colorpicker-inline { + position: relative; + display: inline-block; + float: none; + z-index: auto; +} +.colorpicker.colorpicker-horizontal { + width: 110px; + min-width: 110px; + height: auto; +} +.colorpicker.colorpicker-horizontal .colorpicker-saturation { + margin-bottom: 4px; +} +.colorpicker.colorpicker-horizontal .colorpicker-color { + width: 100px; +} +.colorpicker.colorpicker-horizontal .colorpicker-hue, +.colorpicker.colorpicker-horizontal .colorpicker-alpha { + width: 100px; + height: 15px; + float: left; + cursor: col-resize; + margin-left: 0px; + margin-bottom: 4px; +} +.colorpicker.colorpicker-horizontal .colorpicker-hue i, +.colorpicker.colorpicker-horizontal .colorpicker-alpha i { + display: block; + height: 15px; + background: #ffffff; + position: absolute; + top: 0; + left: 0; + width: 1px; + border: none; + margin-top: 0px; +} +.colorpicker.colorpicker-horizontal .colorpicker-hue { + background-image: url("../img/bootstrap-colorpicker/hue-horizontal.png"); +} +.colorpicker.colorpicker-horizontal .colorpicker-alpha { + background-image: url("../img/bootstrap-colorpicker/alpha-horizontal.png"); +} +.colorpicker-right:before { + left: auto; + right: 6px; +} +.colorpicker-right:after { + left: auto; + right: 7px; +} +.colorpicker-no-arrow:before { + border-right: 0; + border-left: 0; +} +.colorpicker-no-arrow:after { + border-right: 0; + border-left: 0; +} +.colorpicker.colorpicker-visible, +.colorpicker-alpha.colorpicker-visible, +.colorpicker-saturation.colorpicker-visible, +.colorpicker-hue.colorpicker-visible, +.colorpicker-selectors.colorpicker-visible { + display: block; +} +.colorpicker.colorpicker-hidden, +.colorpicker-alpha.colorpicker-hidden, +.colorpicker-saturation.colorpicker-hidden, +.colorpicker-hue.colorpicker-hidden, +.colorpicker-selectors.colorpicker-hidden { + display: none; +} +.colorpicker-inline.colorpicker-visible { + display: inline-block; +} /*# sourceMappingURL=bootstrap-colorpicker.css.map */ \ No newline at end of file diff --git a/octoprint_enclosure/static/css/enclosure.css b/octoprint_enclosure/static/css/enclosure.css new file mode 100644 index 0000000..781a8e9 --- /dev/null +++ b/octoprint_enclosure/static/css/enclosure.css @@ -0,0 +1,74 @@ +#enclosure-table { + table-layout: fixed; + width: 100%; + margin-top: 20px; +} + +#enclosure-table th, +#enclosure-table td { + vertical-align: middle; + text-align: center; +} + + +#enclosure-table th.temperature_sensor, +#enclosure-table td.temperature_sensor { + width: 15%; + text-align: left; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +#enclosure-table th.temperature_actual, +#enclosure-table td.temperature_actual { + width: 20%; +} + +#enclosure-table th.humidity_actual, +#enclosure-table td.humidity_actual { + width: 15%; +} + +#enclosure-table th.temp_hum_control, +#enclosure-table td.temp_hum_control { + width: 15%; +} + +#enclosure-table th.temperature_target, +#enclosure-table td.temperature_target { + width: 35%; + overflow: visible; +} + +.glyphs-on { + color: blue; + text-shadow: 4px 4px 15px blue; +} + +.glyphs-off { + color: red; + text-shadow: 4px 4px 15px red; +} + +.enclosure-link{ + text-decoration: none; +} + +.enclosure-link:hover{ + text-decoration: none; +} + +.navbar-enclosure{ + text-shadow: 0 1px 0 #ccc; + color: #333; + float: none; + padding: 10px 15px 10px; + text-decoration: none; +} + +.neopixel-div{ + width: 25%; +} + + diff --git a/octoprint_enclosure/static/img/bootstrap-colorpicker/alpha-horizontal.png b/octoprint_enclosure/static/img/bootstrap-colorpicker/alpha-horizontal.png old mode 100755 new mode 100644 diff --git a/octoprint_enclosure/static/img/bootstrap-colorpicker/alpha.png b/octoprint_enclosure/static/img/bootstrap-colorpicker/alpha.png old mode 100755 new mode 100644 diff --git a/octoprint_enclosure/static/img/bootstrap-colorpicker/hue-horizontal.png b/octoprint_enclosure/static/img/bootstrap-colorpicker/hue-horizontal.png old mode 100755 new mode 100644 diff --git a/octoprint_enclosure/static/img/bootstrap-colorpicker/hue.png b/octoprint_enclosure/static/img/bootstrap-colorpicker/hue.png old mode 100755 new mode 100644 diff --git a/octoprint_enclosure/static/img/bootstrap-colorpicker/saturation.png b/octoprint_enclosure/static/img/bootstrap-colorpicker/saturation.png old mode 100755 new mode 100644 diff --git a/octoprint_enclosure/static/js/bootstrap-colorpicker.min.js b/octoprint_enclosure/static/js/bootstrap-colorpicker.min.js old mode 100755 new mode 100644 index 2cec749..7cd35b8 --- a/octoprint_enclosure/static/js/bootstrap-colorpicker.min.js +++ b/octoprint_enclosure/static/js/bootstrap-colorpicker.min.js @@ -1,5 +1,5 @@ -/*! - * Bootstrap Colorpicker v2.5.1 - * https://itsjavi.com/bootstrap-colorpicker/ - */ +/*! + * Bootstrap Colorpicker v2.5.1 + * https://itsjavi.com/bootstrap-colorpicker/ + */ !function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):jQuery&&!jQuery.fn.colorpicker&&b(jQuery)}(this,function(a){"use strict";var b=function(c,d,e,f,g){this.fallbackValue=e?e&&"undefined"!=typeof e.h?e:this.value={h:0,s:0,b:0,a:1}:null,this.fallbackFormat=f?f:"rgba",this.hexNumberSignPrefix=g===!0,this.value=this.fallbackValue,this.origFormat=null,this.predefinedColors=d?d:{},this.colors=a.extend({},b.webColors,this.predefinedColors),c&&("undefined"!=typeof c.h?this.value=c:this.setColor(String(c))),this.value||(this.value={h:0,s:0,b:0,a:1})};b.webColors={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32",transparent:"transparent"},b.prototype={constructor:b,colors:{},predefinedColors:{},getValue:function(){return this.value},setValue:function(a){this.value=a},_sanitizeNumber:function(a){return"number"==typeof a?a:isNaN(a)||null===a||""===a||void 0===a?1:""===a?0:"undefined"!=typeof a.toLowerCase?(a.match(/^\./)&&(a="0"+a),Math.ceil(100*parseFloat(a))/100):1},isTransparent:function(a){return!(!a||!("string"==typeof a||a instanceof String))&&(a=a.toLowerCase().trim(),"transparent"===a||a.match(/#?00000000/)||a.match(/(rgba|hsla)\(0,0,0,0?\.?0\)/))},rgbaIsTransparent:function(a){return 0===a.r&&0===a.g&&0===a.b&&0===a.a},setColor:function(a){if(a=a.toLowerCase().trim()){if(this.isTransparent(a))return this.value={h:0,s:0,b:0,a:0},!0;var b=this.parse(a);b?(this.value=this.value={h:b.h,s:b.s,b:b.b,a:b.a},this.origFormat||(this.origFormat=b.format)):this.fallbackValue&&(this.value=this.fallbackValue)}return!1},setHue:function(a){this.value.h=1-a},setSaturation:function(a){this.value.s=a},setBrightness:function(a){this.value.b=1-a},setAlpha:function(a){this.value.a=Math.round(parseInt(100*(1-a),10)/100*100)/100},toRGB:function(a,b,c,d){0===arguments.length&&(a=this.value.h,b=this.value.s,c=this.value.b,d=this.value.a),a*=360;var e,f,g,h,i;return a=a%360/60,i=c*b,h=i*(1-Math.abs(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],{r:Math.round(255*e),g:Math.round(255*f),b:Math.round(255*g),a:d}},toHex:function(a,b,c,d){0===arguments.length&&(a=this.value.h,b=this.value.s,c=this.value.b,d=this.value.a);var e=this.toRGB(a,b,c,d);if(this.rgbaIsTransparent(e))return"transparent";var f=(this.hexNumberSignPrefix?"#":"")+((1<<24)+(parseInt(e.r)<<16)+(parseInt(e.g)<<8)+parseInt(e.b)).toString(16).slice(1);return f},toHSL:function(a,b,c,d){0===arguments.length&&(a=this.value.h,b=this.value.s,c=this.value.b,d=this.value.a);var e=a,f=(2-b)*c,g=b*c;return g/=f>0&&f<=1?f:2-f,f/=2,g>1&&(g=1),{h:isNaN(e)?0:e,s:isNaN(g)?0:g,l:isNaN(f)?0:f,a:isNaN(d)?0:d}},toAlias:function(a,b,c,d){var e,f=0===arguments.length?this.toHex():this.toHex(a,b,c,d),g="alias"===this.origFormat?f:this.toString(this.origFormat,!1);for(var h in this.colors)if(e=this.colors[h].toLowerCase().trim(),e===f||e===g)return h;return!1},RGBtoHSB:function(a,b,c,d){a/=255,b/=255,c/=255;var e,f,g,h;return g=Math.max(a,b,c),h=g-Math.min(a,b,c),e=0===h?null:g===a?(b-c)/h:g===b?(c-a)/h+2:(a-b)/h+4,e=(e+360)%6*60/360,f=0===h?0:h/g,{h:this._sanitizeNumber(e),s:f,b:g,a:this._sanitizeNumber(d)}},HueToRGB:function(a,b,c){return c<0?c+=1:c>1&&(c-=1),6*c<1?a+(b-a)*c*6:2*c<1?b:3*c<2?a+(b-a)*(2/3-c)*6:a},HSLtoRGB:function(a,b,c,d){b<0&&(b=0);var e;e=c<=.5?c*(1+b):c+b-c*b;var f=2*c-e,g=a+1/3,h=a,i=a-1/3,j=Math.round(255*this.HueToRGB(f,e,g)),k=Math.round(255*this.HueToRGB(f,e,h)),l=Math.round(255*this.HueToRGB(f,e,i));return[j,k,l,this._sanitizeNumber(d)]},parse:function(b){if(0===arguments.length)return!1;var c,d,e=this,f=!1,g="undefined"!=typeof this.colors[b];return g&&(b=this.colors[b].toLowerCase().trim()),a.each(this.stringParsers,function(a,h){var i=h.re.exec(b);return c=i&&h.parse.apply(e,[i]),!c||(f={},d=g?"alias":h.format?h.format:e.getValidFallbackFormat(),f=d.match(/hsla?/)?e.RGBtoHSB.apply(e,e.HSLtoRGB.apply(e,c)):e.RGBtoHSB.apply(e,c),f instanceof Object&&(f.format=d),!1)}),f},getValidFallbackFormat:function(){var a=["rgba","rgb","hex","hsla","hsl"];return this.origFormat&&a.indexOf(this.origFormat)!==-1?this.origFormat:this.fallbackFormat&&a.indexOf(this.fallbackFormat)!==-1?this.fallbackFormat:"rgba"},toString:function(a,c){a=a||this.origFormat||this.fallbackFormat,c=c||!1;var d=!1;switch(a){case"rgb":return d=this.toRGB(),this.rgbaIsTransparent(d)?"transparent":"rgb("+d.r+","+d.g+","+d.b+")";case"rgba":return d=this.toRGB(),"rgba("+d.r+","+d.g+","+d.b+","+d.a+")";case"hsl":return d=this.toHSL(),"hsl("+Math.round(360*d.h)+","+Math.round(100*d.s)+"%,"+Math.round(100*d.l)+"%)";case"hsla":return d=this.toHSL(),"hsla("+Math.round(360*d.h)+","+Math.round(100*d.s)+"%,"+Math.round(100*d.l)+"%,"+d.a+")";case"hex":return this.toHex();case"alias":return d=this.toAlias(),d===!1?this.toString(this.getValidFallbackFormat()):c&&!(d in b.webColors)&&d in this.predefinedColors?this.predefinedColors[d]:d;default:return d}},stringParsers:[{re:/rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*?\)/,format:"rgb",parse:function(a){return[a[1],a[2],a[3],1]}},{re:/rgb\(\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*?\)/,format:"rgb",parse:function(a){return[2.55*a[1],2.55*a[2],2.55*a[3],1]}},{re:/rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d*(?:\.\d+)?)\s*)?\)/,format:"rgba",parse:function(a){return[a[1],a[2],a[3],a[4]]}},{re:/rgba\(\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*(?:,\s*(\d*(?:\.\d+)?)\s*)?\)/,format:"rgba",parse:function(a){return[2.55*a[1],2.55*a[2],2.55*a[3],a[4]]}},{re:/hsl\(\s*(\d*(?:\.\d+)?)\s*,\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*?\)/,format:"hsl",parse:function(a){return[a[1]/360,a[2]/100,a[3]/100,a[4]]}},{re:/hsla\(\s*(\d*(?:\.\d+)?)\s*,\s*(\d*(?:\.\d+)?)\%\s*,\s*(\d*(?:\.\d+)?)\%\s*(?:,\s*(\d*(?:\.\d+)?)\s*)?\)/,format:"hsla",parse:function(a){return[a[1]/360,a[2]/100,a[3]/100,a[4]]}},{re:/#?([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,format:"hex",parse:function(a){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16),1]}},{re:/#?([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/,format:"hex",parse:function(a){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16),1]}}],colorNameToHex:function(a){return"undefined"!=typeof this.colors[a.toLowerCase()]&&this.colors[a.toLowerCase()]}};var c={horizontal:!1,inline:!1,color:!1,format:!1,input:"input",container:!1,component:".add-on, .input-group-addon",fallbackColor:!1,fallbackFormat:"hex",hexNumberSignPrefix:!0,sliders:{saturation:{maxLeft:100,maxTop:100,callLeft:"setSaturation",callTop:"setBrightness"},hue:{maxLeft:0,maxTop:100,callLeft:!1,callTop:"setHue"},alpha:{maxLeft:0,maxTop:100,callLeft:!1,callTop:"setAlpha"}},slidersHorz:{saturation:{maxLeft:100,maxTop:100,callLeft:"setSaturation",callTop:"setBrightness"},hue:{maxLeft:100,maxTop:0,callLeft:"setHue",callTop:!1},alpha:{maxLeft:100,maxTop:0,callLeft:"setAlpha",callTop:!1}},template:'