| @ -0,0 +1,5 @@ | |||
| _build/* | |||
| _checkouts/* | |||
| src/config.erl | |||
| rebar.lock | |||
| *.ignore | |||
| @ -0,0 +1,674 @@ | |||
| GNU GENERAL PUBLIC LICENSE | |||
| Version 3, 29 June 2007 | |||
| Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> | |||
| 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. | |||
| <one line to give the program's name and a brief idea of what it does.> | |||
| Copyright (C) <year> <name of author> | |||
| 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 <https://www.gnu.org/licenses/>. | |||
| 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: | |||
| <program> Copyright (C) <year> <name of author> | |||
| 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 | |||
| <https://www.gnu.org/licenses/>. | |||
| 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 | |||
| <https://www.gnu.org/licenses/why-not-lgpl.html>. | |||
| @ -0,0 +1,16 @@ | |||
| # `wifi` Application | |||
| Welcome to the `wifi` AtomVM application. | |||
| The `wifi` AtomVM application demonstrates how to configure an ESP32 device for both Station (STA) and Access Point (AP) modes, allowing an ESP32 device to join an existing WiFi network or to serve as a WiFi access point for other devices. | |||
| For more information about programming on the AtomVM platform, see the [AtomVM Programmers Guide](https://www.atomvm.net/doc/master/programmers-guide.html). | |||
| For general information about building and executing Erlang AtomVM example programs, see the Erlang example program [README](../README.md). | |||
| > **IMPORTANT** If you are running this example program on a device that supports WiFi (e.g., the ESP32 or Pico W), you must first copy the `src/config.erl-template` file to set `src/config.erl` and edit the WiFi Access Point SSID and PSK to which the ESP32 device is to connect before building this application: | |||
| sta => [ | |||
| {ssid, "my_sta_ssid"}, | |||
| {psk, "my_sta_psk"} | |||
| ] | |||
| @ -0,0 +1,16 @@ | |||
| {erl_opts, [debug_info]}. | |||
| {deps, [ | |||
| {mqtt_client, {git, "https://github.com/atomvm/atomvm_mqtt_client.git", {branch, "master"}}}, | |||
| {atomvm_adc, {git, "https://github.com/atomvm/atomvm_adc.git", {branch, "master"}}} | |||
| ]}. | |||
| {plugins, [ | |||
| atomvm_rebar3_plugin | |||
| ]}. | |||
| {atomvm_rebar3_plugin, [ | |||
| {packbeam, [prune]} | |||
| ]}. | |||
| {profiles, [ | |||
| {check, [ | |||
| {plugins, [erlfmt]} | |||
| ]} | |||
| ]}. | |||
| @ -0,0 +1,12 @@ | |||
| {application, airconditioner, [ | |||
| {description, "An AtomVM application for controlling a window air conditioner."}, | |||
| {vsn, "1.0.0"}, | |||
| {registered, []}, | |||
| {applications, [ | |||
| kernel, stdlib | |||
| ]}, | |||
| {env, []}, | |||
| {modules, []}, | |||
| {licenses, ["GPL v3"]}, | |||
| {links, []} | |||
| ]}. | |||
| @ -0,0 +1,86 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(?APPNAME). | |||
| -behaviour(supervisor). | |||
| -export([start/0]). | |||
| -export([init/1]). | |||
| -define(SERVER, ?MODULE). | |||
| start() -> | |||
| io:format("========================================~n"), | |||
| io:format("==== [ RuhNet - https://ruhnet.co ] ====~n"), | |||
| io:format("========================================~n"), | |||
| supervisor:start_link({local, ?SERVER}, ?MODULE, []), | |||
| timer:sleep(infinity). | |||
| %%% if this supervisor dies, since it is linked to this main process it | |||
| %%% will die too, and trigger a restart of the device (IF you have set | |||
| %%% the auto-restart on exit in your AtomVM compile config.) | |||
| init([]) -> | |||
| io:format("Starting supervisor '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| setup_pins(), | |||
| util:beep(220, 200), | |||
| util:beep(440, 600), | |||
| util:beep(180, 100), | |||
| util:beep(440, 200), | |||
| util:beep(180, 50), | |||
| MaxRestarts = 5, % Kill everyone and die if more than MaxRestarts failures per MaxSecBetweenRestarts seconds | |||
| MaxSecBetweenRestarts = 10, | |||
| % Worker1 = {led, {led, start_link, []}, permanent, 2000, worker, [led]}, | |||
| Debugger = worker(debugger, start_link, []), | |||
| LedControl = worker(led, start_link, []), | |||
| Thermostat = worker(thermostat, start_link, []), | |||
| TempReader = worker(temperature, start_link, []), | |||
| ButtonWatcher = worker(button_watcher, start_link, []), | |||
| MainControl = worker(control, start_link, []), | |||
| NetworkSup = supervisor(network_sup, []), | |||
| {ok, {{one_for_one, MaxRestarts, MaxSecBetweenRestarts}, [ | |||
| Debugger | |||
| ,LedControl | |||
| ,TempReader | |||
| ,Thermostat | |||
| ,MainControl | |||
| %,ButtonWatcher | |||
| ,NetworkSup | |||
| ] }}. | |||
| %Create a worker spec: | |||
| worker(Name, StartFunc, Args) -> | |||
| {Name, {Name, StartFunc, Args}, permanent, brutal_kill, worker, [Name]}. | |||
| supervisor(Name, Args) -> | |||
| {Name, {Name, start_link, Args}, permanent, brutal_kill, supervisor, [Name]}. | |||
| setup_pins() -> | |||
| io:format("Setting pin modes...~n"), | |||
| setup_pins(?OUTPUT_PINS, output), | |||
| setup_pins(?INPUT_PINS, input). | |||
| setup_pins([Pin|RemainingPins], Mode) -> | |||
| gpio:set_pin_mode(Pin, Mode), | |||
| %gpio:set_direction(GPIO, Pin, Mode), %gpio:start() first for Pid of GPIO | |||
| case Mode of | |||
| output -> | |||
| case lists:member(Pin, ?GENERIC_OUTPUTS) of %check if this pin is a generic output | |||
| true -> | |||
| case ?GENERIC_OUTPUT_ACTIVE_LOW of | |||
| true -> util:set_output(Pin, high); %turn active low generic outputs OFF by setting high. | |||
| _ -> ok | |||
| end; | |||
| _ -> ok | |||
| end; | |||
| _ -> ok | |||
| end, | |||
| setup_pins(RemainingPins, Mode); | |||
| setup_pins([], _Mode) -> | |||
| ok. | |||
| @ -0,0 +1,92 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -define(APPNAME, airconditioner). | |||
| -define(DEVICENAME, "greenwood_AC1"). | |||
| -define(NVS_NAMESPACE, ac). | |||
| -define(DEBUG_ENABLED_BY_DEFAULT, console_only). % true|false|console_only|mqtt_only | |||
| %PINS/PORTS/PERIPHERALS | |||
| -define(COMPRESSOR_LED, 2). % | |||
| -define(STATUS_LED, 0). % | |||
| -define(STATUS_LED2, 15). % | |||
| -define(COMPRESSOR, 4). % | |||
| -define(BEEPER, 5). %VSPI | |||
| -define(FAN1, 25). % | |||
| -define(FAN2, 26). % | |||
| -define(FAN3, 27). % | |||
| -define(OUT1, 23). %VSPI | |||
| %-define(OUT2, 33). %ADC1 CH5 | |||
| %-define(THERMISTOR4, 33). %ADC1 CH5 | |||
| -define(THERMISTOR3, 32). %ADC1 CH4 | |||
| -define(THERMISTOR1, 34). %ADC1 CH6 INPUT ONLY | |||
| -define(THERMISTOR2, 35). %ADC1 CH7 INPUT ONLY | |||
| -define(BUTTON_MODE, 18). %VSPI | |||
| -define(BUTTON_FAN, 19). %VSPI | |||
| -define(BUTTON_TEMP_UP, 36). %INPUT ONLY | |||
| -define(BUTTON_TEMP_DOWN, 39). %INPUT ONLY | |||
| -define(SDA, 21). %SDA | |||
| -define(SCL, 22). %SDL | |||
| -define(SPI_MISO, 12). %HSPI | |||
| -define(SPI_MOSI, 13). %HSPI | |||
| -define(SPI_SCK, 14). %HSPI | |||
| -define(SPI_CS, 15). %HSPI | |||
| -define(GENERIC_OUTPUT_ACTIVE_LOW, true). | |||
| -define(GENERIC_OUTPUTS, [?OUT1]). | |||
| -define(OUTPUT_PINS, [ | |||
| ?STATUS_LED | |||
| ,?STATUS_LED2 | |||
| ,?FAN1 | |||
| ,?FAN2 | |||
| ,?FAN3 | |||
| ,?COMPRESSOR | |||
| ,?COMPRESSOR_LED | |||
| ,?BEEPER | |||
| ,?OUT1 | |||
| ]). | |||
| -define(INPUT_PINS, [ | |||
| ?THERMISTOR1 | |||
| ,?THERMISTOR2 | |||
| ,?BUTTON_MODE | |||
| ,?BUTTON_FAN | |||
| ,?BUTTON_TEMP_UP | |||
| ,?BUTTON_TEMP_DOWN | |||
| ]). | |||
| %-define(MEASUREINTERVAL, 2000). | |||
| -define(SAFETY_DELAY, 360000). | |||
| -define(COIL_TEMP_LIMIT, 42). | |||
| -define(THERMOSTAT_DEFAULT, <<"67">>). %BINARY integer only, not float or integer | |||
| -define(THERMOSTAT_SPAN_DEFAULT, <<"4.0">>). %BINARY FLOAT ONLY | |||
| -define(MIN_THERMOSTAT, 55). | |||
| -define(MAX_THERMOSTAT, 99). | |||
| -define(THERMOSTAT_PUB_INTERVAL_SEC, 120). | |||
| -define(FLOAT_DECIMAL_LIMIT, 2). %format floats to this number of decimal places when converting to binary | |||
| %MQTT Topics | |||
| -define(TOPIC_AC, <<?DEVICENAME, "/AC">>). | |||
| -define(TOPIC_MAIN_STATUS, <<"status">>). %shared feed shows devices connecting | |||
| -define(TOPIC_STATUS, <<?DEVICENAME, "/status">>). | |||
| -define(TOPIC_DEBUG, <<?DEVICENAME, "/debug">>). | |||
| -define(TOPIC_TEMP_COIL, <<?DEVICENAME, "/coilTemp">>). | |||
| -define(TOPIC_TEMP1, <<?DEVICENAME, "/temp1">>). | |||
| -define(TOPIC_TEMP2, <<?DEVICENAME, "/temp2">>). | |||
| -define(TOPIC_TEMP_OUTSIDE, <<?DEVICENAME, "/tempOutside">>). | |||
| -define(TOPIC_FAN, <<?DEVICENAME, "/fan">>). | |||
| %-define(TOPIC_SPAN, <<?DEVICENAME, "/span">>). | |||
| -define(TOPIC_THERMOSTAT_SET, <<?DEVICENAME, "/thermostatSet">>). | |||
| -define(TOPIC_THERMOSTAT, <<?DEVICENAME, "/thermostat">>). | |||
| -define(TOPIC_OUT1, <<?DEVICENAME, "/out1">>). | |||
| @ -0,0 +1,60 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(button_watcher). | |||
| -export([start_link/0, init/1]). | |||
| start_link() -> | |||
| io:format("Starting '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| init([]). | |||
| %timer:sleep(1). | |||
| init(_) -> | |||
| io:format("[~p:~p] Starting...~n", [?MODULE, ?FUNCTION_NAME]), | |||
| led:flash(?STATUS_LED, 20, 20), | |||
| %_Pid = spawn_link(?MODULE, read_buttons, []), | |||
| %{ok, self()}. | |||
| Pid = spawn(fun read_buttons/0), | |||
| {ok, Pid}. | |||
| read_buttons() -> | |||
| case gpio:digital_read(?BUTTON_MODE) of | |||
| low -> | |||
| control:cycle_mode(), | |||
| io:format("[~p:~p] Mode button (~p) pressed!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_MODE]); | |||
| high -> | |||
| io:format("[~p:~p] Mode button (~p) released!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_MODE]) | |||
| end, | |||
| case gpio:digital_read(?BUTTON_FAN) of | |||
| low -> | |||
| control:cycle_fan(), | |||
| io:format("[~p:~p] Fan button (~p) pressed!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_FAN]); | |||
| high -> | |||
| io:format("[~p:~p] Fan button (~p) released!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_FAN]) | |||
| end, | |||
| case gpio:digital_read(?BUTTON_TEMP_UP) of | |||
| low -> | |||
| thermostat:up(), | |||
| io:format("[~p:~p] Temp up button (~p) pressed!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_TEMP_UP]); | |||
| high -> | |||
| io:format("[~p:~p] Temp up button (~p) released!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_TEMP_UP]) | |||
| end, | |||
| case gpio:digital_read(?BUTTON_TEMP_DOWN) of | |||
| low -> | |||
| thermostat:down(), | |||
| io:format("[~p:~p] Temp down button (~p) pressed!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_TEMP_DOWN]); | |||
| high -> | |||
| io:format("[~p:~p] Temp down button (~p) released!~n", [?MODULE, ?FUNCTION_NAME, ?BUTTON_TEMP_DOWN]) | |||
| end, | |||
| timer:sleep(50), | |||
| read_buttons(). | |||
| @ -0,0 +1,43 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -module(config). | |||
| -include("app.hrl"). | |||
| %WIFI Details | |||
| -define(WLAN_SSID, "MyNetworkSSID"). | |||
| -define(WLAN_PSK, "WifiPsswrd"). | |||
| -define(WLAN_AP_SSID, "RuhNetAirConditioner"). | |||
| -define(WLAN_AP_PSK, "WiFi_AP_Password"). | |||
| %MQTT Server Credentials | |||
| -define(MQTT_SERVER, "mqtt.lan"). | |||
| -define(MQTT_PORT, "1883"). | |||
| -define(MQTT_USERNAME, "ruhnet_ac1"). | |||
| -define(MQTT_PASSWORD, "Pa$$w0Rd"). | |||
| -export([get/0]). | |||
| get() -> | |||
| #{ mqtt => #{ | |||
| url => "mqtt://" ++ ?MQTT_USERNAME ++ ":" ++ ?MQTT_PASSWORD ++ "@" ++ ?MQTT_SERVER ++ ":" ++ ?MQTT_PORT, | |||
| username => ?MQTT_USERNAME, | |||
| password => ?MQTT_PASSWORD | |||
| }, | |||
| sta => [ | |||
| {dhcp_hostname, ?DEVICENAME}, | |||
| {ssid, ?WLAN_SSID}, | |||
| {psk, ?WLAN_PSK} | |||
| ], | |||
| ap => [ | |||
| {ssid, ?WLAN_AP_SSID}, | |||
| {psk, ?WLAN_AP_PSK}, | |||
| {ssid_hidden, false}, | |||
| {max_connections, 4} | |||
| ] | |||
| }. | |||
| @ -0,0 +1,442 @@ | |||
| % | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(control). | |||
| -behavior(gen_server). | |||
| -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). | |||
| -export([set_mode/1, cycle_mode/0, set_fan/1, cycle_fan/0, set_safe/0, all_off/0 ]). %, load/0, save/0]). | |||
| %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |||
| %%% @doc This module is the master control for the air conditioner. | |||
| %%% State is tuple list of [ | |||
| %%% {mode, off|cool|energy_saver|fan_only}, | |||
| %%% {fan speed, 1|2|3}, | |||
| %%% {compressor on|off}, | |||
| %%% {compressor_safe, safe|wait} | |||
| %%% ] | |||
| %%% Mode 'energy_saver' turns fan on/off along with compressor, while 'on', keeps fan running constantly. | |||
| %%% @end | |||
| %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |||
| start_link() -> | |||
| debugger:format("Starting '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |||
| init(_) -> | |||
| debugger:format("Starting '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| util:beep(880, 1000), | |||
| %erlang:send_after(200, self(), start), | |||
| erlang:send_after(200, ?MODULE, start), | |||
| %set initial state: | |||
| {ok, [{mode, off}, {fan, 3}, {compressor, off}, {compressor_safe, wait}] }. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| handle_cast(set_safe, _State=[{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, _CS}]) -> | |||
| debugger:format("[~p:~p] overriding wait timer; setting compressor_safety: 'safe'~n", [?MODULE, ?FUNCTION_NAME]), | |||
| spawn(fun() -> led:flash(?COMPRESSOR_LED, 50, 8) end), | |||
| {noreply, [{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, safe}] }; | |||
| handle_cast(cycle_mode, [{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| Mode = case M of | |||
| off -> cool; | |||
| cool -> energy_saver; | |||
| energy_saver -> fan_only; | |||
| fan_only -> off | |||
| end, | |||
| {noreply, [{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, CS}]}; | |||
| handle_cast(cycle_fan, [{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| Fan = case F of | |||
| 1 -> 2; | |||
| 2 -> 3; | |||
| 3 -> 1 | |||
| end, | |||
| case M of | |||
| cool -> fan(Fan); | |||
| fan_only -> fan(Fan); | |||
| energy_saver -> fan(Fan); | |||
| _ -> ok | |||
| end, | |||
| {noreply, [{mode, M}, {fan, Fan}, {compressor, C}, {compressor_safe, CS}]}; | |||
| handle_cast(_Msg, State) -> | |||
| {noreply, State}. | |||
| %%% MODE SELECTION off|cool|energy_saver|fan_only | |||
| handle_call({set_mode, Mode}, _From, _State=[{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| erlang:send(?MODULE, {set_mode, Mode}), | |||
| {reply, ok, [{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, CS}] }; | |||
| %%% FAN SELECTION 1|2|3 | |||
| handle_call({set_fan, FanNew}, _From, _State=[{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| erlang:send(?MODULE, {set_fan, FanNew}), | |||
| {reply, ok, [{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, CS}] }; | |||
| handle_call(Msg, _From, State) -> | |||
| debugger:format("[~p] Received unknown ~p message: ~p~n", [?MODULE, ?FUNCTION_NAME, Msg]), | |||
| {reply, ok, State}. | |||
| handle_info(start, State) -> | |||
| % Start first compressor safety timer | |||
| erlang:send(?MODULE, operation_loop), | |||
| %[{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CS}] = State, | |||
| %debugger:format("[control] handle_info start: State=[mode:~p f:~p comp:~p cs:~p].~n", [M, F, C, CS]), | |||
| debugger:format("[~p:~p]start Setting initial safety delay of ~p seconds...~n", [?MODULE, ?FUNCTION_NAME, trunc(?SAFETY_DELAY / 1000)]), | |||
| fan(0), %just in case we crashed and fan is still on. | |||
| compressor_set(off), %just in case we crashed and compressor is still on. | |||
| erlang:send_after(?SAFETY_DELAY, ?MODULE, {compressor_safety, safe}), %mark safe after the delay has elapsed | |||
| {noreply, State}; | |||
| handle_info({compressor_safety, CSafe}, _State=[{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, _CS}]) -> | |||
| debugger:format("[~p:~p] setting compressor_safety to: ~p~n", [?MODULE, ?FUNCTION_NAME, CSafe]), | |||
| %io:format("[control] handle_info compressorsafety:~p. State=[mode:~p f:~p comp:~p cs:~p].~n", [CSafe, M, F, C, _CS]), | |||
| %io:format("[control] handle_info compressorsafety NewState=[mode:~p f:~p comp:~p cs:~p].~n", [M, F, C, CSafe]), | |||
| {noreply, [{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CSafe}] }; | |||
| %%% MODE SELECTION off|cool|energy_saver|fan_only | |||
| handle_info({set_mode, Mode}, _State=[{mode, M}, {fan, F}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| debugger:format("[~p:~p] changing mode from ~p to new setting: ~p~n", [?MODULE, ?FUNCTION_NAME, M, Mode]), | |||
| {Comp, CSafe} = case Mode of | |||
| off -> | |||
| fan(0), | |||
| case C of | |||
| on -> erlang:send_after(?SAFETY_DELAY, ?MODULE, {compressor_safety, safe}), | |||
| {compressor_set(off), wait}; | |||
| _ -> {off, CS} | |||
| end; | |||
| fan_only -> | |||
| erlang:send(?MODULE, {set_fan, fan_on(F)}), | |||
| case C of | |||
| on -> erlang:send_after(?SAFETY_DELAY, ?MODULE, {compressor_safety, safe}), | |||
| {compressor_set(off), wait}; | |||
| _ -> {off, CS} | |||
| end; | |||
| _ -> erlang:send(?MODULE, {set_fan, F}), | |||
| {C, CS} | |||
| end, | |||
| State = [{mode, Mode}, {fan, F}, {compressor, Comp}, {compressor_safe, CSafe}], | |||
| notify(?TOPIC_STATUS, status_binary(State, "mode_changed")), | |||
| spawn(fun() -> util:beep(440, 100) end), | |||
| spawn(fun() -> led:flash(?STATUS_LED, 100, 4) end), | |||
| {noreply, State}; | |||
| %%% FAN SELECTION 1|2|3 | |||
| handle_info({set_fan, FanNew}, _State=[{mode, Mode}, {fan, FanPrev}, {compressor, C}, {compressor_safe, CS}]) -> | |||
| F = case FanNew of %this keeps the fan selection between 1 and 3. Even if fan is off (mode off) the fan should be 1, 2, or 3 | |||
| 0 -> | |||
| fan(0), | |||
| FanPrev; | |||
| _NewFan -> | |||
| spawn(fun() -> | |||
| timer:sleep(1000), %no reason for this other than to seem neat :) | |||
| fan(FanNew) | |||
| end), | |||
| case FanNew of | |||
| 3 -> 3; | |||
| 2 -> 2; | |||
| 1 -> 1; | |||
| _ -> FanPrev | |||
| end | |||
| end, | |||
| {noreply, [{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, CS}] }; | |||
| %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |||
| %%% OPERATION LOOP | |||
| %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |||
| %compressor not safe (wait) | |||
| handle_info(operation_loop, State=[{mode, Mode}, {fan, F}, {compressor, C}, {compressor_safe, wait}]) -> | |||
| debugger:format("[~p:~p] operation_loop State=[mode:~p f:~p comp:~p cs:wait].~n", [?MODULE, ?FUNCTION_NAME, Mode, F, C]), | |||
| case C of | |||
| on -> compressor_set(off); %this should never happen, but if it does, we want the log message | |||
| _ -> compressor_set_outputs(off) %silently make sure compressor is off | |||
| end, | |||
| case Mode of %allow fan to run even if compressor is in 'wait' stage | |||
| cool -> fan(F); | |||
| energy_saver -> | |||
| debugger:format("[~p] Turning fan off since we are in energy_saver mode and compressor is off...~n", [?MODULE]), | |||
| fan(0); | |||
| fan_only -> fan_on(F); | |||
| _ -> ok | |||
| end, | |||
| notify(?TOPIC_STATUS, status_binary(State)), | |||
| erlang:send_after(20000, ?MODULE, operation_loop), | |||
| {noreply, State}; | |||
| %mode is on (some form or another), and compressor is off: turn on compressor if temp/thermostat requires | |||
| handle_info(operation_loop, [{mode, Mode}, {fan, F}, {compressor, off}, {compressor_safe, safe}] ) -> | |||
| case Mode of %set the fan state first | |||
| cool -> fan(F); | |||
| fan_only -> fan(F); | |||
| _ -> ok | |||
| end, | |||
| %[{temp, Temp}, {coiltemp, CoilTemp}, _, _, _] = temperature:get_temperature(), | |||
| [{temp, Temp}, {coiltemp, CoilTemp} |_] = temperature:get_temperature(), | |||
| [{temp, TSet}, {span, Span}] = thermostat:get_thermostat(), | |||
| %HalfSpan = Span / 2, %CANNOT do math operations within an if/when clause! | |||
| {TempIsHigh, _TempIsLow} = cutoff_check(Temp, TSet, Span), | |||
| Comp = if | |||
| TempIsHigh | |||
| %Temp >= (TSet + HalfSpan) | |||
| andalso Temp /= 0 | |||
| andalso ((Mode == cool) orelse (Mode == energy_saver)) | |||
| andalso ((CoilTemp > (?COIL_TEMP_LIMIT + 5)) | |||
| orelse (CoilTemp =< 15) | |||
| orelse (CoilTemp == 0) | |||
| orelse ((CoilTemp >= 31.5) andalso (CoilTemp =< 32.5))) -> | |||
| case Mode of | |||
| energy_saver -> fan_on(F); | |||
| _ -> ok | |||
| end, | |||
| compressor_set(on); | |||
| true -> off | |||
| end, | |||
| State = [{mode, Mode}, {fan, F}, {compressor, Comp}, {compressor_safe, safe}], | |||
| debugger:format("[~p:~p] operation_loop State=[mode:~p f:~p comp:~p cs:~p].~n", [?MODULE, ?FUNCTION_NAME, Mode, F, Comp, safe]), | |||
| notify(?TOPIC_STATUS, status_binary(State)), | |||
| erlang:send_after(20000, ?MODULE, operation_loop), | |||
| {noreply, State}; | |||
| %compressor is on; regardless of mode, turn off compressor (and set safety delay), if temp requires. | |||
| handle_info(operation_loop, [{mode, Mode}, {fan, F}, {compressor, on}, {compressor_safe, safe}]) -> | |||
| [{temp, Temp}, {coiltemp, CoilTemp} |_] = temperature:get_temperature(), | |||
| [{temp, TSet}, {span, Span}] = thermostat:get_thermostat(), | |||
| %HalfSpan = Span / 2, | |||
| {_TempIsHigh, TempIsLow} = cutoff_check(Temp, TSet, Span), | |||
| {Comp, CS, StatusMsg} = if | |||
| (CoilTemp =< ?COIL_TEMP_LIMIT) | |||
| andalso ((CoilTemp =< 31.5) orelse (CoilTemp >= 32.5)) %temp sensor at 0C, (probably unplugged) | |||
| andalso (CoilTemp >= 15) %thermistor unplugged? | |||
| andalso (CoilTemp /= 0) -> | |||
| compressor_set(off), | |||
| erlang:send_after(?SAFETY_DELAY, ?MODULE, {compressor_safety, safe}), | |||
| Msg = io_lib:format("COMPRESSOR FREEZE STOP! Coil temperature is: ~.1f", [CoilTemp]), | |||
| spawn(fun() -> util:beep(880, 1000), util:beep(440, 1000), util:beep(880, 1000), util:beep(880, 1000) end), | |||
| debugger:format("~p~n", [Msg]), | |||
| {off, wait, Msg}; | |||
| %Temp =< (TSet - HalfSpan) -> %normal temp low compressor shutoff | |||
| TempIsLow -> %normal temp low compressor shutoff | |||
| compressor_set(off), | |||
| erlang:send_after(?SAFETY_DELAY, ?MODULE, {compressor_safety, safe}), | |||
| {off, wait, "thermostat compressor off"}; | |||
| true -> | |||
| fan_on(F), %Compressor is on, so just in case, we make sure fan is also on. | |||
| {on, safe, "ok"} | |||
| end, | |||
| State = [{mode, Mode}, {fan, F}, {compressor, Comp}, {compressor_safe, CS}], | |||
| %debugger:format("[~p] ~p operation_loop T=~.2f, CT=~.2f, TS=~p, S=~.1f, State=[mode:~p f:~p comp:~p cs:~p].~n", [?MODULE, ?FUNCTION_NAME, Temp, CoilTemp,TSet, Span, Mode, F, on, safe]), | |||
| debugger:format("[~p:~p] operation_loop State=[mode:~p f:~p comp:~p cs:~p].~n", [?MODULE, ?FUNCTION_NAME, Mode, F, Comp, CS]), | |||
| notify(?TOPIC_STATUS, status_binary(State, StatusMsg)), | |||
| erlang:send_after(20000, ?MODULE, operation_loop), | |||
| {noreply, State}. | |||
| %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |||
| %%% Convenience functions: | |||
| %%% | |||
| set_mode(Mode) -> % off|cool|energy_saver|fan_only | |||
| case validate_mode(Mode) of | |||
| invalid -> invalid_mode; | |||
| ValidMode -> gen_server:call(?MODULE, {set_mode, ValidMode}) | |||
| end. | |||
| set_status_led(Mode) -> | |||
| case Mode of | |||
| off -> util:set_output(?STATUS_LED, off); | |||
| on -> util:set_output(?STATUS_LED, on); | |||
| cool -> util:set_output(?STATUS_LED, on); | |||
| energy_saver -> util:set_output(?STATUS_LED, on); | |||
| fan_only -> util:set_output(?STATUS_LED, on); | |||
| _ -> util:set_output(?STATUS_LED, off) | |||
| end. | |||
| %set_mode(Mode) -> % off|cool|energy_saver|fan_only | |||
| % case mode_valid(Mode) of | |||
| % true -> gen_server:call(?MODULE, {set_mode, Mode}); | |||
| % _ -> invalid_mode | |||
| % end. | |||
| validate_mode(Mode) -> | |||
| case Mode of | |||
| off -> off; | |||
| "off" -> off; | |||
| "OFF" -> off; | |||
| cool -> cool; | |||
| "cool" -> cool; | |||
| "COOL" -> cool; | |||
| energy_saver -> energy_saver; | |||
| "energy_saver" -> energy_saver; | |||
| "ENERGY_SAVER" -> energy_saver; | |||
| fan_only -> fan_only; | |||
| "fan_only" -> fan_only; | |||
| "FAN_ONLY" -> fan_only; | |||
| fan -> fan_only; | |||
| "fan" -> fan_only; | |||
| "FAN" -> fan_only; | |||
| _ -> invalid | |||
| end. | |||
| mode_valid(Mode) -> | |||
| case Mode of | |||
| off -> true; | |||
| cool -> true; | |||
| energy_saver -> true; | |||
| fan_only -> true; | |||
| _ -> false | |||
| end. | |||
| set_fan(Fan) -> | |||
| gen_server:call(?MODULE, {set_fan, Fan}). | |||
| set_safe() -> | |||
| util:beep(1000, 200), | |||
| timer:sleep(200), | |||
| util:beep(1000, 200), | |||
| gen_server:cast(?MODULE, set_safe). | |||
| cutoff_check(Temp, TSet, Span) -> | |||
| %determine cutoff temperature based on thermostat and span size. | |||
| %If span size is small (<3), split it evenly. If large, bias it | |||
| %towards cooling further under the thermostat setpoint before cutting | |||
| %off compressor. | |||
| HalfSpan = Span/2, | |||
| SmallPartOfSpan = Span * 0.25, | |||
| LargePartOfSpan = Span * 0.75, | |||
| HighPoint = case (Span < 3) of | |||
| true -> TSet + HalfSpan; | |||
| _ -> TSet + SmallPartOfSpan | |||
| end, | |||
| LowPoint = case (Span < 3) of | |||
| true -> TSet - HalfSpan; | |||
| _ -> TSet - LargePartOfSpan | |||
| end, | |||
| debugger:format("[~p:~p] Cutoff Temps: [highpoint: ~.2f lowpoint: ~.2f]~n", [?MODULE, ?FUNCTION_NAME, HighPoint, LowPoint]), | |||
| {Temp >= HighPoint, Temp =< LowPoint}. | |||
| %load() -> | |||
| % gen_server:call(?MODULE, {load}). | |||
| % | |||
| %save() -> | |||
| % gen_server:call(?MODULE, {save}). | |||
| all_off() -> | |||
| compressor_set(off), | |||
| fan(0). | |||
| compressor_set(C) -> | |||
| debugger:format("[~p] ~p: TURNING ~p COMPRESSOR.~n", [?MODULE, ?FUNCTION_NAME, C]), | |||
| compressor_set_outputs(C). | |||
| compressor_set_outputs(C) -> | |||
| util:set_output(?COMPRESSOR, C), | |||
| util:set_output(?COMPRESSOR_LED, C), | |||
| C. | |||
| cycle_mode() -> | |||
| gen_server:cast(?MODULE, cycle_mode). | |||
| cycle_fan() -> | |||
| gen_server:cast(?MODULE, cycle_fan). | |||
| fan_on(F) -> | |||
| case F of | |||
| 0 -> fan(3); | |||
| _ -> fan(F) | |||
| end. | |||
| fan(F) -> | |||
| debugger:format("Setting fan to ~p.~n", [F]), | |||
| case util:make_int(F) of | |||
| 0 -> | |||
| util:set_output(?FAN1, off), | |||
| util:set_output(?FAN2, off), | |||
| util:set_output(?FAN3, off), | |||
| 0; | |||
| 1 -> | |||
| util:set_output(?FAN2, off), %turn off the ones that may be on before turning on the one required | |||
| util:set_output(?FAN3, off), | |||
| util:set_output(?FAN1, on), | |||
| 1; | |||
| 2 -> | |||
| util:set_output(?FAN1, off), | |||
| util:set_output(?FAN3, off), | |||
| util:set_output(?FAN2, on), | |||
| 2; | |||
| 3 -> | |||
| util:set_output(?FAN1, off), | |||
| util:set_output(?FAN2, off), | |||
| util:set_output(?FAN3, on), | |||
| 3; | |||
| _ -> 0 | |||
| end. | |||
| notify(Topic, Msg) -> | |||
| case whereis(mqtt_client) of | |||
| undefined -> io:format("MQTT is not alive; message: ~p~n", [Msg]); | |||
| %_Pid -> spawn( fun() -> mqtt:pub(Topic, Msg) end) % this notify/2 is called from handle_call/handle_info, so need to return quickly. | |||
| _Pid -> mqtt:publish_and_forget(Topic, Msg) % this notify/2 is called from handle_call/handle_info, so need to return quickly. | |||
| end. | |||
| status_binary(State) -> | |||
| status_binary(State, "ok"). | |||
| status_binary([{mode, Mode}, {fan, Fan}, {compressor, Comp}, {compressor_safe, CS}], StatusMsg) -> | |||
| [{temp, TStat}, {span, Span}] = thermostat:get_thermostat(), | |||
| [{temp, _}, {coiltemp, CoilTemp}, {templocal, TempLocal}, {tempremote, TempRemote}, {tempsrc, TempSrc}] = temperature:get_temperature(), | |||
| {{Year, Month, Day}, {Hour, Minute, Second}} = erlang:universaltime(), | |||
| BMode = util:convert_to_binary(Mode), | |||
| BFan = util:convert_to_binary(Fan), | |||
| BComp = util:convert_to_binary(Comp), | |||
| BTempLocal = util:convert_to_binary(TempLocal), | |||
| BTempRemote = util:convert_to_binary(TempRemote), | |||
| BTempSrc = util:convert_to_binary(TempSrc), | |||
| BCoilTemp = util:convert_to_binary(CoilTemp), | |||
| BTStat = util:convert_to_binary(TStat), | |||
| BSpan = util:convert_to_binary(Span), | |||
| BCS = util:convert_to_binary(CS), | |||
| BTime = util:convert_to_binary(io_lib:format("~p~2..0p~2..0p ~2..0p:~2..0p:~2..0p", [ Year, Month, Day, Hour, Minute, Second ])), | |||
| BStatusMsg = util:convert_to_binary(StatusMsg), | |||
| <<"{" | |||
| ,"\"mode\":\"", BMode/binary, "\"," | |||
| ,"\"fan\":", BFan/binary, "," | |||
| ,"\"compressor\":\"", BComp/binary, "\"," | |||
| ,"\"temp_local\":", BTempLocal/binary, "," | |||
| ,"\"temp_remote\":", BTempRemote/binary, "," | |||
| ,"\"thermostat\":", BTStat/binary, "," | |||
| ,"\"tempsource\":\"", BTempSrc/binary, "\"," | |||
| ,"\"span\":", BSpan/binary, "," | |||
| ,"\"coil\":", BCoilTemp/binary, "," | |||
| ,"\"comp_safe\":\"", BCS/binary, "\"," | |||
| ,"\"time\":\"", BTime/binary, "\"," | |||
| ,"\"status\":\"", BStatusMsg/binary, "\"" | |||
| ,"}">>. | |||
| %status_string([{mode, Mode}, {fan, Fan}, {compressor, Comp}, {compressor_safe, CS}]) -> | |||
| % {Temp, TempRemote, TempSrc, CoilTemp} = temperature:get_temperature(), | |||
| % [{temp, TStat}, {span, Span}] = thermostat:get_thermostat(), | |||
| % "{" | |||
| % ++ "\"mode\":\"" ++ atom_to_list(Mode) ++ "\"," | |||
| % ++ "\"fan\":" ++ integer_to_list(Fan) ++ "," | |||
| % ++ "\"compressor\":\"" ++ atom_to_list(Comp) ++ "\"," | |||
| % ++ "\"temp_local\":" ++ float_to_list(Temp, [{decimals, 2}]) ++ "," | |||
| % ++ "\"temp_remote\":" ++ float_to_list(TempRemote, [{decimals, 2}]) ++ "," | |||
| % ++ "\"thermostat\":" ++ integer_to_list(TStat) ++ "," | |||
| % ++ "\"tempsource\":\"" ++ binary_to_list(TempSrc) ++ "\"," | |||
| % ++ "\"span\":" ++ float_to_list(Span, [{decimals, 2}]) ++ "," | |||
| % ++ "\"coil\":" ++ float_to_list(CoilTemp, [{decimals, 2}]) ++ "," | |||
| % ++ "\"comp_safe\":\"" ++ atom_to_list(CS) ++ "\"" | |||
| % ++ "}". | |||
| @ -0,0 +1,111 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(debugger). | |||
| -behavior(gen_server). | |||
| -export([log/1, format/1, format/2, enable/0, disable/0, mqtt_only/0, console_only/0, set_boot_time/0, uptime/0]). | |||
| -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). | |||
| start_link() -> | |||
| io:format("Starting ~p with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, ?DEBUG_ENABLED_BY_DEFAULT, []). | |||
| init(DebugStatus) -> | |||
| io:format("~p:~p/~p called with arg: '~p'.~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, DebugStatus]), | |||
| %erlang:send(self(), uptime), | |||
| %erlang:send_after(60000, self(), time), | |||
| {ok, {DebugStatus, erlang:universaltime()}}. %set state of default debug status and bootup time | |||
| handle_call(enable, _From, _State={_, BootTime}) -> | |||
| {reply, ok, {true, BootTime}}; | |||
| handle_call(disable, _From, _State={_, BootTime}) -> | |||
| {reply, ok, {false, BootTime}}; | |||
| handle_call(console_only, _From, _State={_, BootTime}) -> | |||
| {reply, ok, {console_only, BootTime}}; | |||
| handle_call(mqtt_only, _From, _State={_, BootTime}) -> | |||
| {reply, ok, {mqtt_only, BootTime}}; | |||
| handle_call({set_boot_time, NewBootTime}, _From, {DebugType, _}) -> | |||
| {reply, ok, {DebugType, NewBootTime}}; | |||
| handle_call(boot_time, _From, State={_, BootTime}) -> | |||
| {reply, BootTime, State}; | |||
| handle_call(Call, _From, State) -> | |||
| erlang:display(Call), | |||
| {reply, ok, State}. | |||
| handle_cast(Msg, State={DebugType, _}) -> | |||
| select_output(DebugType, Msg), | |||
| {noreply, State}. | |||
| %handle_info(time, State) -> | |||
| % {{Year, Month, Day}, {Hour, Minute, Second}} = erlang:universaltime(), | |||
| % debugger:format("[DEBUG] Time: ~p/~2..0p/~2..0p ~2..0p:~2..0p:~2..0p ~n", [ Year, Month, Day, Hour, Minute, Second ]), | |||
| % erlang:send_after(60000, self(), time), | |||
| % {noreply, State}; | |||
| handle_info(uptime, State) -> | |||
| {_, {{Year, Month, Day}, {Hour, Minute, Second}}} = State, | |||
| debugger:format("BOOT TIME: ~p/~2..0p/~2..0p ~2..0p:~2..0p:~2..0p ~n", [ Year, Month, Day, Hour, Minute, Second ]), | |||
| debugger:format("UPTIME: ~p minutes ~n", [trunc(erlang:monotonic_time(second)/60)]), | |||
| %erlang:send_after(900000, self(), uptime), %repeat every 15 minutes | |||
| {noreply, State}; | |||
| handle_info(Msg, State) -> | |||
| select_output(State, Msg), | |||
| {noreply, State}. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| select_output(Mode, Msg) -> | |||
| case Mode of | |||
| console_only -> | |||
| %io:format("[DEBUG]: ~p~n", [Msg]); | |||
| io:format(Msg); | |||
| mqtt_only -> | |||
| notify(?TOPIC_DEBUG, Msg); | |||
| true -> | |||
| %io:format("[DEBUG]: ~p~n", [Msg]), | |||
| io:format(Msg), | |||
| notify(?TOPIC_DEBUG, Msg); | |||
| false -> ok | |||
| end. | |||
| notify(Topic, Msg) -> | |||
| case whereis(mqtt_client) of | |||
| undefined -> io:format("[DEBUG MQTT dead] MSG:~p", [Msg]); | |||
| _Pid -> mqtt:publish_and_forget(Topic, Msg) % this notify/2 is called from handle_call/handle_info, so need to return quickly. | |||
| end. | |||
| enable() -> | |||
| gen_server:call(?MODULE, enable). | |||
| disable() -> | |||
| gen_server:call(?MODULE, disable). | |||
| mqtt_only() -> | |||
| gen_server:call(?MODULE, mqtt_only). | |||
| console_only() -> | |||
| gen_server:call(?MODULE, console_only). | |||
| log(Msg) -> | |||
| gen_server:cast(?MODULE, Msg). | |||
| format(Msg) -> | |||
| log(Msg). | |||
| format(FmtMsg, FmtArgs) -> | |||
| Msg = io_lib:format(FmtMsg, FmtArgs), | |||
| gen_server:cast(?MODULE, Msg). | |||
| uptime() -> | |||
| erlang:send(?MODULE, uptime). | |||
| set_boot_time() -> | |||
| gen_server:call(?MODULE, {set_boot_time, erlang:universaltime()}). %set state of default debug status and bootup time | |||
| @ -0,0 +1,83 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(led). | |||
| -export([flash/0, flash/1, flash/2, flash/3]). | |||
| %-export([init/1, handle_call/3, handle_info/2, terminate/2]). | |||
| -export([start_link/0, init/1, handle_call/3, terminate/2]). | |||
| start_link() -> | |||
| io:format("Starting '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |||
| %timer:sleep(1). | |||
| init(_) -> | |||
| io:format("[~p:~p] Starting...~n", [?MODULE, ?FUNCTION_NAME]), | |||
| flash_led(?STATUS_LED, 50, 20), | |||
| util:set_output(?STATUS_LED, on), | |||
| {ok, []}. | |||
| handle_call(init, _From, State) -> | |||
| {reply, ok, State}; | |||
| handle_call({flash, Pin, Interval, Times}, _From, State) -> | |||
| Pid = spawn(fun() -> flash_led(Pin, Interval, Times) end), | |||
| %{reply, ok, [Pid|State]}; | |||
| {reply, ok, State}; | |||
| handle_call(listproc, _From, State) -> | |||
| io:format("Processes: ~p ~n", [State]), | |||
| {reply, ok, State}; | |||
| handle_call(reset, _From, State) -> | |||
| io:format("Processes: ~p ~n", [State]), | |||
| kill_flashers(State), | |||
| {reply, ok, []}; | |||
| handle_call(Call, _From, State) -> | |||
| erlang:display(Call), | |||
| {reply, ok, State}. | |||
| %handle_info({gpio_interrupt, 26}, SPI) -> | |||
| % handle_irq(SPI), | |||
| % {noreply, SPI}. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| kill_flashers(PidList) -> | |||
| case PidList of | |||
| [Pid|Remainder] -> exit(Pid, kill), | |||
| kill_flashers(Remainder); | |||
| [] -> ok; | |||
| _ -> ok | |||
| end. | |||
| flash() -> | |||
| flash(?STATUS_LED, 1000, forever). | |||
| flash(Pin) -> | |||
| gen_server:call(?MODULE, {flash, Pin, 1000, forever}). | |||
| flash(Pin, Interval) -> | |||
| io:format("Flashing Pin ~p FOREVER with interval ~p ms.~n", [Pin, Interval]), | |||
| gen_server:call(?MODULE, {flash, Pin, Interval, forever}). | |||
| flash(Pin, Interval, Times) -> | |||
| io:format("Flashing Pin ~p ~p times with interval ~p ms.~n", [Pin, Times, Interval]), | |||
| gen_server:call(?MODULE, {flash, Pin, Interval, Times}). | |||
| flash_led(_Pin, _Interval, 0) -> | |||
| ok; | |||
| flash_led(Pin, Interval, forever) -> | |||
| flash_led(Pin, Interval, 1), | |||
| flash_led(Pin, Interval, forever); | |||
| flash_led(Pin, Interval, Times) -> | |||
| util:set_output(Pin, on), | |||
| timer:sleep(Interval), | |||
| util:set_output(Pin, off), | |||
| timer:sleep(Interval), | |||
| flash_led(Pin, Interval, Times-1). | |||
| @ -0,0 +1,377 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -module(mqtt). | |||
| -behavior(gen_server). | |||
| %-export([start/0]). | |||
| -export([start_link/0, init/1, handle_call/3, handle_cast/2, terminate/2]). | |||
| -export([publish/2, publish/3, publish_and_forget/2, subscribe_remote_temp/1, unsubscribe/1]). | |||
| -include("app.hrl"). | |||
| start_link() -> | |||
| io:format("Starting '~p' with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |||
| %{ok, _Pid} = init([]). | |||
| init(_) -> | |||
| io:format("Starting '~p' with ~p/~p...~n", [mqtt_client, start_link, 1]), | |||
| %{ok, {no_mqtt_pid, not_ready}}. | |||
| My_Pid = self(), | |||
| {ok, {My_Pid, not_ready}}. | |||
| %{ok, MQTT_PID}. | |||
| start_mqtt_client() -> | |||
| Config = maps:get(mqtt, config:get()), | |||
| MQTTConfig = #{ | |||
| url => maps:get(url, Config), | |||
| client_id => ?DEVICENAME, | |||
| disconnected_handler => fun(_MQTT_CLIENT_PID) -> io:format("yoyo disconnected from mqtt!!!!!!~n"), mqtt_client:reconnect(whereis(mqtt_client)) end, | |||
| error_handler => fun(_MQTT_CLIENT_PID, Err) -> io:format("dah mqtt error_handler: ~p~n", [Err]) end, | |||
| connected_handler => fun handle_connected/1 | |||
| }, | |||
| io:format("Starting 'mqtt_client'...~n"), | |||
| {ok, _MQTT_PID} = mqtt_client:start_link({local, mqtt_client}, MQTTConfig). | |||
| handle_call(start_client, _From, {_, _ReadyStatus}) -> | |||
| io:format("MQTT Controller received 'start_client' message from 'wifi' after obtaining IP address; starting 'mqtt_client'...~n"), | |||
| {ok, MQTT_PID} = start_mqtt_client(), | |||
| {reply, ok, {MQTT_PID, not_ready}}; | |||
| handle_call({ready, MQTT_PID}, _From, {_, _ReadyStatus}) -> | |||
| {reply, ok, {MQTT_PID, ready}}; | |||
| handle_call({not_ready, MQTT_PID}, _From, {_, _ReadyStatus}) -> | |||
| {reply, ok, {MQTT_PID, not_ready}}; | |||
| handle_call({publish, Topic, Message}, _From, State) -> | |||
| Reply = gen_server:call(?MODULE, {publish, Topic, default_qos, Message}), | |||
| {reply, Reply, State}; | |||
| handle_call({publish, Topic, QoS, Message}, _From, State={_MQTT_PID, ReadyStatus}) -> | |||
| case ReadyStatus of | |||
| ready -> | |||
| publish_message(Topic, QoS, Message), | |||
| {reply, ok, State}; | |||
| _ -> {reply, mqtt_not_ready, State} | |||
| end; | |||
| handle_call(get_pid, _From, State={MQTT_PID, _ReadyStatus}) -> | |||
| {reply, MQTT_PID, State}; | |||
| handle_call(get, _From, State={_MQTT_PID, _ReadyStatus}) -> | |||
| {reply, State, State}; | |||
| handle_call(Msg, From, State) -> | |||
| io:format("MQTT Controller received unknown message ~p from ~p~n", [Msg, From]), | |||
| {reply, ok, State}. | |||
| handle_cast({publish, Topic, Message}, State={_MQTT_PID, ReadyStatus}) -> %Fire-and-forget publish with no response | |||
| case ReadyStatus of | |||
| ready -> spawn(publish_and_forget(Topic, Message) ); | |||
| _ -> ReadyStatus | |||
| end, | |||
| {noreply, State}; | |||
| handle_cast(_Msg, State) -> | |||
| {noreply, State}. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| ac_on() -> | |||
| io:format("Turning on AC.~n", []), | |||
| util:set_output(?FAN3, on), | |||
| util:set_output(?COMPRESSOR, on), | |||
| util:set_output(?STATUS_LED, on), | |||
| publish_message(?TOPIC_AC, <<"AC ON">>). | |||
| compressor_off() -> | |||
| io:format("Turning off compressor.~n", []), | |||
| util:set_output(?COMPRESSOR, off), | |||
| publish_message(?TOPIC_AC, <<"COMPRESSOR OFF">>). | |||
| compressor_on() -> | |||
| io:format("FORCE Turning ON compressor.~n", []), | |||
| util:set_output(?COMPRESSOR, on), | |||
| publish_message(?TOPIC_AC, <<"COMPRESSOR OFF">>). | |||
| all_off() -> | |||
| io:format("Turning off compressor.~n", []), | |||
| util:set_output(?FAN3, off), | |||
| util:set_output(?FAN2, off), | |||
| util:set_output(?FAN1, off), | |||
| util:set_output(?COMPRESSOR, off), | |||
| publish_message(?TOPIC_AC, <<"ALL OFF">>). | |||
| publish(Topic, Message) -> | |||
| publish(Topic, default_qos, Message). | |||
| publish(Topic, QoS, Message) -> | |||
| publish_message(Topic, QoS, Message). | |||
| %gen_server:call(?MODULE, {publish, Topic, QoS, Message}). | |||
| publish_and_forget(Topic, Message) -> | |||
| publish_message(Topic, at_most_once, Message). | |||
| %gen_server:cast(?MODULE, {publish, Topic, at_most_once, Message}). | |||
| handle_connected(MQTT) -> | |||
| Config = mqtt_client:get_config(MQTT), | |||
| debugger:format("[~p:~p] MQTT started and connected to ~p~n", [?MODULE, ?FUNCTION_NAME, maps:get(url, Config)]), | |||
| gen_server:call(mqtt, {ready, MQTT}), | |||
| subscribe_to_topic_list(MQTT, get_topics()). | |||
| subscribe_to_topic(MQTT, Topic, SubHandleFunc, DataHandleFunc) -> | |||
| debugger:format("Subscribing to ~p...~n", [Topic]), | |||
| case mqtt_client:subscribe(MQTT, util:convert_to_binary(Topic), #{ | |||
| %subscribed_handler => fun handle_subscribed/2, | |||
| %data_handler => fun handle_data/3 | |||
| subscribed_handler => SubHandleFunc, | |||
| data_handler => DataHandleFunc | |||
| }) of | |||
| ok -> ok; | |||
| _ -> io:format("MQTT Subscribe Failed! KILLING MQTT CLIENT ~p. My PID: ~p~n", [MQTT, self()]), | |||
| exit(MQTT) | |||
| end. | |||
| subscribe_to_topic_list(MQTT, Topics) -> | |||
| case Topics of | |||
| [{Topic, SubHandleFunc, DataHandleFunc}|Remaining] -> | |||
| subscribe_to_topic(MQTT, Topic, SubHandleFunc, DataHandleFunc), | |||
| subscribe_to_topic_list(MQTT, Remaining); | |||
| _ -> debugger:format("Done subscribing to MQTT topics.~n") | |||
| end. | |||
| get_topics() -> | |||
| [ | |||
| {?TOPIC_AC, fun handle_subscribed/2, fun handle_data/3} | |||
| ,{?TOPIC_THERMOSTAT, fun handle_subscribed_thermostat/2, fun handle_data_thermostat/3} | |||
| ,{?TOPIC_OUT1, fun handle_subscribed/2, fun handle_data_output/3} | |||
| ,{?TOPIC_FAN, fun handle_subscribed/2, fun handle_data_fan/3} | |||
| ]. | |||
| handle_subscribed(_MQTT, Topic) -> | |||
| debugger:format("Subscribed to topic: ~p.~n", [Topic]). | |||
| unsubscribe(Topic) -> | |||
| {MQTT_PID, _ReadyStatus} = gen_server:call(?MODULE, get), | |||
| UnsubHandlerFunc = fun(_MQTT, UnsubTopic) -> debugger:format("Unsubscribed from topic feed: ~p ~n", [UnsubTopic]) end, | |||
| debugger:format("[mqtt:unsubscribe] Running mqtt:unsubscribe in mqtt.erl to mqtt_client ~p on topic: ~p~n",[MQTT_PID, Topic]), | |||
| mqtt_client:unsubscribe(MQTT_PID, util:convert_to_binary(Topic), #{unsubscribed_handler => UnsubHandlerFunc}). | |||
| subscribe_remote_temp(Topic) -> | |||
| {MQTT_PID, ReadyStatus} = gen_server:call(?MODULE, get), | |||
| case ReadyStatus of | |||
| ready -> subscribe_to_topic(MQTT_PID, Topic, fun handle_subscribed/2, fun handle_data_remote_temp/3); | |||
| _ -> ReadyStatus | |||
| end. | |||
| handle_data_remote_temp(_MQTT, Topic, Data) -> | |||
| debugger:format("[~p:~p/~p] remote temperature [~p] received from ~p~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, Data, Topic]), | |||
| temperature:set_remote_temperature(Data). | |||
| handle_subscribed_thermostat(_MQTT, Topic) -> | |||
| debugger:format("Subscribed to topic: ~p.~n", [Topic]), %, | |||
| debugger:format("Spawning thermostat setpoint publish loop on topic ~p~n", [?TOPIC_THERMOSTAT_SET]), | |||
| spawn(fun() -> publish_thermostat_loop(?THERMOSTAT_PUB_INTERVAL_SEC * 1000) end). | |||
| handle_data(_MQTT, Topic, Data) -> | |||
| debugger:format("[~p:~p/~p] received data on topic ~p: ~p ~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, Topic, Data]), | |||
| case Data of | |||
| <<"flash">> -> spawn(fun() -> led:flash(?STATUS_LED, 100, 20) end); | |||
| <<"flash2">> -> spawn(fun() -> led:flash(?STATUS_LED2, 300, 10) end); | |||
| <<"flash 10">> -> spawn(fun() -> led:flash(?STATUS_LED, 200, 10) end); | |||
| <<"flash forever">> -> spawn(fun() -> led:flash(?STATUS_LED, 200, forever) end); | |||
| <<"listproc">> -> gen_server:call(led, listproc); | |||
| <<"reset_led">> -> gen_server:call(led, reset); | |||
| <<"beep">> -> spawn(fun() -> util:beep(440, 1000) end); | |||
| <<"beep ", F/binary>> -> spawn(fun() -> util:beep(util:make_int(F), 1000) end); | |||
| %%% | |||
| <<"ac_on">> -> ac_on(); | |||
| <<"all_off">> -> all_off(); | |||
| <<"compressor_off">> -> compressor_off(); | |||
| <<"force_compressor_on">> -> compressor_on(); | |||
| %<<"coiltemp ", T/binary>> -> control:set_coil_templimit(util:make_int(T)); | |||
| %%% | |||
| <<"sysinfo">> -> system_info:start(); | |||
| <<"uptime">> -> publish_message(?TOPIC_DEBUG, util:uptime()); | |||
| <<"debug">> -> debugger:enable(); %crashes after a few minutes | |||
| <<"nodebug">> -> debugger:disable(); | |||
| <<"debug_mqtt_only">> -> debugger:mqtt_only(); | |||
| <<"debug_console_only">> -> debugger:console_only(); | |||
| %%% | |||
| <<"off">> -> control:set_mode(off); | |||
| <<"on">> -> control:set_mode(cool); | |||
| <<"cool">> -> control:set_mode(cool); | |||
| <<"fan_only">> -> control:set_mode(fan_only); | |||
| <<"energy_saver">> -> control:set_mode(energy_saver); | |||
| <<"mode_cycle">> -> control:cycle_mode(); | |||
| <<"fan_cycle">> -> control:cycle_fan(); | |||
| <<"fan ", F/binary>> -> control:set_fan(util:make_int(F)); | |||
| <<"temp_source ", TempSrc/binary>> -> temperature:set_source(TempSrc); | |||
| <<"safe">> -> control:set_safe(); | |||
| <<"reset">> -> all_off(), esp:restart(); | |||
| <<"reboot">> -> all_off(), esp:restart(); | |||
| %%% Timer | |||
| <<"timer_h off ", T/binary>> -> mode_timer(off, T*3600); %hours timer | |||
| <<"timer_m off ", T/binary>> -> mode_timer(off, T*60); %minutes timer | |||
| <<"timer_s off ", T/binary>> -> mode_timer(off, T); %seconds timer | |||
| <<"timer off ", T/binary>> -> mode_timer(off, T); %default seconds timer | |||
| <<"timer_h cool ", T/binary>> -> mode_timer(cool, T*3600); %hours timer | |||
| <<"timer_m cool ", T/binary>> -> mode_timer(cool, T*60); %minutes timer | |||
| <<"timer_s cool ", T/binary>> -> mode_timer(cool, T); %seconds timer | |||
| <<"timer cool ", T/binary>> -> mode_timer(cool, T); %default seconds timer | |||
| <<"timer_h on ", T/binary>> -> mode_timer(cool, T*3600); %hours timer | |||
| <<"timer_m on ", T/binary>> -> mode_timer(cool, T*60); %minutes timer | |||
| <<"timer_s on ", T/binary>> -> mode_timer(cool, T); %seconds timer | |||
| <<"timer on ", T/binary>> -> mode_timer(cool, T); %default seconds timer | |||
| <<"timer_h energy_saver ", T/binary>> -> mode_timer(cool, T*3600); %hours timer | |||
| <<"timer_m energy_saver ", T/binary>> -> mode_timer(cool, T*60); %minutes timer | |||
| <<"timer_s energy_saver ", T/binary>> -> mode_timer(cool, T); %seconds timer | |||
| <<"timer energy_saver ", T/binary>> -> mode_timer(cool, T); %default seconds timer | |||
| <<"timer_h fan_only ", T/binary>> -> mode_timer(fan_only, T*3600); %hours timer | |||
| <<"timer_m fan_only ", T/binary>> -> mode_timer(fan_only, T*60); %minutes timer | |||
| <<"timer_s fan_only ", T/binary>> -> mode_timer(fan_only, T); %seconds timer | |||
| <<"timer fan_only ", T/binary>> -> mode_timer(fan_only, T); %default seconds timer | |||
| % <<"timer_h ", Mode/binary, " ", T/binary>> -> %hours timer | |||
| % TimeMs = util:make_int(T) * 3600 * 1000, | |||
| % erlang:send_after(TimeMs, control, {set_mode, Mode}); | |||
| % <<"timer_m ", Mode/binary, " ", T/binary>> -> %minutes timer | |||
| % TimeMs = util:make_int(T) * 60 * 1000, | |||
| % erlang:send_after(TimeMs, control, {set_mode, Mode}); | |||
| % <<"timer_s ", Mode/binary, " ", T/binary>> -> %seconds timer | |||
| % TimeMs = util:make_int(T) * 1000, | |||
| % erlang:send_after(TimeMs, control, {set_mode, Mode}); | |||
| % <<"timer ", Mode/binary, " ", T/binary>> -> %default seconds timer | |||
| % TimeMs = util:make_int(T) * 1000, | |||
| % erlang:send_after(TimeMs, control, {set_mode, Mode}); | |||
| %TimeMs = case binary:last(T) of | |||
| % 104 -> %h | |||
| % 72 -> %H | |||
| % 109 -> %m | |||
| % 77 -> %M | |||
| % 115 -> %s | |||
| % 83 -> %S | |||
| %end, | |||
| %%% | |||
| _ -> util:set_output(?STATUS_LED, Data) | |||
| end. | |||
| handle_data_thermostat(_MQTT, Topic, Data) -> | |||
| debugger:format("[~p:~p/~p] received data on topic ~p: ~p ~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, Topic, Data]), | |||
| case Data of | |||
| <<"+">> -> thermostat:up(); | |||
| <<"up">> -> thermostat:up(); | |||
| <<"-">> -> thermostat:down(); | |||
| <<"down">> -> thermostat:down(); | |||
| <<"show">> -> | |||
| Res = thermostat:get_thermostat(), | |||
| io:format("Thermostat: ~p~n", [Res]), | |||
| publish_message(?TOPIC_THERMOSTAT_SET, Res); | |||
| <<"span ", S/binary>> -> thermostat:set_span(S); | |||
| <<"save">> -> thermostat:save(); | |||
| <<"load">> -> thermostat:load(); | |||
| <<"default">> -> thermostat:default(); | |||
| %%% Timer | |||
| <<"timer_h ", Temp:2/binary, " ", T/binary>> -> thermostat_timer(Temp, util:make_int(T) * 3600); %hours timer | |||
| <<"timer_m ", Temp:2/binary, " ", T/binary>> -> thermostat_timer(Temp, util:make_int(T) * 60); %minutes timer | |||
| <<"timer_s ", Temp:2/binary, " ", T/binary>> -> thermostat_timer(Temp, util:make_int(T)); %seconds timer | |||
| <<"timer ", Temp:2/binary, " ", T/binary>> -> thermostat_timer(Temp, util:make_int(T)); %seconds timer | |||
| %%% | |||
| _ -> thermostat:set_temp(Data), | |||
| publish_message(?TOPIC_THERMOSTAT_SET, Data) | |||
| end. | |||
| mode_timer(Mode, TimeSec) -> | |||
| T = util:make_int(TimeSec), | |||
| spawn(fun() -> | |||
| debugger:format("Setting mode to ~p via timer for ~p seconds from now...~n", [Mode, T]), | |||
| erlang:send_after(T * 1000, control, {set_mode, Mode}), | |||
| debugger:format("Changing mode to ~p via timer after ~p seconds!~n", [Mode, T]) | |||
| end). | |||
| thermostat_timer(Temp, TimeSec) -> | |||
| T = util:make_int(TimeSec), | |||
| spawn(fun() -> | |||
| debugger:format("Setting thermostat ~p timer for ~p seconds from now...~n", [Temp, T]), | |||
| erlang:send_after(T * 1000, thermostat, {set_temp, util:make_int(Temp)}), | |||
| debugger:format("Set thermostat to ~p with timer after ~p seconds!~n", [Temp, T]) | |||
| end). | |||
| handle_data_fan(_MQTT, Topic, Data) -> | |||
| debugger:format("[~p:~p/~p] received data on topic ~p: ~p ~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, Topic, Data]), | |||
| case Data of | |||
| <<"cycle">> -> control:cycle_fan(); | |||
| <<"1">> -> control:set_fan(1); | |||
| <<"2">> -> control:set_fan(2); | |||
| <<"3">> -> control:set_fan(3); | |||
| F -> control:set_fan(util:make_int(F)) | |||
| end. | |||
| %handle_data_output(_MQTT, Topic = <<"barf/out", X/binary>>, Data) -> | |||
| handle_data_output(_MQTT, Topic, Data) -> | |||
| debugger:format("~p/~p received data on topic ~p: ~p ~n", [?FUNCTION_NAME, ?FUNCTION_ARITY, Topic, Data]), | |||
| %binary:last gives the last byte of a binary as an integer (ASCII value in this case). Subtract 48 to get the output number. :) | |||
| Output = binary:last(Topic)-48, | |||
| Pin = lists:nth(Output, ?GENERIC_OUTPUTS), %select the output pin from the ?GENERIC_OUTPUTS define list. | |||
| SetOutFunc = case ?GENERIC_OUTPUT_ACTIVE_LOW of | |||
| true -> fun util:set_output_activelow/2; | |||
| _ -> fun util:set_output/2 | |||
| end, | |||
| SetOutFunc(Pin, Data). | |||
| publish_thermostat_loop(Interval) -> | |||
| [{temp, Therm}|_] = thermostat:get_thermostat(), | |||
| publish_and_forget(?TOPIC_THERMOSTAT_SET, Therm), | |||
| timer:sleep(Interval), | |||
| publish_thermostat_loop(Interval). | |||
| publish_message(Topic, Data) -> | |||
| publish_message(Topic, default_qos, Data). | |||
| publish_message(Topic, QoS, Data) -> | |||
| publish_message(Topic, QoS, Data, 10000). | |||
| publish_message(Topic, QoS, Data, Timeout) -> | |||
| try | |||
| %io:format("Publishing data '~p' to topic ~p and mqtt_client pid ~p from my Pid ~p mqtt pid:~p ~n", [Data, Topic, whereis(mqtt_client), Self, whereis(mqtt)]), | |||
| io:format("MQTT Publishing '~p' to topic ~p~n", [Data, Topic]), | |||
| MQTT_CLIENT = whereis(mqtt_client), | |||
| Self = self(), | |||
| HandlePublished = fun(MQTT2, Topic2, MsgId) -> | |||
| %io:format("published_handler about to send pub message to PID: ~p mqtt pid ~p ~n", [Self, whereis(mqtt)]), | |||
| Self ! published, | |||
| handle_published(MQTT2, Topic2, MsgId) | |||
| end, | |||
| PublishOptions = #{qos => qos(QoS), published_handler => HandlePublished}, | |||
| Msg = util:convert_to_binary(Data), | |||
| _ = mqtt_client:publish(MQTT_CLIENT, util:convert_to_binary(Topic), Msg, PublishOptions), | |||
| case qos(QoS) of | |||
| at_most_once -> ok; %don't wait for confirmation message as it won't be sent! | |||
| _ -> | |||
| receive | |||
| published -> | |||
| ok; | |||
| MessageRX -> io:format("MQTT received something else besides 'published': ~p~n", [MessageRX]) | |||
| after Timeout -> | |||
| io:format("Timed out waiting for publish ack~n") | |||
| end | |||
| end | |||
| catch | |||
| C:E:S -> | |||
| io:format("Error in publish: ~p:~p~p~n", [C, E, S]) | |||
| end. | |||
| handle_published(MQTT, Topic, MsgId) -> | |||
| io:format("MQTT client ~p published message (with acknoledgement) to topic ~p msg_id=~p~n", [MQTT, Topic, MsgId]). | |||
| qos(QoS) -> %allow invalid QoS value to be accepted and set to 'at_least_once' | |||
| case QoS of | |||
| at_least_once -> at_least_once; | |||
| at_most_once -> at_most_once; | |||
| exactly_once -> exactly_once; | |||
| %_ -> at_least_once %this is the default | |||
| _ -> at_most_once %this is the default | |||
| end. | |||
| @ -0,0 +1,40 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -module(network_sup). | |||
| -behaviour(supervisor). | |||
| -export([start_link/0]). | |||
| -export([init/1]). | |||
| -define(SERVER, ?MODULE). | |||
| start_link() -> | |||
| supervisor:start_link({local, ?SERVER}, ?MODULE, []). | |||
| init([]) -> | |||
| io:format("Starting ~p supervisor with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| MaxRestarts = 3, % Kill everyone and die if more than MaxRestarts failures per MaxSecBetweenRestarts seconds | |||
| MaxSecBetweenRestarts = 10, | |||
| WiFi = worker(wifi, start_link, []), | |||
| MQTT_Controller = worker(mqtt, start_link, []), | |||
| %MQTTClient = worker(mqtt_client, start_link, []), | |||
| %HTTP = worker(httpsrv, start_link, []), | |||
| % rest_for_one restart strategy would be preferrable here but is not yet supported :) | |||
| %{ok, {{rest_for_one, MaxRestarts, MaxSecBetweenRestarts}, [ | |||
| {ok, {{one_for_one, MaxRestarts, MaxSecBetweenRestarts}, [ | |||
| MQTT_Controller %start before wifi! | |||
| ,WiFi | |||
| %,MQTTClient | |||
| %,HTTP | |||
| ] }}. | |||
| %Create a worker spec: | |||
| worker(Name, StartFunc, Args) -> | |||
| {Name, {Name, StartFunc, Args}, permanent, brutal_kill, worker, [Name]}. | |||
| @ -0,0 +1,95 @@ | |||
| % | |||
| % This file is part of AtomVM. | |||
| % | |||
| % Copyright 2022 Fred Dushin <fred@dushin.net> | |||
| % | |||
| % Licensed under the Apache License, Version 2.0 (the "License"); | |||
| % you may not use this file except in compliance with the License. | |||
| % You may obtain a copy of the License at | |||
| % | |||
| % http://www.apache.org/licenses/LICENSE-2.0 | |||
| % | |||
| % Unless required by applicable law or agreed to in writing, software | |||
| % distributed under the License is distributed on an "AS IS" BASIS, | |||
| % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |||
| % See the License for the specific language governing permissions and | |||
| % limitations under the License. | |||
| % | |||
| % SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later | |||
| % | |||
| -module(system_info). | |||
| -export([start/0]). | |||
| start() -> | |||
| SystemInfo = #{ | |||
| atom_count => erlang:system_info(atom_count), | |||
| process_count => erlang:system_info(process_count), | |||
| port_count => erlang:system_info(port_count), | |||
| word_size => erlang:system_info(wordsize), | |||
| system_architecture => erlang:system_info(system_architecture) | |||
| }, | |||
| io:format("SystemInfo:~n"), | |||
| io:format("===========~n"), | |||
| print_map(SystemInfo), | |||
| io:format("~n"), | |||
| PlatformInfo = | |||
| case atomvm:platform() of | |||
| esp32 -> | |||
| #{ | |||
| esp32_free_heap_size => erlang:system_info(esp32_free_heap_size), | |||
| esp32_largest_free_block => erlang:system_info(esp32_largest_free_block), | |||
| esp32_minimum_free_size => erlang:system_info(esp32_minimum_free_size), | |||
| esp32_chip_info => erlang:system_info(esp32_chip_info), | |||
| esp_idf_version => erlang:system_info(esp_idf_version) | |||
| }; | |||
| _ -> | |||
| #{} | |||
| end, | |||
| io:format("PlatformInfo:~n"), | |||
| io:format("=============~n"), | |||
| print_map(PlatformInfo), | |||
| io:format("~n"), | |||
| Processes = erlang:processes(), | |||
| ProcessInfo = [{Process, get_process_info(Process)} || Process <- Processes], | |||
| io:format("ProcessInfo:~n"), | |||
| io:format("============~n"), | |||
| print_process_info(ProcessInfo), | |||
| io:format("~n"), | |||
| ok. | |||
| get_process_info(Pid) -> | |||
| maps:from_list([ | |||
| erlang:process_info(Pid, heap_size), | |||
| erlang:process_info(Pid, stack_size), | |||
| erlang:process_info(Pid, message_queue_len), | |||
| erlang:process_info(Pid, memory) | |||
| ]). | |||
| print_process_info(ProcessInfo) -> | |||
| [ | |||
| begin | |||
| io:format("Pid: ~p~n", [Pid]), | |||
| print_map(Info) | |||
| end | |||
| || {Pid, Info} <- ProcessInfo | |||
| ]. | |||
| print_map(Map) -> | |||
| maps:fold( | |||
| fun(Key, Value, _) -> | |||
| print_entry(Key, Value) | |||
| end, | |||
| ok, | |||
| Map | |||
| ). | |||
| print_entry(Key, Value) when is_list(Value) -> | |||
| io:format("~p: ~s~n", [Key, Value]); | |||
| print_entry(Key, Value) -> | |||
| io:format("~p: ~p~n", [Key, Value]). | |||
| @ -0,0 +1,167 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(temperature). | |||
| -behavior(gen_server). | |||
| -export([get_temperature/0, set_remote_temperature/1, set_source/1]). | |||
| -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). | |||
| start_link() -> | |||
| debugger:format("Starting ~p with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). | |||
| init(_) -> | |||
| debugger:format("[~p:~p/~p] Reading initial temperatures from thermistors on ~p and ~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, ?THERMISTOR1, ?THERMISTOR2]), | |||
| {ok, ADC_T1_PID} = adc:start(?THERMISTOR1), | |||
| {ok, ADC_TCOIL_PID} = adc:start(?THERMISTOR2), | |||
| TempSource = format_source(esp:nvs_get_binary(?NVS_NAMESPACE, temp_source, <<"local">>)), | |||
| TempLocal = read_temp(ADC_T1_PID, thermistor1, 0.0), | |||
| TempCoil = read_temp(ADC_TCOIL_PID, coil_thermistor, 0.0), | |||
| erlang:send(self(), {subscribe_remote_temp, TempSource}), | |||
| erlang:send_after(5000, self(), {tempread_loop, ADC_T1_PID, ADC_TCOIL_PID}), | |||
| {ok, [{temp, TempLocal}, {coiltemp, TempCoil}, {templocal, TempLocal}, {tempremote, -1.0}, {tempsrc, TempSource}] }. | |||
| handle_info({subscribe_remote_temp, TempSource}, State) -> | |||
| case TempSource of | |||
| local -> ok; %do nothing for local | |||
| _ -> debugger:format("[~p:~p] subscribe_remote_temp attempting subscribe to remote source...~n", [?MODULE, ?FUNCTION_NAME]), | |||
| case whereis(mqtt) of | |||
| undefined -> | |||
| debugger:format("'mqtt' is not yet started, trying again later.~n"), | |||
| erlang:send_after(10000, self(), {subscribe_remote_temp, TempSource}); | |||
| _Pid -> case gen_server:call(mqtt, get) of | |||
| {_, ready} -> | |||
| mqtt:subscribe_remote_temp(TempSource); | |||
| _ -> | |||
| debugger:format("'mqtt' is running, but not ready, trying again later.~n"), | |||
| erlang:send_after(10000, self(), {subscribe_remote_temp, TempSource}) | |||
| end | |||
| end | |||
| end, | |||
| {noreply, State}; | |||
| handle_info({tempread_loop, ADC_T1, ADC_TCOIL}, [_, {coiltemp, TCoil}, {templocal, TLocal}, {tempremote, TRemote}, {tempsrc, TSrc}]) -> | |||
| T1 = read_temp(ADC_T1, thermistor1, TLocal), | |||
| Coil = read_temp(ADC_TCOIL, coil_thermistor, TCoil), | |||
| T = temp_select(T1, TRemote, TSrc), | |||
| %debugger:format("[~p:~p] tempread_loop [T=~.2f, TLocal=~.2f TCoil=~.2f, TRem=~p, TSrc=~p].~n", [?MODULE, ?FUNCTION_NAME, T, T1, Coil, TRemote, TSrc]), | |||
| debugger:format("[~p:~p] tempread_loop [T=~.2f, TLocal=~.2f TCoil=~.2f, TRem=~.2f, TSrc=~p].~n", [?MODULE, ?FUNCTION_NAME, T, T1, Coil, TRemote, TSrc]), | |||
| erlang:send_after(15000, self(), {tempread_loop, ADC_T1, ADC_TCOIL}), | |||
| {noreply, [{temp, T}, {coiltemp, Coil}, {templocal, T1}, {tempremote, TRemote}, {tempsrc, TSrc}] }. | |||
| %set remote temperature from external source | |||
| handle_call({set_remote, TRemoteInput}, _From, [{temp, _}, {coiltemp, Coil}, {templocal, TLocal}, {tempremote, _}, {tempsrc, TSrc}]) -> | |||
| TRemote = util:make_float(TRemoteInput), | |||
| T = temp_select(TLocal, TRemote, TSrc), | |||
| {reply, ok, [{temp, T}, {coiltemp, Coil}, {templocal, TLocal}, {tempremote, TRemote}, {tempsrc, TSrc}] }; | |||
| %set external source | |||
| handle_call({set_source, Src}, _From, [{temp, _T}, {coiltemp, Coil}, {templocal, TLocal}, {tempremote, TRemote}, {tempsrc, OldSrc}]) -> | |||
| Source = change_source(Src, OldSrc), | |||
| T = temp_select(TLocal, TRemote, Source), | |||
| {reply, ok, [{temp, T}, {coiltemp, Coil}, {templocal, TLocal}, {tempremote, TRemote}, {tempsrc, Source}] }; | |||
| handle_call(get, _From, State) -> | |||
| {reply, State, State}. | |||
| handle_cast(_Msg, State) -> | |||
| {noreply, State}. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| read_temp(ADC, Label, ErrDefaultVal) -> | |||
| case adc:read(ADC) of | |||
| {ok, {Raw, MilliVolts}} -> | |||
| debugger:format("[~p:~p] Read values from ADC ~p ~p: [Raw: ~p Voltage: ~pmV]~n", [?MODULE, ?FUNCTION_NAME, ADC, Label, Raw, MilliVolts]), | |||
| %MilliVolts/1000; | |||
| convert_reading_to_F(MilliVolts); | |||
| Error -> | |||
| debugger:format("[~p:~p] Error taking reading from ADC ~p ~p: ~p~n", [?MODULE, ?FUNCTION_NAME, ADC, Label, Error]), | |||
| ErrDefaultVal | |||
| end. | |||
| get_temperature() -> | |||
| gen_server:call(?MODULE, get). | |||
| set_remote_temperature(T) -> %set the remote temperature from MQTT or external source. | |||
| gen_server:call(?MODULE, {set_remote, T}). | |||
| % if | |||
| % is_float(T) -> gen_server:call(?MODULE, {set_remote, T}); | |||
| % is_integer(T) -> gen_server:call(?MODULE, {set_remote, float(T)}); %% FUNCTION float/1 DOESN'T WORK! | |||
| % true -> gen_server:call(?MODULE, {set_remote, -1.0}) | |||
| % end. | |||
| set_source(Src) -> | |||
| gen_server:call(?MODULE, {set_source, Src}). | |||
| change_source(NewSrc, OldSrc) -> | |||
| BNewSrc = util:convert_to_binary(NewSrc), | |||
| BOldSrc = util:convert_to_binary(OldSrc), | |||
| if | |||
| BNewSrc == BOldSrc -> %Don't write to NVS or subscribe/unsubscribe if source is unchanged. | |||
| debugger:format("[~p:~p] Temp source is unchanged, keeping old.~n", [?MODULE, ?FUNCTION_NAME]), | |||
| OldSrc; | |||
| true -> | |||
| Unsubscribed = case OldSrc of | |||
| local -> ok; | |||
| _ -> | |||
| debugger:format("[~p:~p] Unsubscribing from old source: ~p~n",[?MODULE, ?FUNCTION_NAME, OldSrc]), | |||
| mqtt:unsubscribe(OldSrc) | |||
| end, | |||
| case NewSrc of %new source is 'local' or a topic? | |||
| local -> save_source(local); | |||
| <<"local">> -> save_source(local); | |||
| _ -> case Unsubscribed of | |||
| ok -> | |||
| debugger:format("[~p:~p] We are unsubscribed from old source ~p. Subscribing to new: ~p~n",[?MODULE, ?FUNCTION_NAME, OldSrc, NewSrc]), | |||
| case mqtt:subscribe_remote_temp(NewSrc) of | |||
| ok -> save_source(NewSrc); %subscription was successful, so save only then | |||
| Error -> Error | |||
| end; | |||
| _ -> OldSrc %revert to old source since we are still subscribed to it! | |||
| end | |||
| end | |||
| end. | |||
| save_source(Src) -> | |||
| case Src of | |||
| local -> | |||
| esp:nvs_set_binary(?NVS_NAMESPACE, temp_source, <<"local">>), | |||
| local; | |||
| Topic -> | |||
| esp:nvs_set_binary(?NVS_NAMESPACE, temp_source, util:convert_to_binary(Topic)), | |||
| Topic | |||
| end. | |||
| format_source(<<SrcBinary/binary>>) -> | |||
| case SrcBinary of | |||
| <<"local">> -> local; | |||
| _ -> SrcBinary | |||
| end. | |||
| temp_select(TLocal, TRemote, TSrc) -> | |||
| case TSrc of | |||
| local -> TLocal; | |||
| _ -> if | |||
| TRemote > 0 -> TRemote; %if remote temp is 0 (or less), use local temp until a valid value is received. | |||
| true -> TLocal | |||
| end | |||
| end. | |||
| convert_reading_to_F(MilliVolts) -> | |||
| %MilliVolts/21.5. %cheapo estimation! | |||
| %MilliVolts/15.0. %cheapo estimation! | |||
| 0.038 * MilliVolts + 32.806. | |||
| @ -0,0 +1,96 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(thermostat). | |||
| -behavior(gen_server). | |||
| -export([up/0, down/0, get_thermostat/0, set_temp/1, set_span/1, load/0, save/0, default/0]). | |||
| -export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2]). | |||
| start_link() -> | |||
| debugger:format("Starting ~p with ~p/~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY]), | |||
| {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, [?THERMOSTAT_DEFAULT, ?THERMOSTAT_SPAN_DEFAULT], []). | |||
| init(Args = [DefTempBinInt, DefSpanBinFloat]) -> | |||
| debugger:format("~p:~p/~p called with args: ~p...~n", [?MODULE, ?FUNCTION_NAME, ?FUNCTION_ARITY, Args]), | |||
| StartTemp = esp:nvs_get_binary(?NVS_NAMESPACE, thermostat, DefTempBinInt), | |||
| SpanDegrees = esp:nvs_get_binary(?NVS_NAMESPACE, span, DefSpanBinFloat), | |||
| debugger:format("[~p:~p] Setting initial values. Temp: ~p Span: ~p~n", [?MODULE, ?FUNCTION_NAME, StartTemp, SpanDegrees]), | |||
| {ok, [{temp, binary_to_integer(StartTemp)}, {span, binary_to_float(SpanDegrees)}]}. | |||
| handle_info({set_temp, Temp}, State=[_T, Span]) -> | |||
| if | |||
| Temp >= ?MIN_THERMOSTAT andalso Temp =< ?MAX_THERMOSTAT -> | |||
| {noreply, [{temp, Temp}, Span]}; | |||
| true -> {noreply, State} | |||
| end. | |||
| handle_call({set_temp, Temp}, _From, State=[_T, Span]) -> | |||
| if | |||
| Temp >= ?MIN_THERMOSTAT andalso Temp =< ?MAX_THERMOSTAT -> | |||
| {reply, ok, [{temp, Temp}, Span]}; | |||
| true -> {reply, ok, State} | |||
| end; | |||
| handle_call({up}, _From, _State=[{temp, Temp}, Span]) -> | |||
| {reply, ok, [{temp, Temp+1}, Span]}; | |||
| handle_call({down}, _From, _State=[{temp, Temp}, Span]) -> | |||
| {reply, ok, [{temp, Temp-1}, Span]}; | |||
| handle_call({default}, _From, _State=[_T, Span]) -> | |||
| {reply, ok, [{temp, binary_to_integer(?THERMOSTAT_DEFAULT)}, Span]}; | |||
| handle_call({load}, _From, _State=[_T, Span]) -> | |||
| StoredTemp = esp:nvs_get_binary(?NVS_NAMESPACE, thermostat, ?THERMOSTAT_DEFAULT), | |||
| {reply, ok, [{temp, binary_to_integer(StoredTemp)}, Span]}; | |||
| handle_call({save}, _From, State=[{temp, Temp}, {span, Span}]) -> | |||
| debugger:format("[~p:~p] Saving current thermostat value: ~p~n", [?MODULE, ?FUNCTION_NAME, Temp]), | |||
| esp:nvs_set_binary(?NVS_NAMESPACE, thermostat, integer_to_binary(Temp)), | |||
| esp:nvs_set_binary(?NVS_NAMESPACE, span, float_to_binary(Span, [{decimals, 1}])), | |||
| {reply, ok, State}; | |||
| handle_call({set_span, Span}, _From, [{temp, Temp}|_]) -> | |||
| debugger:format("[~p:~p] Setting new span value: ~p~n", [?MODULE, ?FUNCTION_NAME, Span]), | |||
| {reply, ok, [{temp, Temp}, {span, Span/1}]}; %divide by one forces float | |||
| handle_call(get, _From, State) -> | |||
| {reply, State, State}; | |||
| handle_call(Call, _From, State) -> | |||
| debugger:log(Call), | |||
| %erlang:display(Call), | |||
| {reply, ok, State}. | |||
| handle_cast(_Msg, State) -> | |||
| {noreply, State}. | |||
| terminate(_Reason, _State) -> | |||
| ok. | |||
| up() -> | |||
| gen_server:call(?MODULE, {up}). | |||
| down() -> | |||
| gen_server:call(?MODULE, {down}). | |||
| get_thermostat() -> | |||
| gen_server:call(?MODULE, get). | |||
| set_temp(TempInput) -> | |||
| Temp = util:make_int(TempInput), | |||
| gen_server:call(?MODULE, {set_temp, Temp}). | |||
| set_span(DegreesInput) -> | |||
| Span = util:make_float(DegreesInput), | |||
| gen_server:call(?MODULE, {set_span, Span}). | |||
| load() -> | |||
| gen_server:call(?MODULE, {load}). | |||
| save() -> | |||
| gen_server:call(?MODULE, {save}). | |||
| default() -> | |||
| gen_server:call(?MODULE, {default}). | |||
| @ -0,0 +1,206 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(util). | |||
| -export([ set_output/2, set_output_activelow/2, print_time/0, uptime/0, beep/2, make_int/1, make_float/1, convert_to_binary/1 ]). | |||
| set_output(Pin, State) -> | |||
| Level = level(State), %validate the pin state. | |||
| case Level of | |||
| ok -> ok; | |||
| _ -> gpio:digital_write(Pin, Level) | |||
| end. | |||
| set_output_activelow(Pin, State) -> | |||
| Level = level_reverse(level(State)), %validate the pin state. | |||
| case Level of | |||
| ok -> ok; | |||
| _ -> gpio:digital_write(Pin, Level) | |||
| end. | |||
| print_time() -> | |||
| %debugger:format("Printing Time with ~p...~n", [?FUNCTION_NAME]), | |||
| {{Year, Month, Day}, {Hour, Minute, Second}} = erlang:universaltime(), | |||
| debugger:format("Date: ~p/~2..0p/~2..0p ~2..0p:~2..0p:~2..0p (~pms)~n", [ | |||
| Year, Month, Day, Hour, Minute, Second, erlang:system_time(millisecond) | |||
| ]), | |||
| {{Year, Month, Day}, {Hour, Minute, Second}}. | |||
| uptime() -> | |||
| UptimeSec = erlang:monotonic_time(second), | |||
| Days = trunc(UptimeSec/86400), | |||
| Hours = case (UptimeSec > 86400) of | |||
| true -> trunc((UptimeSec rem (Days * 86400))/3600); | |||
| _ -> trunc(UptimeSec/3600) | |||
| end, | |||
| Mins = case (UptimeSec > 3600) of | |||
| true -> trunc((UptimeSec rem (Hours * 3600))/60); | |||
| _ -> trunc(UptimeSec/60) | |||
| end, | |||
| Secs = case (UptimeSec > 60) of | |||
| true -> UptimeSec rem (Mins * 60); | |||
| _ -> UptimeSec | |||
| end, | |||
| {{Y,M,D}, {H,M,S}} = erlang:universaltime(), | |||
| Timestamp = io_lib:format("~p~2..0p~2..0p ~2..0p:~2..0p:~2..0p", [Y, M, D, H, M, S]), | |||
| UptimeMsg = io_lib:format("~p UPTIME: ~p days, ~p hours, ~p minutes, ~p seconds", [Timestamp, Days, Hours, Mins, Secs]), | |||
| io:format("~p~n", [UptimeMsg]), | |||
| UptimeMsg. | |||
| %%% Crude beep/sound functionality | |||
| beep(_Freq, _Duration) when (_Duration =< 1) -> | |||
| ok; | |||
| beep(Freq, DurationMs) -> | |||
| CyclePeriod = 1000 / Freq, %full cycle is 2 switch time intervals | |||
| gpio:digital_write(?BEEPER, high), | |||
| timer:sleep(trunc(CyclePeriod / 2)), | |||
| gpio:digital_write(?BEEPER, low), | |||
| timer:sleep(trunc(CyclePeriod / 2)), | |||
| beep(Freq, DurationMs - CyclePeriod). %not accurate length, but good enough | |||
| level(State) when is_list(State) -> | |||
| level(list_to_binary(State)); | |||
| level(State) -> | |||
| case State of | |||
| %on values: | |||
| 1 -> high; | |||
| on -> high; | |||
| high -> high; | |||
| true -> high; | |||
| <<"1">> -> high; | |||
| <<"on">> -> high; | |||
| <<"ON">> -> high; | |||
| <<"On">> -> high; | |||
| <<"high">> -> high; | |||
| <<"true">> -> high; | |||
| %off values: | |||
| 0 -> low; | |||
| off -> low; | |||
| low -> low; | |||
| false -> low; | |||
| <<"0">> -> low; | |||
| <<"off">> -> low; | |||
| <<"OFF">> -> low; | |||
| <<"Off">> -> low; | |||
| <<"low">> -> low; | |||
| <<"false">> -> low; | |||
| %fallback | |||
| _ -> ok %do nothing | |||
| end. | |||
| level_reverse(State) -> | |||
| case State of | |||
| high -> low; | |||
| low -> high | |||
| end. | |||
| myatom_to_binary(X) -> | |||
| case X of | |||
| on -> <<"on">>; | |||
| off -> <<"off">>; | |||
| cool -> <<"cool">>; | |||
| fan_only -> <<"fan_only">>; | |||
| energy_saver -> <<"energy_saver">>; | |||
| safe -> <<"safe">>; | |||
| wait -> <<"wait">>; | |||
| alarm -> <<"alarm">>; | |||
| ready -> <<"ready">>; | |||
| not_ready -> <<"not_ready">>; | |||
| mqtt_not_ready -> <<"mqtt_not_ready">>; | |||
| local -> <<"local">>; | |||
| remote -> <<"remote">>; | |||
| low -> <<"low">>; | |||
| high -> <<"high">>; | |||
| true -> <<"true">>; | |||
| false -> <<"false">>; | |||
| yes -> <<"yes">>; | |||
| no -> <<"no">>; | |||
| input -> <<"input">>; | |||
| output -> <<"output">>; | |||
| error -> <<"error">>; | |||
| default -> <<"default">> | |||
| end. | |||
| convert_to_binary(X) -> %try to convert anything to a string printable binary | |||
| if | |||
| is_binary(X) -> X; | |||
| %is_atom(X) -> atom_to_binary(X); %atom_to_binary DOESN'T WORK!! (It crashes.) | |||
| is_atom(X) -> myatom_to_binary(X); | |||
| is_tuple(X) -> list_to_binary(io_lib:format("~p", [X])); | |||
| is_float(X) -> float_to_binary(X, [{decimals, ?FLOAT_DECIMAL_LIMIT}]); | |||
| is_integer(X) -> integer_to_binary(X); | |||
| is_list(X) -> | |||
| try | |||
| list_to_binary(X) | |||
| catch _ -> | |||
| try | |||
| list_to_binary(io_lib:format("~p", [X])) | |||
| catch _ -> | |||
| case X of | |||
| [Y|_] -> convert_to_binary(Y); | |||
| _ -> <<"">> | |||
| end | |||
| end | |||
| end; | |||
| true -> <<"">> | |||
| end. | |||
| make_float(X) -> %Give back a float best you can from whatever input | |||
| if | |||
| X == [] -> 0.0; | |||
| is_float(X) -> X; | |||
| is_integer(X) -> X/1; %float(X) DOESN'T WORK, but division by one does. | |||
| is_list(X) -> try % "68" "68.0" "abc" | |||
| make_float(list_to_binary(X)) | |||
| catch _:_ -> | |||
| [Y|_]=X, | |||
| make_float(Y) | |||
| end; | |||
| is_binary(X) -> try binary_to_float(X) | |||
| catch _:_ -> | |||
| try binary_to_integer(X) | |||
| catch _:_ -> 0.0 | |||
| end | |||
| end; | |||
| true -> 0.0 | |||
| end. | |||
| make_int(X) -> %Give back an int best you can from whatever input | |||
| if | |||
| is_integer(X) -> X; | |||
| is_float(X) -> trunc(X); | |||
| X == [] -> 0; | |||
| is_list(X) -> try % "68" "68.0" "abc" | |||
| make_int(list_to_binary(X)) | |||
| catch _:_ -> | |||
| [Y|_]=X, | |||
| make_int(Y) | |||
| end; | |||
| is_binary(X) -> try binary_to_integer(X) | |||
| catch _:_ -> | |||
| try trunc(binary_to_float(X)) | |||
| catch _:_ -> 0 | |||
| end | |||
| end; | |||
| true -> 0 | |||
| end. | |||
| %-spec to_strip_plus(kz_term:ne_binary()) -> kz_term:ne_binary(). | |||
| %to_strip_plus(Number) -> | |||
| % case normalize(Number) of | |||
| % <<$+,N/binary>> -> N; | |||
| % DID -> DID | |||
| % end. | |||
| % -> <<"sofia/", ?SIP_INTERFACE, "/", Contact/binary>> | |||
| @ -0,0 +1,80 @@ | |||
| %% | |||
| %% Copyright (c) 2024 RuhNet | |||
| %% All rights reserved. | |||
| %% | |||
| %% Licensed under the GPL v3. | |||
| %% | |||
| -include("app.hrl"). | |||
| -module(wifi). | |||
| -export([start_link/0]). | |||
| start_link() -> | |||
| Config = [ | |||
| {ap, [ | |||
| {ap_started, fun ap_started/0}, | |||
| {sta_connected, fun sta_connected/1}, | |||
| {sta_ip_assigned, fun sta_ip_assigned/1}, | |||
| {sta_disconnected, fun sta_disconnected/1} | |||
| | maps:get(ap, config:get()) | |||
| ]}, | |||
| {sta, [ | |||
| {connected, fun connected/0}, | |||
| {got_ip, fun got_ip/1}, | |||
| {disconnected, fun disconnected/0} | |||
| | maps:get(sta, config:get()) | |||
| ]}, | |||
| {sntp, [ | |||
| {host, "time-d-b.nist.gov"}, | |||
| {synchronized, fun sntp_synchronized/1} | |||
| ]} | |||
| ], | |||
| case network:start_link(Config) of | |||
| {ok, _Pid} -> | |||
| debugger:format("Network started.~n"), | |||
| {ok, _Pid}; | |||
| %timer:sleep(infinity); | |||
| Error -> | |||
| Error | |||
| end. | |||
| ap_started() -> | |||
| debugger:format("AP started.~n"). | |||
| sta_connected(Mac) -> | |||
| debugger:format("WiFi AP: Station connected with mac ~p~n", [Mac]). | |||
| sta_disconnected(Mac) -> | |||
| debugger:format("WiFi AP: Station ~p disconnected~n", [Mac]). | |||
| sta_ip_assigned(Address) -> | |||
| debugger:format("WiFi AP: Station assigned address ~p~n", [Address]). | |||
| connected() -> | |||
| debugger:format("WiFi Client: connected.~n"). | |||
| got_ip(IpInfo) -> | |||
| debugger:format("WiFi Client: Using IP address: ~p.~n", [IpInfo]), | |||
| % network_services_sup:start_link(). %We have an IP address, so start our network dependant services supervisor | |||
| case whereis(mqtt) of | |||
| undefined -> | |||
| debugger:format("MQTT CONTROLLER NOT RUNNING??~n"); | |||
| _Pid -> gen_server:call(mqtt, start_client) | |||
| end, | |||
| ok. | |||
| disconnected() -> | |||
| debugger:format("WiFi Client: disconnected.~n"), | |||
| timer:sleep(10000), | |||
| debugger:format("WiFi [not] killing myself because of disconnection...~n"), | |||
| timer:sleep(1). | |||
| %exit(kill). %kill myself (supervisor will restart) FIXME: is this best way to handle this?? | |||
| sntp_synchronized({TVSec, TVUsec}) -> | |||
| debugger:format("Synchronized time with SNTP server. TVSec=~p TVUsec=~p~n", [TVSec, TVUsec]), | |||
| util:print_time(), | |||
| debugger:format("Updating system boot time..."), | |||
| debugger:set_boot_time(). | |||