pax_global_header00006660000000000000000000000064146040514640014516gustar00rootroot0000000000000052 comment=e9b4e8d56038270c7b9eb4b9e2ee7f3076ae7abf echoromeo-pynobo-e9b4e8d/000077500000000000000000000000001460405146400155105ustar00rootroot00000000000000echoromeo-pynobo-e9b4e8d/.github/000077500000000000000000000000001460405146400170505ustar00rootroot00000000000000echoromeo-pynobo-e9b4e8d/.github/workflows/000077500000000000000000000000001460405146400211055ustar00rootroot00000000000000echoromeo-pynobo-e9b4e8d/.github/workflows/python-publish.yml000066400000000000000000000020411460405146400246120ustar00rootroot00000000000000# This workflow will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries # This workflow uses actions that are not certified by GitHub. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support # documentation. name: Upload Python Package on: release: types: [published] permissions: contents: read jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build - name: Build package run: python -m build - name: Publish package uses: pypa/gh-action-pypi-publish@release/v1 with: user: __token__ password: ${{ secrets.PYPI_TOKEN }} echoromeo-pynobo-e9b4e8d/.github/workflows/python-test.yml000066400000000000000000000007351460405146400241330ustar00rootroot00000000000000name: Test Python Package on: pull_request: workflow_dispatch: permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] fail-fast: false steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Run tests run: python -m unittest echoromeo-pynobo-e9b4e8d/.gitignore000066400000000000000000000022051460405146400174770ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ echoromeo-pynobo-e9b4e8d/LICENSE000066400000000000000000001045131460405146400165210ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . echoromeo-pynobo-e9b4e8d/MANIFEST.in000066400000000000000000000001161460405146400172440ustar00rootroot00000000000000# Include the README include *.md # Include the license file include LICENSE echoromeo-pynobo-e9b4e8d/README.md000066400000000000000000000122111460405146400167640ustar00rootroot00000000000000# Nobø Hub / Nobø Energy Control TCP/IP Interface This system/service/software is not officially supported or endorsed by Glen Dimplex Nordic AS, and the authors/maintainer(s) are not official partner of Glen Dimplex Nordic AS [The API (v1.1) for Nobø Hub can be found here][api] [api]: https://www.glendimplex.no/media/15650/nobo-hub-api-v-1-1-integration-for-advanced-users.pdf ## Quick Start import asyncio from pynobo import nobo async def main(): # Either call using the three last digits in the hub serial hub = nobo('123', synchronous=False) # or full serial and IP if you do not want to discover on UDP: hub = nobo('123123123123', ip='10.0.0.128', discover=False, synchronous=False) # Connect to the hub and get initial data await hub.connect() # Inspect what you get def update(hub): print(hub.hub_info) print(hub.zones) print(hub.components) print(hub.week_profiles) print(hub.overrides) print(hub.temperatures) # Read the initial data update(hub) # Listen for data updates - register before calling hub.start() to avoid race condition hub.register_callback(callback=update) # Start the background tasks for reading responses and keep connction alive # This will connect to the hub if necessary await hub.start() # Hang around and wait for data updates await asyncio.sleep(60) # Stop the connection await hub.stop() asyncio.run(main()) ## Available functionality * `nobo` class - When called it will initialize logger and dictionaries, connect to hub and start daemon thread. * `nobo.API` class - All the commands and responses from API v1.1, Some with sensible names, others not yet given better names. * `nobo.DiscoveryProtocol` - An `asyncio.DatagramProtocol` used to discover Nobø Ecohubs on the local network. ### Discover and test connection It is possible to discover hubs on the local network, and also test connectivity, before starting the background tasks. # Discover all hubs on local network hubs = await nobo.async_discover_hubs() # Test connection to the first (ip, serial) = hubs.pop() hub = nobo(serial + '123', ip=ip, discover=False, synchronous=False) await hub.connect() # Then start the background tasks await hub.start() # Or just close the connection right away await hub.close() ### Background Tasks Calling `start()` will first try to discover the Nobø Ecohub on the local network, unless `discover` is set to `False`, which required IP address and full serial (12 digits). If an IP address is provided, or the hub is discovered, it will attempt to connect to it, and if successful, start the following tasks: * keep_alive - Send a periodic keep alive message to the hub * socket_receive - Handle incoming messages from the hub If the connection is lost, it will attempt to reconnect. ### Command Functions These functions send commands to the hub. * async_send_command - Send a list of command string(s) to the hub * async_create_override - Override hub/zones/components * async_update_zone - Update the name, week profile, temperature or override allowing for a zone. * async_add_week_profile - Create a week profile * async_update_week_profile - Update a week profile * async_remove_week_profile - Remove a week profile ### Dictionary helper functions These functions simplify getting the data you want from the dictionaries. They do not perform any I/O, and can safely be called from the event loop. * get_week_profile_status - Get the status of a week profile at a certain time in the week * get_current_zone_mode - Get the mode of a zone at a certain time * get_current_component_temperature - Get the current temperature from a component * get_current_zone_temperature - Get the current temperature from (the first component in) a zone * get_zone_override_mode - Get the override mode for the zone ## Backwards compatibility Synchronous wrapper methods are available for compatibility with v1.1.2, but it is recommended to switch to the async methods by initializing the hub with `synchronous=False`. Otherwise, initializing will start the async event loop in a daemon thread, discover and connect to hub before returning as before. import time from pynobo import nobo def main(): # Either call using the three last digits in the hub serial hub = nobo('123') # or full serial and IP if you do not want to discover on UDP: hub = nobo('123123123123', '10.0.0.128', False) # Inspect what you get def update(hub): print(hub.hub_info) print(hub.zones) print(hub.components) print(hub.week_profiles) print(hub.overrides) print(hub.temperatures) # Listen for data updates - register before getting initial data to avoid race condition hub.register_callback(callback=update) # Get initial data update(hub) # Hang around and wait for data updates time.sleep(60) main() echoromeo-pynobo-e9b4e8d/pynobo.py000066400000000000000000001513541460405146400174010ustar00rootroot00000000000000import asyncio import collections from contextlib import suppress import datetime import errno import logging import threading import warnings import socket from typing import Union _LOGGER = logging.getLogger(__name__) # In case any of these errors occurs after successful initial connection, we will try to reconnect. RECONNECT_ERRORS = [ errno.ECONNRESET, # Happens after 24 hours errno.ECONNREFUSED, # Not experienced, but likable to happen in case a reboot of the hub errno.EHOSTUNREACH, # May happen if hub or network switch is temporarily down errno.EHOSTDOWN, # May happen if hub is temporarily down errno.ENETDOWN, # May happen if local network is temporarily down errno.ENETUNREACH, # May happen if hub or local network is temporarily down errno.ETIMEDOUT, # Happens if hub has not responded to handshake in 60 seconds, e.g. due to network issue ] class nobo: """This is where all the Nobø Hub magic happens!""" class API: """ All the commands and responses from API v1.1. Some with sensible names, others not yet given better names. """ VERSION = '1.1' START = 'HELLO' #HELLO REJECT = 'REJECT' #REJECT HANDSHAKE = 'HANDSHAKE' #HANDSHAKE ADD_ZONE = 'A00' # Adds Zone to hub database: A00 ADD_COMPONENT = 'A01' # Adds Component to hub database: A01 ADD_WEEK_PROFILE = 'A02' # Adds Week Profile to hub database: A02 ADD_OVERRIDE = 'A03' # Adds an override to hub database: A03 RESPONSE_ADD_ZONE = 'B00' RESPONSE_ADD_COMPONENT = 'B01' RESPONSE_ADD_WEEK_PROFILE = 'B02' RESPONSE_ADD_OVERRIDE = 'B03' UPDATE_ZONE = 'U00' # Updates Zone to hub database: U00 UPDATE_COMPONENT = 'U01' # Updates Component to hub database: U01 UPDATE_WEEK_PROFILE = 'U02' # Updates Week Profile to hub database: U02 UPDATE_HUB_INFO = 'U03' # Updates hub information: U83 RESPONSE_UPDATE_ZONE = 'V00' RESPONSE_UPDATE_COMPONENT = 'V01' RESPONSE_UPDATE_WEEK_PROFILE = 'V02' RESPONSE_UPDATE_HUB_INFO = 'V03' RESPONSE_UPDATE_INTERNET_ACCESS = 'V06' # Removes a Zone from the hub's internal database. All values except Zone lD is ignored. # Any Components in the Zone are also deleted (and S02 Component deleted messages arc sent for the deleted Components). # Any Component used as temperature sensor for the Zone is modified to no longer be temperature sensor for the Zone (and a V0l Component updated message is sent). # R00 REMOVE_ZONE = 'R00' # Removes a Component from the hub's internal database. All values except Component Serial Number is ignored. # R01 REMOVE_COMPONENT = 'R01' # Removes a WeekProfile from the hub's intemal database. All values except Week Profile lD is ignored. # Any Zones that are set to use the Week Profile are set to use the default Week Profile in stead (and V00 Zone updated messages are sent). # R02 REMOVE_WEEK_PROFILE = 'R02' RESPONSE_REMOVE_ZONE = 'S00' RESPONSE_REMOVE_COMPONENT = 'S01' RESPONSE_REMOVE_WEEK_PROFILE = 'S02' RESPONSE_REMOVE_OVERRIDE = 'S03' # Gets all information from hub. Will trigger a sequence of series of one HOO message, zero or more # HOI, zero or more H02, zero or more Y02, zero or more H03, zero or more H04 commands, one V06 # message if <.:onne<.:ted v ia LAN (not Internet), and lastly a H05 message. 'll1e client knows # that the Hub is tlnished sending all info when it has received the H05 mess3ge. GET_ALL_INFO = 'G00' # (Never used by the Nobo Energy Control app- you should only use GOO.) Gets all Zones lrom hub. # Will trigger a series of H01 messages from the Hub. GET_ALL_ZONES = 'G01' # (Never used by the Nobo Energy Control app - you should only use GOO.) Gets all Components li·om hub. # Will result i n a series of H02 messages from the Hub. GET_ALL_COMPONENTS = 'G02' # (Never used by the Nobo Energy Control app- you should only use GOO.) Gets all WeekProfile data from hub. # Will trigger a series of 1103 messages from the lluh. GET_ALL_WEEK_PROFILES = 'G03' # (Never used by the Nobo Energy Control app - you should only use GOO.) Gets all active overrrides from hub. # Will trigger a series of H04 messages from the Hub. GET_ACTIVE_OVERRIDES = 'G04' RESPONSE_SENDING_ALL_INFO = 'H00' # Response to GET_ALL_INFO signifying that all relevant info stored in Hub is about to be sent. RESPONSE_ZONE_INFO = 'H01' # Response with Zone info, one per message: H01 RESPONSE_COMPONENT_INFO = 'H02' # Response with Component info, one per message: H02 RESPONSE_WEEK_PROFILE_INFO = 'H03' # Response with Week Profile info, one per message: H03 RESPONSE_OVERRIDE_INFO = 'H04' # Response with override info, one per message: H04 RESPONSE_HUB_INFO = 'H05' # G00 request complete signal + static info: H05 EXECUTE_START_SEARCH = 'X00' EXECUTE_STOP_SEARCH = 'X01' EXECUTE_COMPONENT_PAIR = 'X03' RESPONSE_STARTED_SEARCH = 'Y00' RESPONSE_STOPPED_SEARCH = 'Y01' RESPONSE_COMPONENT_TEMP = 'Y02' # Component temperature value sent as part of a GOO response, or pushed from the Hub automatically to all connected clients whenever the Hub has received updated temperature data. RESPONSE_COMPONENT_PAIR = 'Y03' RESPONSE_COMPONENT_FOUND = 'Y04' RESPONSE_ERROR = 'E00' # Other error messages than E00 may also be sent from the Hub (E01, E02 etc.): E00 OVERRIDE_MODE_NORMAL = '0' OVERRIDE_MODE_COMFORT = '1' OVERRIDE_MODE_ECO = '2' OVERRIDE_MODE_AWAY = '3' OVERRIDE_MODES = [OVERRIDE_MODE_NORMAL, OVERRIDE_MODE_COMFORT, OVERRIDE_MODE_ECO, OVERRIDE_MODE_AWAY] OVERRIDE_TYPE_NOW = '0' OVERRIDE_TYPE_TIMER = '1' OVERRIDE_TYPE_FROM_TO = '2' OVERRIDE_TYPE_CONSTANT = '3' OVERRIDE_TYPES = [OVERRIDE_TYPE_NOW, OVERRIDE_TYPE_TIMER, OVERRIDE_TYPE_FROM_TO, OVERRIDE_TYPE_CONSTANT] OVERRIDE_TARGET_GLOBAL = '0' OVERRIDE_TARGET_ZONE = '1' OVERRIDE_TARGET_COMPONENT = '2' # Not implemented yet OVERRIDE_TARGETS = [OVERRIDE_TARGET_GLOBAL, OVERRIDE_TARGET_ZONE, OVERRIDE_TARGET_COMPONENT] OVERRIDE_NOT_ALLOWED = '0' OVERRIDE_ALLOWED = '1' OVERRIDE_ID_NONE = '-1' OVERRIDE_ID_HUB = '-1' WEEK_PROFILE_STATE_ECO = '0' WEEK_PROFILE_STATE_COMFORT = '1' WEEK_PROFILE_STATE_AWAY = '2' WEEK_PROFILE_STATE_OFF = '4' STRUCT_KEYS_HUB = ['serial', 'name', 'default_away_override_length', 'override_id', 'software_version', 'hardware_version', 'production_date'] STRUCT_KEYS_ZONE = ['zone_id', 'name', 'week_profile_id', 'temp_comfort_c', 'temp_eco_c', 'override_allowed', 'deprecated_override_id'] STRUCT_KEYS_COMPONENT = ['serial', 'status', 'name', 'reverse_onoff', 'zone_id', 'override_id', 'tempsensor_for_zone_id'] STRUCT_KEYS_WEEK_PROFILE = ['week_profile_id', 'name', 'profile'] # profile is minimum 7 and probably more values separated by comma STRUCT_KEYS_OVERRIDE = ['override_id', 'mode', 'type', 'end_time', 'start_time', 'target_type', 'target_id'] NAME_OFF = 'off' NAME_AWAY = 'away' NAME_ECO = 'eco' NAME_COMFORT = 'comfort' NAME_NORMAL = 'normal' DICT_OVERRIDE_MODE_TO_NAME = {OVERRIDE_MODE_NORMAL : NAME_NORMAL, OVERRIDE_MODE_COMFORT : NAME_COMFORT, OVERRIDE_MODE_ECO : NAME_ECO, OVERRIDE_MODE_AWAY : NAME_AWAY} DICT_WEEK_PROFILE_STATUS_TO_NAME = {WEEK_PROFILE_STATE_ECO : NAME_ECO, WEEK_PROFILE_STATE_COMFORT : NAME_COMFORT, WEEK_PROFILE_STATE_AWAY : NAME_AWAY, WEEK_PROFILE_STATE_OFF : NAME_OFF} DICT_NAME_TO_OVERRIDE_MODE = {NAME_NORMAL : OVERRIDE_MODE_NORMAL, NAME_COMFORT : OVERRIDE_MODE_COMFORT, NAME_ECO : OVERRIDE_MODE_ECO, NAME_AWAY : OVERRIDE_MODE_AWAY} DICT_NAME_TO_WEEK_PROFILE_STATUS = {NAME_ECO : WEEK_PROFILE_STATE_ECO, NAME_COMFORT : WEEK_PROFILE_STATE_COMFORT, NAME_AWAY : WEEK_PROFILE_STATE_AWAY, NAME_OFF : WEEK_PROFILE_STATE_OFF} def is_valid_datetime(timestamp: str): if len(timestamp) != 12: # Leading zero is optional for some of the fields below, but we require it. return False try: datetime.datetime.strptime(timestamp, '%Y%m%d%H%M') except ValueError: return False return True def time_is_quarter(minutes: str): return int(minutes) % 15 == 0 def validate_temperature(temperature: Union[int, str]): if type(temperature) not in (int, str): raise TypeError('Temperature must be integer or string') if isinstance(temperature, str) and not temperature.isdigit(): raise ValueError(f'Temperature "{temperature}" must be digits') temperature_int = int(temperature) if temperature_int < 7: raise ValueError(f'Min temperature is 7°C') if temperature_int > 30: raise ValueError(f'Max temperature is 30°C') def validate_week_profile(profile): if type(profile) != list: raise ValueError("Week profile must be a list") day_count=0 for i in profile: if len(i) != 5: raise ValueError(f"Invalid week profile entry: {i}") time = datetime.datetime.strptime(i[0:4], "%H%M") if not time.minute % 15 == 0: raise ValueError(f"Week profile entry not in whole quarters: {i}") # Last character is state (0=Eco, 1=Comfort, 2=Away, 4=Off) if not i[4] in "0124": raise ValueError(f"Week profile entry contains invalid state, must be 0, 1, 2, or 4: {i}") if time.hour == 0 and time.minute == 0: day_count+=1 if day_count != 7: raise ValueError("Week profile must contain exactly 7 entries for midnight (starting with 0000)") class Model: """ A device model that supports Nobø Ecohub. Official lists of devices: https://help.nobo.no/en/user-manual/before-you-start/what-is-a-receiver/list-of-receivers/ https://help.nobo.no/en/user-manual/before-you-start/what-is-a-transmitter/list-of-transmitters/ """ THERMOSTAT_HEATER = "THERMOSTAT_HEATER" THERMOSTAT_FLOOR = "THERMOSTAT_FLOOR" THERMOSTAT_ROOM = "THERMOSTAT_ROOM" SWITCH = "SWITCH" SWITCH_OUTLET = "SWITCH_OUTLET" CONTROL_PANEL = "CONTROL_PANEL" UNKNOWN = "UNKNOWN" def __init__( self, model_id: str, type: Union[THERMOSTAT_HEATER, THERMOSTAT_FLOOR, THERMOSTAT_ROOM, SWITCH, SWITCH_OUTLET, CONTROL_PANEL, UNKNOWN], name: str, *, supports_comfort: bool = False, supports_eco: bool = False, requires_control_panel = False, has_temp_sensor: bool = False): self._model_id = model_id self._type = type self._name = name self._supports_comfort = supports_comfort self._supports_eco = supports_eco self._requires_control_panel = requires_control_panel self._has_temp_sensor = has_temp_sensor @property def model_id(self) -> str: """Model id of the component (first 3 digits of the serial number).""" return self._model_id @property def name(self) -> str: """Model name.""" return self._name @property def type(self) -> Union[THERMOSTAT_HEATER, THERMOSTAT_FLOOR, THERMOSTAT_ROOM, SWITCH, SWITCH_OUTLET, CONTROL_PANEL, UNKNOWN]: """Model type.""" return self._type @property def supports_comfort(self) -> bool: """Return True if comfort temperature can be set on hub.""" return self._supports_comfort @property def supports_eco(self) -> bool: """Return True if eco temperature can be set on hub.""" return self._supports_eco @property def requires_control_panel(self) -> bool: """Return True if setting temperature on hub requires a control panel in the zone.""" return self._requires_control_panel @property def has_temp_sensor(self) -> bool: """Return True if component has a temperature sensor.""" return self._has_temp_sensor MODELS = { "120": Model("120", Model.SWITCH, "RS 700"), "121": Model("121", Model.SWITCH, "RSX 700"), "130": Model("130", Model.SWITCH_OUTLET, "RCE 700"), "160": Model("160", Model.THERMOSTAT_HEATER, "R80 RDC 700"), "165": Model("165", Model.THERMOSTAT_HEATER, "R80 RDC 700 LST (GB)"), "168": Model("168", Model.THERMOSTAT_HEATER, "NCU-2R", supports_comfort=True, supports_eco=True), "169": Model("169", Model.THERMOSTAT_HEATER, "DCU-2R", supports_comfort=True, supports_eco=True), "170": Model("170", Model.THERMOSTAT_HEATER, "Serie 18, ewt touch", supports_comfort=True, supports_eco=True), # Not verified if temperature can be set remotely "180": Model("180", Model.THERMOSTAT_HEATER, "2NC9 700", supports_eco=True), "182": Model("182", Model.THERMOSTAT_HEATER, "R80 RSC 700 (5-24)", supports_eco=True), "183": Model("183", Model.THERMOSTAT_HEATER, "R80 RSC 700 (5-30)", supports_eco=True), "184": Model("184", Model.THERMOSTAT_HEATER, "NCU-1R", supports_eco=True), "186": Model("186", Model.THERMOSTAT_HEATER, "DCU-1R", supports_eco=True), "190": Model("190", Model.THERMOSTAT_HEATER, "Safir", supports_comfort=True, supports_eco=True, requires_control_panel=True), "192": Model("192", Model.THERMOSTAT_HEATER, "R80 TXF 700", supports_comfort=True, supports_eco=True, requires_control_panel=True), "194": Model("194", Model.THERMOSTAT_HEATER, "R80 RXC 700", supports_comfort=True, supports_eco=True), "198": Model("198", Model.THERMOSTAT_HEATER, "NCU-ER", supports_comfort=True, supports_eco=True), "199": Model("199", Model.THERMOSTAT_HEATER, "DCU-ER", supports_comfort=True, supports_eco=True), "200": Model("200", Model.THERMOSTAT_FLOOR, "TRB 36 700"), "210": Model("210", Model.THERMOSTAT_FLOOR, "NTB-2R", supports_comfort=True, supports_eco=True), "220": Model("220", Model.THERMOSTAT_FLOOR, "TR36", supports_eco=True), "230": Model("230", Model.THERMOSTAT_ROOM, "TCU 700"), "231": Model("231", Model.THERMOSTAT_ROOM, "THB 700"), "232": Model("232", Model.THERMOSTAT_ROOM, "TXB 700"), "234": Model("234", Model.CONTROL_PANEL, "SW4", has_temp_sensor=True), } class DiscoveryProtocol(asyncio.DatagramProtocol): """Protocol to discover Nobø Echohub on local network.""" def __init__(self, serial = '', ip = None): """ :param serial: The last 3 digits of the Ecohub serial number or the complete 12 digit serial number :param ip: ip address to search for Ecohub at (default None) """ self.serial = serial self.ip = ip self.hubs = set() def connection_made(self, transport: asyncio.transports.DatagramTransport): self.transport = transport def datagram_received(self, data: bytes, addr): msg = data.decode('utf-8') _LOGGER.info('broadcast received: %s from %s', msg, addr[0]) # Expected string “__NOBOHUB__123123123”, where 123123123 is replaced with the first 9 digits of the Hub’s serial number. if msg.startswith('__NOBOHUB__'): discover_serial = msg[11:] discover_ip = addr[0] if len(self.serial) == 12: if discover_serial != self.serial[0:9]: # This is not the Ecohub you are looking for discover_serial = None else: discover_serial = self.serial else: discover_serial += self.serial if self.ip and discover_ip != self.ip: # This is not the Ecohub you are looking for discover_ip = None if discover_ip and discover_serial: self.hubs.add( (discover_ip, discover_serial) ) def __init__(self, serial, ip=None, discover=True, loop=None, synchronous=True, timezone: datetime.tzinfo=None): """ Initialize logger and dictionaries. :param serial: The last 3 digits of the Ecohub serial number or the complete 12 digit serial number :param ip: IP address to search for Ecohub at (default None) :param discover: True/false for using UDP autodiscovery for the IP (default True) :param loop: Deprecated :param synchronous: True/false for using the module synchronously. For backwards compatibility. """ self.serial = serial self.ip = ip self.discover = discover if loop is not None: _LOGGER.warning("loop is deprecated. Use synchronous=False instead.") synchronous=False self.timezone = timezone self._callbacks = [] self._reader = None self._writer = None self._keep_alive_task = None self._socket_receive_task = None self._received_all_info = False self.hub_info = {} self.zones = collections.OrderedDict() self.components = collections.OrderedDict() self.week_profiles = collections.OrderedDict() self.overrides = collections.OrderedDict() self.temperatures = collections.OrderedDict() if synchronous: # Run asyncio in a separate thread try: loop = asyncio.get_running_loop() except RuntimeError: _LOGGER.debug("Creating new event loop") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self.start()) _LOGGER.debug("Creating daemon thread") thread = threading.Thread(target=lambda: loop.run_forever()) thread.setDaemon(True) thread.start() def register_callback(self, callback=lambda *args, **kwargs: None): """ Register a callback to notify updates to the hub state. The callback MUST be safe to call from the event loop. The nobo instance is passed to the callback function. Limit callbacks to read state. :param callback: a callback method """ self._callbacks.append(callback) def deregister_callback(self, callback=lambda *args, **kwargs: None): """ Deregister a previously registered callback. :param callback: a callback method """ self._callbacks.remove(callback) async def connect(self): """Connect to Ecohub, either by scanning or directly.""" connected = False if self.discover: _LOGGER.info('Looking for Nobø Ecohub with serial: %s and ip: %s', self.serial, self.ip) discovered_hubs = await self.async_discover_hubs(serial=self.serial, ip=self.ip) if not discovered_hubs: _LOGGER.error('Failed to discover any Nobø Ecohubs') raise Exception('Failed to discover any Nobø Ecohubs') while discovered_hubs: (discover_ip, discover_serial) = discovered_hubs.pop() connected = await self.async_connect_hub(discover_ip, discover_serial) if connected: break # We connect to the first valid hub, no reason to try the rest else: # check if we have an IP if not self.ip: _LOGGER.error('Could not connect, no ip address provided') raise ValueError('Could not connect, no ip address provided') # check if we have a valid serial before we start connection if len(self.serial) != 12: _LOGGER.error('Could not connect, no valid serial number provided') raise ValueError('Could not connect, no valid serial number provided') connected = await self.async_connect_hub(self.ip, self.serial) if not connected: _LOGGER.error('Could not connect to Nobø Ecohub') raise Exception(f'Failed to connect to Nobø Ecohub with serial: {self.serial} and ip: {self.ip}') async def start(self): """Discover Ecohub and start the TCP client.""" if not self._writer: await self.connect() # Start the tasks to send keep-alive and receive data self._keep_alive_task = asyncio.create_task(self.keep_alive()) self._socket_receive_task = asyncio.create_task(self.socket_receive()) _LOGGER.info('connected to Nobø Ecohub') async def stop(self): """Stop the keep-alive and receiver tasks and close the connection to Nobø Ecohub.""" if self._keep_alive_task: self._keep_alive_task.cancel() with suppress(asyncio.CancelledError): await self._keep_alive_task if self._socket_receive_task: self._socket_receive_task.cancel() with suppress(asyncio.CancelledError): await self._keep_alive_task await self.close() _LOGGER.info('disconnected from Nobø Ecohub') async def close(self): """Close the connection to Nobø Ecohub.""" if self._writer: self._writer.close() with suppress(ConnectionError): await self._writer.wait_closed() self._writer = None _LOGGER.info('connection closed') def connect_hub(self, ip, serial): try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete(self.async_connect_hub(ip, serial)) async def async_connect_hub(self, ip, serial): """ Attempt initial connection and handshake. :param ip: The ecohub ip address to connect to :param serial: The complete 12 digit serial number of the hub to connect to """ if len(serial) != 12 or not serial.isdigit(): raise ValueError(f'Invalid serial number: {serial}') self._reader, self._writer = await asyncio.wait_for(asyncio.open_connection(ip, 27779), timeout=5) # start handshake: "HELLO \r" now = datetime.datetime.now(self.timezone).strftime('%Y%m%d%H%M%S') await self.async_send_command([nobo.API.START, nobo.API.VERSION, serial, now]) # receive the response data (4096 is recommended buffer size) response = await asyncio.wait_for(self.get_response(), timeout=5) _LOGGER.debug('first handshake response: %s', response) # successful response is "HELLO \r" if response[0] == nobo.API.START: # send “REJECT\r” if command set is not supported? No need to abort if Hub is ok with the mismatch? if response[1] != nobo.API.VERSION: #await self.async_send_command([nobo.API.REJECT]) _LOGGER.warning('api version might not match, hub: v%s, pynobo: v%s', response[1], nobo.API.VERSION) warnings.warn(f'api version might not match, hub: v{response[1]}, pynobo: v{nobo.API.VERSION}') #overkill? # send/receive handshake complete await self.async_send_command([nobo.API.HANDSHAKE]) response = await asyncio.wait_for(self.get_response(), timeout=5) _LOGGER.debug('second handshake response: %s', response) if response[0] == nobo.API.HANDSHAKE: # Connect OK, store full serial for reconnect self.hub_ip = ip self.hub_serial = serial # Get initial data await asyncio.wait_for(self._get_initial_data(), timeout=5) for callback in self._callbacks: callback(self) return True else: # Something went wrong... _LOGGER.error('Final handshake not as expected %s', response) await self.close() raise Exception(f'Final handshake not as expected {response}') if response[0] == nobo.API.REJECT: # This may not be the hub we are looking for # Reject response: "REJECT \r" # 0=Client command set version too old (or too new!). # 1=Hub serial number mismatch. # 2=Wrong number of arguments. # 3=Timestamp incorrectly formatted _LOGGER.warning('connection to hub rejected: %s', response) await self.close() return False # Unexpected response _LOGGER.error('connection to hub rejected: %s', response) raise Exception(f'connection to hub rejected: {response}') async def reconnect_hub(self): """Attempt to reconnect to the hub.""" _LOGGER.info('reconnecting to hub') # Pause keep alive during reconnect self._keep_alive = False # TODO: set timeout? if self.discover: # Reconnect using complete serial, but allow ip to change unless originally provided discovered_hubs = await self.async_discover_hubs(ip=self.ip, serial=self.hub_serial, rediscover=True) while discovered_hubs: (discover_ip, discover_serial) = discovered_hubs.pop() try: connected = await self.async_connect_hub(discover_ip, discover_serial) if connected: break except OSError as e: # We know we should be able to connect, because we just discovered the IP address. However, if # the connection was lost due to network problems on our host, we must wait until we have a local # IP address. E.g. discovery may find Nobø Ecohub before DHCP address is assigned. if e.errno in RECONNECT_ERRORS: _LOGGER.warning("Failed to connect to ip %s: %s", discover_ip, e) discovered_hubs.add( (discover_ip, discover_serial) ) await asyncio.sleep(1) else: raise e else: connected = False while not connected: _LOGGER.debug('Discovery disabled - waiting 10 seconds before trying to reconnect.') await asyncio.sleep(10) with suppress(asyncio.TimeoutError): try: connected = await self.async_connect_hub(self.ip, self.serial) except OSError as e: if e.errno in RECONNECT_ERRORS: _LOGGER.debug('Ignoring %s', e) else: raise e self._keep_alive = True _LOGGER.info('reconnected to Nobø Hub') @staticmethod def discover_hubs(serial="", ip=None, autodiscover_wait=3.0, loop=None): if loop is not None: _LOGGER.warning("loop is deprecated") try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete(nobo.async_discover_hubs(serial, ip, autodiscover_wait)) @staticmethod async def async_discover_hubs(serial="", ip=None, autodiscover_wait=3.0, loop=None, rediscover=False): """ Attempt to autodiscover Nobø Ecohubs on the local network. Every two seconds, the Hub sends one UDP broadcast packet on port 10000 to broadcast IP 255.255.255.255, we listen for this package, and collect every packet that contains the magic __NOBOHUB__ identifier. The set of (ip, serial) tuples is returned. Specifying a complete 12 digit serial number or an ip address, will only attempt to discover hubs matching that serial, ip address or both. Specifyng the last 3 digits of the serial number will append this to the discovered serial number. Not specifying serial or ip will include all found hubs on the network, but only the discovered part of the serial number (first 9 digits). :param serial: The last 3 digits of the Ecohub serial number or the complete 12 digit serial number :param ip: ip address to search for Ecohub at (default None) :param autodiscover_wait: how long to wait for an autodiscover package from the hub (default 3.0) :param loop: deprecated :param rediscover: if true, run until the hub is discovered :return: a set of hubs matching that serial, ip address or both """ if loop is not None: _LOGGER.warning("loop is deprecated.") transport, protocol = await asyncio.get_running_loop().create_datagram_endpoint( lambda: nobo.DiscoveryProtocol(serial, ip), local_addr=('0.0.0.0', 10000), reuse_port=nobo._reuse_port()) try: await asyncio.sleep(autodiscover_wait) while rediscover and not protocol.hubs: await asyncio.sleep(autodiscover_wait) finally: transport.close() return protocol.hubs @staticmethod def _reuse_port() -> bool: """ Check if we can set `reuse_port` when listening for broadcasts. To support Windows. """ if hasattr(socket, 'SO_REUSEPORT'): sock = socket.socket(type=socket.SOCK_DGRAM) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.close() return True except OSError: pass return False async def keep_alive(self, interval = 14): """ Send a periodic handshake. Needs to be sent every < 30 sec, preferably every 14 seconds. :param interval: seconds between each handshake. Default 14. """ self._keep_alive = True while True: await asyncio.sleep(interval) if self._keep_alive: await self.async_send_command([nobo.API.HANDSHAKE]) def _create_task(self, target): try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.call_soon_threadsafe(lambda: loop.create_task(target)) def send_command(self, commands): self._create_task(self.async_send_command(commands)) async def async_send_command(self, commands): """ Send a list of command string(s) to the hub. :param commands: list of commands, either strings or integers """ if not self._writer: return _LOGGER.debug('sending: %s', commands) # Convert integers to string for idx, c in enumerate(commands): if isinstance(c, int): commands[idx] = str(c) message = ' '.join(commands).encode('utf-8') try: self._writer.write(message + b'\r') await self._writer.drain() except ConnectionError as e: _LOGGER.info('lost connection to hub (%s)', e) await self.close() async def _get_initial_data(self): self._received_all_info = False await self.async_send_command([nobo.API.GET_ALL_INFO]) while not self._received_all_info: self.response_handler(await self.get_response()) async def get_response(self): """ Get a response string from the hub and reformat string list before returning it. :return: a single response as a list of strings where each string is a field """ try: message = await self._reader.readuntil(b'\r') message = message[:-1] except ConnectionError as e: _LOGGER.info('lost connection to hub (%s)', e) await self.close() raise e response = message.decode('utf-8').split(' ') _LOGGER.debug('received: %s', response) return response async def socket_receive(self): try: while True: try: response = await self.get_response() if response[0] == nobo.API.HANDSHAKE: pass # Handshake, no action needed elif response[0] == 'E': _LOGGER.error('error! what did you do? %s', response) # TODO: Raise something here? else: self.response_handler(response) for callback in self._callbacks: callback(self) except (asyncio.IncompleteReadError) as e: _LOGGER.info('Reconnecting due to %s', e) await self.reconnect_hub() except (OSError) as e: if e.errno in RECONNECT_ERRORS: _LOGGER.info('Reconnecting due to %s', e) await self.reconnect_hub() else: raise e except asyncio.CancelledError: _LOGGER.debug('socket_receive stopped') except Exception as e: # Ops, now we have real problems _LOGGER.error('Unhandled exception %s', e, exc_info=1) # Just disconnect (instead of risking an infinite reconnect loop) await self.stop() def response_handler(self, response): """ Handle the response(s) from the hub and update the dictionaries accordingly. :param response: list of strings where each string is a field """ # All info incoming, clear existing info if response[0] == nobo.API.RESPONSE_SENDING_ALL_INFO: self._received_all_info = False self.hub_info = {} self.zones = {} self.components = {} self.week_profiles = {} self.overrides = {} # The added/updated info messages elif response[0] in [nobo.API.RESPONSE_ZONE_INFO, nobo.API.RESPONSE_ADD_ZONE , nobo.API.RESPONSE_UPDATE_ZONE]: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_ZONE, response[1:])) self.zones[dicti['zone_id']] = dicti _LOGGER.info('added/updated zone: %s', dicti['name']) elif response[0] in [nobo.API.RESPONSE_COMPONENT_INFO, nobo.API.RESPONSE_ADD_COMPONENT , nobo.API.RESPONSE_UPDATE_COMPONENT]: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_COMPONENT, response[1:])) if dicti['zone_id'] == '-1' and dicti['tempsensor_for_zone_id'] != '-1': dicti['zone_id'] = dicti['tempsensor_for_zone_id'] serial = dicti['serial'] model_id = serial[:3] if model_id in nobo.MODELS: dicti['model'] = nobo.MODELS[model_id] else: dicti['model'] = nobo.Model( model_id, nobo.Model.UNKNOWN, f'Unknown (serial number: {serial[:3]} {serial[3:6]} {serial[6:9]} {serial[9:]})' ) self.components[dicti['serial']] = dicti _LOGGER.info('added/updated component: %s', dicti['name']) elif response[0] in [nobo.API.RESPONSE_WEEK_PROFILE_INFO, nobo.API.RESPONSE_ADD_WEEK_PROFILE, nobo.API.RESPONSE_UPDATE_WEEK_PROFILE]: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_WEEK_PROFILE, response[1:])) dicti['profile'] = response[-1].split(',') self.week_profiles[dicti['week_profile_id']] = dicti _LOGGER.info('added/updated week profile: %s', dicti['name']) elif response[0] in [nobo.API.RESPONSE_OVERRIDE_INFO, nobo.API.RESPONSE_ADD_OVERRIDE]: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_OVERRIDE, response[1:])) self.overrides[dicti['override_id']] = dicti _LOGGER.info('added/updated override: id %s', dicti['override_id']) elif response[0] in [nobo.API.RESPONSE_HUB_INFO, nobo.API.RESPONSE_UPDATE_HUB_INFO]: self.hub_info = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_HUB, response[1:])) _LOGGER.info('updated hub info: %s', self.hub_info) if response[0] == nobo.API.RESPONSE_HUB_INFO: self._received_all_info = True # The removed info messages elif response[0] == nobo.API.RESPONSE_REMOVE_ZONE: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_ZONE, response[1:])) self.zones.pop(dicti['zone_id'], None) _LOGGER.info('removed zone: %s', dicti['name']) elif response[0] == nobo.API.RESPONSE_REMOVE_COMPONENT: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_COMPONENT, response[1:])) self.components.pop(dicti['serial'], None) _LOGGER.info('removed component: %s', dicti['name']) elif response[0] == nobo.API.RESPONSE_REMOVE_WEEK_PROFILE: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_WEEK_PROFILE, response[1:])) self.week_profiles.pop(dicti['week_profile_id'], None) _LOGGER.info('removed week profile: %s', dicti['name']) elif response[0] == nobo.API.RESPONSE_REMOVE_OVERRIDE: dicti = collections.OrderedDict(zip(nobo.API.STRUCT_KEYS_OVERRIDE, response[1:])) self.overrides.pop(dicti['override_id'], None) _LOGGER.info('removed override: %s', dicti['override_id']) # Component temperature data elif response[0] == nobo.API.RESPONSE_COMPONENT_TEMP: self.temperatures[response[1]] = response[2] _LOGGER.info('updated temperature from %s: %s', response[1], response[2]) # Internet settings elif response[0] == nobo.API.RESPONSE_UPDATE_INTERNET_ACCESS: internet_access = response[1] encryption_key = 0 for i in range(2, 18): encryption_key = (encryption_key << 8) + int(response[i]) _LOGGER.info('internet enabled: %s, key: %s', internet_access, hex(encryption_key)) else: _LOGGER.warning('behavior undefined for this response: %s', response) warnings.warn(f'behavior undefined for this response: {response}') #overkill? def create_override(self, mode, type, target_type, target_id='-1', end_time='-1', start_time='-1'): self._create_task(self.async_create_override(mode, type, target_type, target_id, end_time, start_time)) async def async_create_override(self, mode, type, target_type, target_id='-1', end_time='-1', start_time='-1'): """ Override hub/zones/components. Use OVERRIDE_MODE_NORMAL to disable an existing override. :param mode: API.OVERRIDE_MODE. NORMAL, COMFORT, ECO or AWAY :param type: API.OVERRIDE_TYPE. NOW, TIMER, FROM_TO or CONSTANT :param target_type: API.OVERRIDE_TARGET. GLOBAL or ZONE :param target_id: the target id (default -1) :param end_time: the end time (default -1), format YYYYMMDDhhmm, where mm must be in whole 15 minutes :param start_time: the start time (default -1), format YYYYMMDDhhmm, where mm must be in whole 15 minutes """ if not mode in nobo.API.OVERRIDE_MODES: raise ValueError(f'Unknown override mode {mode}') if not type in nobo.API.OVERRIDE_TYPES: raise ValueError(f'Unknown override type {type}') if not target_type in nobo.API.OVERRIDE_TARGETS: raise ValueError(f'Unknown override target type {target_type}') if target_id != '-1' and not target_id in self.zones: raise ValueError(f'Unknown override target {target_id}') if end_time != '-1': if not nobo.API.is_valid_datetime(end_time): raise ValueError(f'Illegal end_time {end_time}: Cannot parse') if not nobo.API.time_is_quarter(end_time[-2:]): raise ValueError(f'Illegal end_time {end_time}: Must be in whole 15 minutes') if start_time != '-1': if not nobo.API.is_valid_datetime(start_time): raise ValueError(f'Illegal start_time: {start_time}: Cannot parse') if not nobo.API.time_is_quarter(end_time[-2:]): raise ValueError(f'Illegal start_time {end_time}: Must be in whole 15 minutes') command = [nobo.API.ADD_OVERRIDE, '1', mode, type, end_time, start_time, target_type, target_id] await self.async_send_command(command) for o in self.overrides: # Save override before command has finished executing if self.overrides[o]['target_id'] == target_id: self.overrides[o]['mode'] = mode self.overrides[o]['type'] = type def update_zone(self, zone_id, name=None, week_profile_id=None, temp_comfort_c=None, temp_eco_c=None, override_allowed=None): self._create_task(self.async_update_zone(zone_id, name, week_profile_id, temp_comfort_c, temp_eco_c, override_allowed)) async def async_update_zone(self, zone_id, name=None, week_profile_id=None, temp_comfort_c=None, temp_eco_c=None, override_allowed=None): """ Update the name, week profile, temperature or override allowing for a zone. :param zone_id: the zone id :param name: the new zone name (default None) :param week_profile_id: the new id for a week profile (default None) :param temp_comfort_c: the new comfort temperature (default None) :param temp_eco_c: the new eco temperature (default None) :param override_allowed: the new override allow setting (default None) """ if not zone_id in self.zones: raise ValueError(f'Unknown zone id {zone_id}') # Initialize command with the current zone settings command = [nobo.API.UPDATE_ZONE] + list(self.zones[zone_id].values()) # Replace command with arguments that are not None. if name: name = name.replace(" ", "\u00A0") if len(name.encode('utf-8')) > 100: raise ValueError(f'Zone name "{name}" too long (max 100 bytes when encoded as UTF-8)') command[2] = name if week_profile_id: if not week_profile_id in self.week_profiles: raise ValueError(f'Unknown week profile id {week_profile_id}') command[3] = week_profile_id if temp_comfort_c: nobo.API.validate_temperature(temp_comfort_c) command[4] = temp_comfort_c self.zones[zone_id]['temp_comfort_c'] = temp_comfort_c # Save setting before sending command if temp_eco_c: nobo.API.validate_temperature(temp_eco_c) command[5] = temp_eco_c self.zones[zone_id]['temp_eco_c'] = temp_eco_c # Save setting before sending command if override_allowed: if override_allowed != nobo.API.OVERRIDE_NOT_ALLOWED and override_allowed != nobo.API.OVERRIDE_ALLOWED: raise ValueError(f'Illegal value for override allowed: {override_allowed}') command[6] = override_allowed if int(command[4]) < int(command[5]): raise ValueError(f'Comfort temperature({command[4]}°C) cannot be less than eco temperature({command[5]}°C)') await self.async_send_command(command) async def async_add_week_profile(self, name, profile=None): """ Add the name and profile parameter for a week. :param name: the new zone name :param profile: the new profile (default None) """ # if no profile is defined if profile is None: profile=['00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000'] _LOGGER.debug('profile: %s', ",".join(profile)) nobo.API.validate_week_profile(profile) # profile id is decided by the hub week_profile_id='0' converted_profile =','.join(profile) name = name.replace(" ", "\u00A0") if len(name.encode('utf-8')) > 100: raise ValueError(f'Zone name "{name}" too long (max 100 bytes when encoded as UTF-8)') command = [nobo.API.ADD_WEEK_PROFILE] + [week_profile_id] + [name] + [converted_profile] await self.async_send_command(command) async def async_update_week_profile(self, week_profile_id: str, name=None, profile=None): """ Update the name and profile parameter for a week. :param week_profile_id: the week_profile_id :param name: the new zone name (default None) :param profile: the new profile (default None) """ if week_profile_id not in self.week_profiles: raise ValueError(f"Unknown week profile {week_profile_id}") if name is None and profile is None: raise ValueError("Set at least name or profile to update") if name: name = name.replace(" ", "\u00A0") if len(name.encode('utf-8')) > 100: raise ValueError(f'Zone name "{name}" too long (max 100 bytes when encoded as UTF-8)') else: name = self.week_profiles[week_profile_id]["name"] if profile: nobo.API.validate_week_profile(profile) else: profile = self.week_profiles[week_profile_id]["profile"] command = [nobo.API.UPDATE_WEEK_PROFILE, week_profile_id, name, ','.join(profile)] await self.async_send_command(command) async def async_remove_week_profile(self, week_profile_id: str): """ Remove the week profile. :param week_profile_id: the week_profile_id """ if week_profile_id not in self.week_profiles: raise ValueError(f"Unknown week profile {week_profile_id}") if week_profile_id in (v['week_profile_id'] for k, v in self.zones.items()): raise ValueError(f"Week profile {week_profile_id} in use, can not remove") name = self.week_profiles[week_profile_id]["name"] profile = self.week_profiles[week_profile_id]["profile"] command = [nobo.API.REMOVE_WEEK_PROFILE, week_profile_id, name, ','.join(profile)] await self.async_send_command(command) def get_week_profile_status(self, week_profile_id, dt=datetime.datetime.today()): """ Get the status of a week profile at a certain time in the week. Monday is day 0. :param week_profile_id: -- the week profile id in question :param dt: -- datetime for the status in question (default datetime.datetime.today()) :return: the status for the profile """ profile = self.week_profiles[week_profile_id]['profile'] target = (dt.hour*100) + dt.minute # profile[0] is always 0000x, so this provides the initial status status = profile[0][-1] weekday = 0 for timestamp in profile[1:]: if timestamp[:4] == '0000': weekday += 1 if weekday == dt.weekday(): if int(timestamp[:4]) <= target: status = timestamp[-1] else: break _LOGGER.debug('Status at %s on weekday %s is %s', target, dt.weekday(), nobo.API.DICT_WEEK_PROFILE_STATUS_TO_NAME[status]) return nobo.API.DICT_WEEK_PROFILE_STATUS_TO_NAME[status] def get_zone_override_mode(self, zone_id): """ Get the override mode of a zone. :param zone_id: the zone id in question :return: the override mode for the zone """ mode = nobo.API.NAME_NORMAL for o in self.overrides: if self.overrides[o]['mode'] == '0': continue # "normal" overrides elif (self.overrides[o]['target_type'] == nobo.API.OVERRIDE_TARGET_ZONE and self.overrides[o]['target_id'] == zone_id): mode = nobo.API.DICT_OVERRIDE_MODE_TO_NAME[self.overrides[o]['mode']] # Takes precedence over global override break elif (self.zones[zone_id]['override_allowed'] == '1' and self.overrides[o]['target_type'] == nobo.API.OVERRIDE_TARGET_GLOBAL): mode = nobo.API.DICT_OVERRIDE_MODE_TO_NAME[self.overrides[o]['mode']] _LOGGER.debug('Current override for zone %s is %s', self.zones[zone_id]['name'], mode) return mode def get_current_zone_mode(self, zone_id, now=None): """ Get the mode of a zone at a certain time. If the zone is overridden only now is possible. :param zone_id: the zone id in question :param now: datetime for the status in question (default datetime.datetime.today()) :return: the mode for the zone """ if now is None: now = datetime.datetime.today() current_time = (now.hour*100) + now.minute current_mode = self.get_zone_override_mode(zone_id) if current_mode == nobo.API.NAME_NORMAL: # no override - find mode from week profile current_mode = self.get_week_profile_status(self.zones[zone_id]['week_profile_id'], now) _LOGGER.debug('Current mode for zone %s at %s is %s', self.zones[zone_id]['name'], current_time, current_mode) return current_mode def get_current_component_temperature(self, serial): """ Get the current temperature from a component. :param serial: the serial for the component in question :return: the temperature for the component (default N/A) """ current_temperature = None if serial in self.temperatures: current_temperature = self.temperatures[serial] if current_temperature == 'N/A': current_temperature = None if current_temperature: _LOGGER.debug('Current temperature for component %s is %s', self.components[serial]['name'], current_temperature) return current_temperature # Function to get (first) temperature in a zone def get_current_zone_temperature(self, zone_id): """ Get the current temperature from (the first component in) a zone. :param zone_id: the id for the zone in question :return: the temperature for the (first) component in the zone (default N/A) """ current_temperature = None for c in self.components: if self.components[c]['zone_id'] == zone_id: current_temperature = self.get_current_component_temperature(c) if current_temperature != None: break if current_temperature: _LOGGER.debug('Current temperature for zone %s is %s', self.zones[zone_id]['name'], current_temperature) return current_temperature echoromeo-pynobo-e9b4e8d/setup.cfg000066400000000000000000000010241460405146400173260ustar00rootroot00000000000000[metadata] # This includes the license file in the wheel. license_file = LICENSE [bdist_wheel] # This flag says to generate wheels that support both Python 2 and Python # 3. If your code will not run unchanged on both Python 2 and 3, you will # need to generate separate wheels for each Python version that you # support. Removing this line (or setting universal to 0) will prevent # bdist_wheel from trying to make a universal wheel. For more see: # https://packaging.python.org/tutorials/distributing-packages/#wheels universal=0echoromeo-pynobo-e9b4e8d/setup.py000066400000000000000000000153371460405146400172330ustar00rootroot00000000000000"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # Arguments marked as "Required" below must be included for upload to PyPI. # Fields marked as "Optional" may be commented out. setup( name='pynobo', # Versions should comply with PEP 440: # https://www.python.org/dev/peps/pep-0440/ # # For a discussion on single-sourcing the version across setup.py and the # project code, see # https://packaging.python.org/en/latest/single_source_version.html version='1.8.1', description='Nobø Hub / Nobø Energy Control TCP/IP Interface', license='GPLv3+', # This is an optional longer description of your project that represents # the body of text which users will see when they visit PyPI. # # Often, this is the same as your README, so you can just read it in from # that file directly (as we have already done above) # # This field corresponds to the "Description" metadata field: # https://packaging.python.org/specifications/core-metadata/#description-optional long_description=long_description, long_description_content_type='text/markdown', # This should be a valid link to your project's main homepage. # # This field corresponds to the "Home-Page" metadata field: # https://packaging.python.org/specifications/core-metadata/#home-page-optional url='https://github.com/echoromeo/pynobo', # This should be your name or the name of the organization which owns the # project. author='echoromeo, capelevy, oyvindwe', # author_email='project@email.com', # Optional # Classifiers help users find your project by categorizing it. # # For a list of valid classifiers, see https://pypi.org/classifiers/ classifiers=[ # Optional # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Home Automation', # Pick your license as you wish 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', ], # This field adds keywords for your project which will appear on the # project page. What does your project relate to? # # Note that this is a string of words separated by whitespace, not a list. keywords='hvac nobø heating automation', # You can just specify package directories manually here if your project is # simple. Or you can use find_packages(). # # Alternatively, if you just want to distribute a single Python file, use # the `py_modules` argument instead as follows, which will expect a file # called `my_module.py` to exist: # # py_modules=["my_module"], # # packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Required py_modules=["pynobo"], # Specify which Python versions you support. In contrast to the # 'Programming Language' classifiers above, 'pip install' will check this # and refuse to install the project if the version does not match. See # https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires python_requires='>=3.7, <4', # This field lists other packages that your project depends on to run. # Any package you put here will be installed by pip when your project is # installed, so they must be valid existing projects. # # For an analysis of "install_requires" vs pip's requirements files see: # https://packaging.python.org/en/latest/requirements.html # install_requires=['asyncio', 'collections', 'contextlib', 'datetime', 'errno', 'logging', 'time', 'threading', 'warnings'], # All are there by default? # List additional groups of dependencies here (e.g. development # dependencies). Users will be able to install these using the "extras" # syntax, for example: # # $ pip install sampleproject[dev] # # Similar to `install_requires` above, these must be valid existing # projects. # extras_require={ # Optional # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. # # If using Python 2.6 or earlier, then these have to be included in # MANIFEST.in as well. # package_data={ # Optional # 'sample': ['package_data.dat'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # # In this case, 'data_file' will be installed into '/my_data' # data_files=[('my_data', ['data/data_file'])], # Optional # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # `pip` to create the appropriate form of executable for the target # platform. # # For example, the following would provide a command called `sample` which # executes the function `main` from this package when invoked: # entry_points={ # Optional # 'console_scripts': [ # 'sample=sample:main', # ], # }, # List additional URLs that are relevant to your project as a dict. # # This field corresponds to the "Project-URL" metadata fields: # https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use # # Examples listed include a pattern for specifying where the package tracks # issues, where the source is hosted, where to say thanks to the package # maintainers, and where to support the project financially. The key is # what's used to render the link text on PyPI. project_urls={ 'Bug Reports': 'https://github.com/echoromeo/pynobo/issues', # 'Funding': 'https://donate.pypi.org', # 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/echoromeo/pynobo/blob/master/pynobo.py', }, ) echoromeo-pynobo-e9b4e8d/test_pynobo.py000066400000000000000000000051531460405146400204330ustar00rootroot00000000000000import unittest from pynobo import nobo class TestValidation(unittest.TestCase): def test_is_valid_datetime(self): self.assertTrue(nobo.API.is_valid_datetime("202404041800")) self.assertFalse(nobo.API.is_valid_datetime("2024040418001")) self.assertFalse(nobo.API.is_valid_datetime("20240404180")) self.assertFalse(nobo.API.is_valid_datetime("invalid")) def test_time_is_quarter(self): self.assertTrue(nobo.API.time_is_quarter("00")) self.assertTrue(nobo.API.time_is_quarter("15")) self.assertTrue(nobo.API.time_is_quarter("30")) self.assertTrue(nobo.API.time_is_quarter("45")) self.assertFalse(nobo.API.time_is_quarter("01")) self.assertFalse(nobo.API.time_is_quarter("59")) def test_validate_temperature(self): nobo.API.validate_temperature("20") nobo.API.validate_temperature(20) nobo.API.validate_temperature(7) nobo.API.validate_temperature(30) with self.assertRaises(TypeError): nobo.API.validate_temperature(0.0) with self.assertRaisesRegex(ValueError, "must be digits"): nobo.API.validate_temperature("foo") with self.assertRaisesRegex(ValueError, "Min temperature is 7"): nobo.API.validate_temperature(6) with self.assertRaisesRegex(ValueError, "Max temperature is 30"): nobo.API.validate_temperature(31) def test_validate_week_profile(self): nobo.API.validate_week_profile(['00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000','00000','12001','16000']) nobo.API.validate_week_profile(['00000','00000','00000','00000','00000','00000','00000']) nobo.API.validate_week_profile(['00000','00001','00002','00004','00000','00000','00000']) with self.assertRaisesRegex(ValueError, "must contain exactly 7 entries for midnight"): nobo.API.validate_week_profile(['00000','00000','00000','00000','00000','00000']) with self.assertRaisesRegex(ValueError, "must contain exactly 7 entries for midnight"): nobo.API.validate_week_profile(['00000','00000','00000','00000','00000','00000','00000','00000']) with self.assertRaisesRegex(ValueError, "invalid state"): nobo.API.validate_week_profile(['00003','00000','00000','00000','00000','00000','00000']) with self.assertRaisesRegex(ValueError, "not in whole quarters"): nobo.API.validate_week_profile(['00000','01231','00000','00000','00000','00000','00000','00000']) if __name__ == '__main__': unittest.main()