pax_global_header00006660000000000000000000000064150017742020014510gustar00rootroot0000000000000052 comment=87e0645c43e97b174a11d418c6231686ae0f8d12 dio-chacon-wifi-api-1.2.2/000077500000000000000000000000001500177420200152215ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/.gitignore000066400000000000000000000060521500177420200172140ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # 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/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ Commands.txt save-avant-aiohttp.zip dio-chacon-wifi-api-1.2.2/.pre-commit-config.yaml000066400000000000000000000013521500177420200215030ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: check-yaml - id: check-toml - id: check-added-large-files - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/python-poetry/poetry rev: '1.8.3' hooks: - id: poetry-check - repo: https://github.com/pycqa/flake8 rev: '7.1.1' hooks: - id: flake8 additional_dependencies: [Flake8-pyproject] - repo: https://github.com/psf/black rev: '24.8.0' hooks: - id: black language_version: python3 - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.2 hooks: - id: ruff args: [ --fix ] - id: ruff-format dio-chacon-wifi-api-1.2.2/.readthedocs.yaml000066400000000000000000000006701500177420200204530ustar00rootroot00000000000000# .readthedocs.yaml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Set the version of Python and other tools you might need build: os: ubuntu-22.04 tools: python: "3.10" mkdocs: configuration: mkdocs.yml # Optionally declare the Python requirements required to build your docs python: install: - requirements: docs/requirements.txt dio-chacon-wifi-api-1.2.2/.vscode/000077500000000000000000000000001500177420200165625ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/.vscode/launch.json000066400000000000000000000014031500177420200207250ustar00rootroot00000000000000{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { //Cf : https://github.com/python-poetry/poetry/issues/5354 "name": "Python: Remote Attach", "type": "debugpy", "request": "attach", "connect": { "host": "localhost", "port": 5678 }, "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ], "justMyCode": false } ] } dio-chacon-wifi-api-1.2.2/LICENSE000066400000000000000000001045151500177420200162340ustar00rootroot00000000000000 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 . dio-chacon-wifi-api-1.2.2/Protocol.md000066400000000000000000000220411500177420200173430ustar00rootroot00000000000000# Protocol for DIO devices Here is a description of the wifi protocol to be used through the chacon's cloud in order to connect and handle DIO devices (REV-SHUTTER, REV-LIGHT or Prise ON/OFF). # Connection : There is 2 way to connect to the cloud service: ## WS login Directly connect in websocket: l4hfront-prod.chacon.cloud/ws?email=USER&password=PASSWORD&serviceName=SERVICE_NAME USER is to be replaced by your user's mail. PASSWORD is to be replaced by your password. SERVICE_NAME An arbitrary string identifying this client ## HTTP login First use this type of REST request : Server Url : https://l4hfront-prod.chacon.cloud/api/session/login Content : {"email":"USER","password":"PASSWORD","installationId":"top"} USER is to be replaced by your user's mail. PASSWORD is to be replaced by your password. installationId should have the value of your installation instance but we send it an arbitrary content here. Typical answer : {"status":200,"data":{"sessionToken":"r:9deb0bfeb982314029166810e940f3ab"}} Then switch to WebSockets since devices actions and states are handled via a websocket connection. Url for websockets switching : l4hfront-prod.chacon.cloud/ws?sessionToken=r:9deb0bfeb982314029166810e940f3ab ## Connection response At connection, it responds with a content like : {"name":"connection","action":"success","data":""} In case there an issue with the sessionToken or with the provided credentials, it responds with: {"name":"connection","action":"invalid","data":""} # User info retrieval : Send this content to the web socket : {"method":"GET","path":"/user","parameters":{},"id":1} Note : the id attribute for each request has to be incremented since the response always contains an id that corresponds to the question. The response will be of the following type (I replaced some content with dots) : { "id": 2, "status": 200, "data": { "id": "...", "name": "... ", "email": "...", "isNewsletter": true, "isPromoNotification": true, "isAIImageObjectDetection": true, "bleKey": "..." } } # Devices retrieval : Send this content to the web socket : {"method":"GET","path":"/device","parameters":{},"id":1} The response will be of the following type (I replaced some content with dots) : { "id": 1, "status": 200, "data": [ { "id": "L4HActuator_...", "createdAt": "...", "provider": "L4HActuator", "name": "...", "defaultName": "CERSwd-3B", "modelName": "CERSwd-3B", "vendor": "Chacon", "hardwareVersion": "1.0", "softwareVersion": "1.0.6", "macAddress": "...", "type": ".dio1.wifi.shutter.mvt_linear.", "roomId": "...", "image": null }, { ... } ] } For a light switch, type will be : .dio1.wifi.genericSwitch.switch. For a plug switch, type will be : .dio1.wifi.plug.switch. # Devices position retrieval : {"method":"POST","path":"/device/states","parameters":{"devices":["L4HActuator_...", ... ]},"id":22} Will return the status of every given device via such an answer : { "id": 22, "status": 200, "data": { "L4HActuator_...": { "rt": "oic.d.blind", "href": "/v1/devices/L4HActuator_...", "provider": "L4HActuator", "rc": 0, "t": 0, "di": "L4HActuator_...", "n": "CERSwd-3B_...", "links": [ { "rt": "oic.wk.p", ... }, { "rt": "oic.r.movement.linear", "href": "mvtlinear", "movement": "stop", "movementSettings": [ "stop", "up", "down" ] }, { "rt": "oic.r.openlevel", "href": "openlevel", "openLevel": 0 }, { "rt": "gw.r.shutter.calibration", "href": "shuttercalibration", "up_ms": 10683, "down_ms": 10370, "direction": 0, "reset": false, "door": false }, { "rt": "gw.r.schedule", "href": "schedule", ... ] }, { "rt": "gw.r.dio1.switch", "href": "dio1_switch", "value": 0 }, { "rt": "gw.r.dio1.paired", "href": "dio1paired", ... } ] }, {...} } } Relevant informations are the movement attribute describing if the shutter is moving up, down or stopped ; the openlevel and the shutter calibration. To know if a device is connected or disconnected from the wifi, in the 'rt'='oic.d.blind' section, the attribute 'rc' to 1 means the device is connected and to 0 is that it is disconnected. # Shutter device action : "stop", "up" or "down" action : {"method":"POST","path":"/device/L4HActuator_.../action/mvtlinear","parameters":{"movement":"down"},"id":8} The Response sends immediately an acknowledge response : {"id":8,"status":200} Then the server sends one event containing some data including the configuration and the current position of the shutter. { "name": "deviceState", "action": "update", "data": {... } } At the end of movment, another response is sent from the server that is similar to the previous answer but with a "stop" event. An attribute named openlevel with a value between 0 and 100 gives the current high of the shutter. Action to set a given position, for exemple 75% opened : {"method":"POST","path":"/device/L4HActuator_.../action/openlevel","parameters":{"openLevel":75},"id":24} NOTE : For group actions or multiple shutter, simply send as many json request as shutters to act on. # Device switch retrieval : {"method":"POST","path":"/device/states","parameters":{"devices":["L4HActuator_...", ... ]},"id":22} Will return the status of every given device via such an answer : { "id": 6, "status": 200, "data": { "L4HActuator_...": { "rt": "oic.d.switch", "href": "/v1/devices/L4HActuator_...", "provider": "L4HActuator", "rc": 1, "t": 0, "di": "L4HActuator_...", "n": "CWMSwd-2B_...", "links": [ { "rt": "oic.wk.p", "href": "platform", ... }, { "rt": "oic.r.switch.binary", "href": "switch", "value": 0 }, { "rt": "gw.r.quietmode", "href": "quietmode", "value": 0 }, { "rt": "gw.r.schedule", "href": "schedule", "maxSchedules": 8, "sun": 1, "schedules": [ ... ] }, { "rt": "gw.r.dio1.paired", "href": "dio1paired", ... } ] } } } The oic.r.switch.binary gives the information if the switch is on or off. # Switching a switch on or off : {"method":"POST","path":"/device/L4HActuator_.../action/switch","parameters":{"value":0},"id":12} Possible values are 0 or 1 to switch on or off. # Disconnecting : {"method":"POST","path":"/session/logout","parameters":{},"id":13} > Only required if you are connected using a sessionToken # Other API verbs not implemented by this lib : Via the Web socket, send either one of this request : For rooms definitions retrieval : {"method":"GET","path":"/room","parameters":{},"id":3} For groups definitions retrieval : {"method":"GET","path":"/group","parameters":{},"id":4} For static content in the mobile app : {"method":"GET","path":"/static/all","parameters":{},"id":5} For device renaming from the mobile App, a server message is sent : {'name': 'device', 'action': 'update', 'data': {'id': 'L4HActuator_....', 'provider': 'L4HActuator', 'name': 'New name for light', 'modelName': 'CWMSwd-2B', 'vendor': 'Chacon', 'hardwareVersion': '1.0', 'softwareVersion': '1.0.6', 'macAddress': '...', 'type': '.dio1.wifi.genericSwitch.switch.', 'roomName': '...', 'roomId': '...', 'image': None, 'isNew': False}} For plug setting's to set the blue status light on or off : {"method":"POST","path":"/device/L4HActuator_..../action/quietmode","parameters":{"value":1},"id":9} dio-chacon-wifi-api-1.2.2/README.md000066400000000000000000000104751500177420200165070ustar00rootroot00000000000000# Dio Chacon Wifi API [![PyPi](https://img.shields.io/pypi/v/dio-chacon-wifi-api)](https://pypi.org/project/dio-chacon-wifi-api) [![GitHub Release](https://img.shields.io/github/release/cnico/dio-chacon-wifi-api.svg)](https://github.com/cnico/dio-chacon-wifi-api/releases) [![Python Version](https://img.shields.io/pypi/pyversions/dio-chacon-wifi-api)](https://pypi.org/project/dio-chacon-wifi-api/) [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Read the docs](https://img.shields.io/readthedocs/dio-chacon-wifi-api/latest.svg?label=Read%20the%20Docs)](https://dio-chacon-wifi-api.readthedocs.io/) [![Codecov](https://codecov.io/gh/cnico/dio-chacon-wifi-api/branch/main/graph/badge.svg)](https://codecov.io/gh/cnico/dio-chacon-wifi-api) [![Github Activity](https://img.shields.io/github/commit-activity/y/cnico/dio-chacon-wifi-api.svg)](https://github.com/cnico/dio-chacon-wifi-api/commits/main) DIO Chacon are devices mainly distributed in the European market. Chacon provide various device to control switches, shutters, camera, lights, etc. The website contains it all : [https://chacon.com/](https://chacon.com/) The cool thing about their device is that they have RF (433Mhz, used by remote control in house) and Wifi protocols (used by the mobile App). The wifi protocol is cloud based with their server and quite reactive through permanent connections (via websockets). This project is a simple implementation, based on the Wifi protocol, of a python client to give the possibility to connect and acts on the devices. It currently supports switches (plugs or wall box for lights) and shutters. It can lists all registered devices (via the mobile app), get their status (on/off ; open level) and act on them (switch on/off ; move up/down/stop cover or move a given percentage of openess). It is used in a [HomeAssistant]() integration but is also usable in other automation platforms (jeedom, etc). ## Using this library To implement a client that interact with Chacon devices, simply have look at [test_integrations_switch.py](https://github.com/cnico/dio-chacon-wifi-api/blob/main//tests/test_integrations_switch.py) or [test_integrations_shutter.py](https://github.com/cnico/dio-chacon-wifi-api/blob/main//tests/test_integrations_shutter.py) that provide effective implementations. The library is published in [pypi.org](https://pypi.org/) and so can be very easily used in any python project (with python > 3.10). `pip install dio-chacon-wifi-api` Note that after the first API call, the connection to the chacon's cloud server is a open in a form of a websocket. To close it, you have to call disconnect method. Note also that this client has auto reconnection implemented in case of a network temporary failure for example. ## Contributing to this project If you find bugs or want to improve the library, simply open an issue and propose PR to merge. Chacon have lots of devices that could be managed via this library. ## Design principles The wifi protocol is described in [Protocol.md](https://github.com/cnico/dio-chacon-wifi-api/blob/main/Protocol.md). You can test this protocol manually through postman with establishing a connection via correct authentification (email + password of your chacon mobile app account) ; then upgrade the connection to Websocket and then interact with json messages in the Websocket stream. For the implementation of the library, it is based on the great [aiohttp](https://docs.aiohttp.org/) library that we use as a http client for REST requests and websocket exchange. All the library is asynchronous and based on [asyncio](https://docs.python.org/3/library/asyncio-dev.html). The websocket permanent connection is established lazily when it is necessary (for example for devices discovery) by an asyncio task. This tasks keeps the connection permanent via automatic ping/pong messages. The protocol is based two types of interaction : - Requests / Responses : this is handled via json message sent in the websocket with an id (the library automatically manages this id) and a response received from the server that has the same id has the request. - Server side sent messages : these push messages (for example a switch manually switched on/off with the button or other event) are sent back to the registerer callback method when you initialize the client. dio-chacon-wifi-api-1.2.2/docs/000077500000000000000000000000001500177420200161515ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/docs/api.md000066400000000000000000000001071500177420200172420ustar00rootroot00000000000000# API Reference ::: src.dio_chacon_wifi_api.client.DIOChaconAPIClient dio-chacon-wifi-api-1.2.2/docs/index.md000066400000000000000000000000161500177420200175770ustar00rootroot00000000000000{!README.md!} dio-chacon-wifi-api-1.2.2/docs/requirements.in000066400000000000000000000000551500177420200212240ustar00rootroot00000000000000mkdocs mkdocstrings[python] markdown-include dio-chacon-wifi-api-1.2.2/docs/requirements.txt000066400000000000000000000026161500177420200214420ustar00rootroot00000000000000# # This file is autogenerated by pip-compile with Python 3.10 # by the following command: # # pip-compile docs/requirements.in # click==8.1.7 # via # mkdocs # mkdocstrings colorama==0.4.6 # via griffe ghp-import==2.1.0 # via mkdocs griffe==0.42.1 # via mkdocstrings-python jinja2==3.1.3 # via # mkdocs # mkdocstrings markdown==3.6 # via # markdown-include # mkdocs # mkdocs-autorefs # mkdocstrings # pymdown-extensions markdown-include==0.8.1 # via -r docs/requirements.in markupsafe==2.1.5 # via # jinja2 # mkdocs # mkdocs-autorefs # mkdocstrings mergedeep==1.3.4 # via mkdocs mkdocs==1.5.3 # via # -r docs/requirements.in # mkdocs-autorefs # mkdocstrings mkdocs-autorefs==1.0.1 # via mkdocstrings mkdocstrings[python]==0.24.3 # via # -r docs/requirements.in # mkdocstrings-python mkdocstrings-python==1.9.2 # via mkdocstrings packaging==24.0 # via mkdocs pathspec==0.12.1 # via mkdocs platformdirs==4.2.0 # via # mkdocs # mkdocstrings pymdown-extensions==10.7.1 # via mkdocstrings python-dateutil==2.9.0.post0 # via ghp-import pyyaml==6.0.1 # via # mkdocs # pymdown-extensions # pyyaml-env-tag pyyaml-env-tag==0.1 # via mkdocs six==1.16.0 # via python-dateutil watchdog==4.0.0 # via mkdocs dio-chacon-wifi-api-1.2.2/mkdocs.yml000066400000000000000000000005731500177420200172310ustar00rootroot00000000000000site_name: Dio Chacon Wifi API theme: name: readthedocs highlightjs: true plugins: - search - mkdocstrings: handlers: # See: https://mkdocstrings.github.io/python/usage/ python: options: docstring_style: google show_source: false markdown_extensions: - markdown_include.include: base_path: . - admonition dio-chacon-wifi-api-1.2.2/poetry.lock000066400000000000000000000446161500177420200174300ustar00rootroot00000000000000[[package]] name = "aiohttp" version = "3.9.3" description = "Async http client/server framework (asyncio)" category = "main" optional = false python-versions = ">=3.8" [package.dependencies] aiosignal = ">=1.1.2" async-timeout = {version = ">=4.0,<5.0", markers = "python_version < \"3.11\""} attrs = ">=17.3.0" frozenlist = ">=1.1.1" multidict = ">=4.5,<7.0" yarl = ">=1.0,<2.0" [package.extras] speedups = ["brotlicffi", "brotli", "aiodns"] [[package]] name = "aioresponses" version = "0.7.6" description = "Mock out requests made by ClientSession from aiohttp package" category = "dev" optional = false python-versions = "*" [package.dependencies] aiohttp = ">=3.3.0,<4.0.0" [[package]] name = "aiosignal" version = "1.3.1" description = "aiosignal: a list of registered asynchronous callbacks" category = "main" optional = false python-versions = ">=3.7" [package.dependencies] frozenlist = ">=1.1.0" [[package]] name = "async-timeout" version = "4.0.3" description = "Timeout context manager for asyncio programs" category = "main" optional = false python-versions = ">=3.7" [[package]] name = "attrs" version = "23.2.0" description = "Classes Without Boilerplate" category = "main" optional = false python-versions = ">=3.7" [package.extras] cov = ["attrs", "coverage[toml] (>=5.3)"] dev = ["attrs", "pre-commit"] docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"] tests = ["attrs", "zope-interface"] tests-mypy = ["mypy (>=1.6)", "pytest-mypy-plugins"] tests-no-zope = ["attrs", "cloudpickle", "hypothesis", "pympler", "pytest-xdist", "pytest (>=4.3.0)"] [[package]] name = "black" version = "24.2.0" description = "The uncompromising code formatter." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] click = ">=8.0.0" mypy-extensions = ">=0.4.3" packaging = ">=22.0" pathspec = ">=0.9.0" platformdirs = ">=2" tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} [package.extras] colorama = ["colorama (>=0.4.3)"] d = ["aiohttp (>=3.7.4,!=3.9.0)", "aiohttp (>=3.7.4)"] jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] uvloop = ["uvloop (>=0.15.2)"] [[package]] name = "certifi" version = "2024.2.2" description = "Python package for providing Mozilla's CA Bundle." category = "dev" optional = false python-versions = ">=3.6" [[package]] name = "cfgv" version = "3.4.0" description = "Validate configuration and produce human readable error messages." category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "charset-normalizer" version = "3.3.2" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." category = "dev" optional = false python-versions = ">=3.7.0" [[package]] name = "click" version = "8.1.7" description = "Composable command line interface toolkit" category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] colorama = {version = "*", markers = "platform_system == \"Windows\""} [[package]] name = "codecov" version = "2.1.13" description = "Hosted coverage reports for GitHub, Bitbucket and Gitlab" category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [package.dependencies] coverage = "*" requests = ">=2.7.9" [[package]] name = "colorama" version = "0.4.6" description = "Cross-platform colored terminal text." category = "dev" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" [[package]] name = "coverage" version = "7.4.4" description = "Code coverage measurement for Python" category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""} [package.extras] toml = ["tomli"] [[package]] name = "debugpy" version = "1.8.1" description = "An implementation of the Debug Adapter Protocol for Python" category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "distlib" version = "0.3.8" description = "Distribution utilities" category = "dev" optional = false python-versions = "*" [[package]] name = "exceptiongroup" version = "1.2.0" description = "Backport of PEP 654 (exception groups)" category = "dev" optional = false python-versions = ">=3.7" [package.extras] test = ["pytest (>=6)"] [[package]] name = "filelock" version = "3.13.1" description = "A platform independent file lock." category = "dev" optional = false python-versions = ">=3.8" [package.extras] docs = ["furo (>=2023.9.10)", "sphinx-autodoc-typehints (>=1.24)", "sphinx (>=7.2.6)"] testing = ["covdefaults (>=2.3)", "coverage (>=7.3.2)", "diff-cover (>=8)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest-timeout (>=2.2)", "pytest (>=7.4.3)"] typing = ["typing-extensions (>=4.8)"] [[package]] name = "flake8" version = "7.0.0" description = "the modular source code checker: pep8 pyflakes and co" category = "dev" optional = false python-versions = ">=3.8.1" [package.dependencies] mccabe = ">=0.7.0,<0.8.0" pycodestyle = ">=2.11.0,<2.12.0" pyflakes = ">=3.2.0,<3.3.0" [[package]] name = "frozenlist" version = "1.4.1" description = "A list-like structure which implements collections.abc.MutableSequence" category = "main" optional = false python-versions = ">=3.8" [[package]] name = "ghp-import" version = "2.1.0" description = "Copy your docs directly to the gh-pages branch." category = "dev" optional = false python-versions = "*" [package.dependencies] python-dateutil = ">=2.8.1" [package.extras] dev = ["twine", "markdown", "flake8", "wheel"] [[package]] name = "griffe" version = "0.42.1" description = "Signatures for entire Python programs. Extract the structure, the frame, the skeleton of your project, to generate API documentation or find breaking changes in your API." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] colorama = ">=0.4" [[package]] name = "identify" version = "2.5.34" description = "File identification library for Python" category = "dev" optional = false python-versions = ">=3.8" [package.extras] license = ["ukkonen"] [[package]] name = "idna" version = "3.6" description = "Internationalized Domain Names in Applications (IDNA)" category = "main" optional = false python-versions = ">=3.5" [[package]] name = "iniconfig" version = "2.0.0" description = "brain-dead simple config-ini parsing" category = "dev" optional = false python-versions = ">=3.7" [[package]] name = "jinja2" version = "3.1.3" description = "A very fast and expressive template engine." category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] MarkupSafe = ">=2.0" [package.extras] i18n = ["Babel (>=2.7)"] [[package]] name = "markdown" version = "3.6" description = "Python implementation of John Gruber's Markdown." category = "dev" optional = false python-versions = ">=3.8" [package.extras] docs = ["mkdocs (>=1.5)", "mkdocs-nature (>=0.6)", "mdx-gh-links (>=0.2)", "mkdocstrings", "mkdocs-gen-files", "mkdocs-section-index", "mkdocs-literate-nav"] testing = ["coverage", "pyyaml"] [[package]] name = "markdown-include" version = "0.8.1" description = "A Python-Markdown extension which provides an 'include' function" category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] markdown = ">=3.0" [package.extras] tests = ["pytest"] [[package]] name = "markupsafe" version = "2.1.5" description = "Safely add untrusted strings to HTML/XML markup." category = "dev" optional = false python-versions = ">=3.7" [[package]] name = "mccabe" version = "0.7.0" description = "McCabe checker, plugin for flake8" category = "dev" optional = false python-versions = ">=3.6" [[package]] name = "mergedeep" version = "1.3.4" description = "A deep merge function for 🐍." category = "dev" optional = false python-versions = ">=3.6" [[package]] name = "mkdocs" version = "1.5.3" description = "Project documentation with Markdown." category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] click = ">=7.0" colorama = {version = ">=0.4", markers = "platform_system == \"Windows\""} ghp-import = ">=1.0" jinja2 = ">=2.11.1" markdown = ">=3.2.1" markupsafe = ">=2.0.1" mergedeep = ">=1.3.4" packaging = ">=20.5" pathspec = ">=0.11.1" platformdirs = ">=2.2.0" pyyaml = ">=5.1" pyyaml-env-tag = ">=0.1" watchdog = ">=2.0" [package.extras] i18n = ["babel (>=2.9.0)"] min-versions = ["babel (==2.9.0)", "click (==7.0)", "colorama (==0.4)", "ghp-import (==1.0)", "importlib-metadata (==4.3)", "jinja2 (==2.11.1)", "markdown (==3.2.1)", "markupsafe (==2.0.1)", "mergedeep (==1.3.4)", "packaging (==20.5)", "pathspec (==0.11.1)", "platformdirs (==2.2.0)", "pyyaml-env-tag (==0.1)", "pyyaml (==5.1)", "typing-extensions (==3.10)", "watchdog (==2.0)"] [[package]] name = "mkdocs-autorefs" version = "1.0.1" description = "Automatically link across pages in MkDocs." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] Markdown = ">=3.3" markupsafe = ">=2.0.1" mkdocs = ">=1.1" [[package]] name = "mkdocstrings" version = "0.24.3" description = "Automatic documentation from sources, for MkDocs." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] click = ">=7.0" Jinja2 = ">=2.11.1" Markdown = ">=3.3" MarkupSafe = ">=1.1" mkdocs = ">=1.4" mkdocs-autorefs = ">=0.3.1" platformdirs = ">=2.2.0" pymdown-extensions = ">=6.3" [package.extras] crystal = ["mkdocstrings-crystal (>=0.3.4)"] python-legacy = ["mkdocstrings-python-legacy (>=0.2.1)"] python = ["mkdocstrings-python (>=0.5.2)"] [[package]] name = "mkdocstrings-python" version = "1.9.2" description = "A Python handler for mkdocstrings." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] griffe = ">=0.37" mkdocstrings = ">=0.24.2" [[package]] name = "multidict" version = "6.0.5" description = "multidict implementation" category = "main" optional = false python-versions = ">=3.7" [[package]] name = "mypy-extensions" version = "1.0.0" description = "Type system extensions for programs checked with the mypy type checker." category = "dev" optional = false python-versions = ">=3.5" [[package]] name = "nodeenv" version = "1.8.0" description = "Node.js virtual environment builder" category = "dev" optional = false python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*" [[package]] name = "packaging" version = "23.2" description = "Core utilities for Python packages" category = "dev" optional = false python-versions = ">=3.7" [[package]] name = "pathspec" version = "0.12.1" description = "Utility library for gitignore style pattern matching of file paths." category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "platformdirs" version = "4.2.0" description = "A small Python package for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." category = "dev" optional = false python-versions = ">=3.8" [package.extras] docs = ["furo (>=2023.9.10)", "proselint (>=0.13)", "sphinx-autodoc-typehints (>=1.25.2)", "sphinx (>=7.2.6)"] test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest-cov (>=4.1)", "pytest-mock (>=3.12)", "pytest (>=7.4.3)"] [[package]] name = "pluggy" version = "1.4.0" description = "plugin and hook calling mechanisms for python" category = "dev" optional = false python-versions = ">=3.8" [package.extras] dev = ["pre-commit", "tox"] testing = ["pytest", "pytest-benchmark"] [[package]] name = "pre-commit" version = "3.6.1" description = "A framework for managing and maintaining multi-language pre-commit hooks." category = "dev" optional = false python-versions = ">=3.9" [package.dependencies] cfgv = ">=2.0.0" identify = ">=1.0.0" nodeenv = ">=0.11.1" pyyaml = ">=5.1" virtualenv = ">=20.10.0" [[package]] name = "pycodestyle" version = "2.11.1" description = "Python style guide checker" category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "pyflakes" version = "3.2.0" description = "passive checker of Python programs" category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "pymdown-extensions" version = "10.7.1" description = "Extension pack for Python Markdown." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] markdown = ">=3.5" pyyaml = "*" [package.extras] extra = ["pygments (>=2.12)"] [[package]] name = "pytest" version = "8.0.1" description = "pytest: simple powerful testing with Python" category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] colorama = {version = "*", markers = "sys_platform == \"win32\""} exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} iniconfig = "*" packaging = "*" pluggy = ">=1.3.0,<2.0" tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} [package.extras] testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] [[package]] name = "pytest-aiohttp" version = "1.0.5" description = "Pytest plugin for aiohttp support" category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] aiohttp = ">=3.8.1" pytest = ">=6.1.0" pytest-asyncio = ">=0.17.2" [package.extras] testing = ["coverage (==6.2)", "mypy (==0.931)"] [[package]] name = "pytest-asyncio" version = "0.23.5" description = "Pytest support for asyncio" category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] pytest = ">=7.0.0,<9" [package.extras] docs = ["sphinx (>=5.3)", "sphinx-rtd-theme (>=1.0)"] testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)"] [[package]] name = "pytest-cov" version = "5.0.0" description = "Pytest plugin for measuring coverage." category = "dev" optional = false python-versions = ">=3.8" [package.dependencies] coverage = {version = ">=5.2.1", extras = ["toml"]} pytest = ">=4.6" [package.extras] testing = ["fields", "hunter", "process-tests", "pytest-xdist", "virtualenv"] [[package]] name = "python-dateutil" version = "2.9.0.post0" description = "Extensions to the standard Python datetime module" category = "dev" optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" [package.dependencies] six = ">=1.5" [[package]] name = "pyyaml" version = "6.0.1" description = "YAML parser and emitter for Python" category = "dev" optional = false python-versions = ">=3.6" [[package]] name = "pyyaml-env-tag" version = "0.1" description = "A custom YAML tag for referencing environment variables in YAML files. " category = "dev" optional = false python-versions = ">=3.6" [package.dependencies] pyyaml = "*" [[package]] name = "requests" version = "2.31.0" description = "Python HTTP for Humans." category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] certifi = ">=2017.4.17" charset-normalizer = ">=2,<4" idna = ">=2.5,<4" urllib3 = ">=1.21.1,<3" [package.extras] socks = ["PySocks (>=1.5.6,!=1.5.7)"] use_chardet_on_py3 = ["chardet (>=3.0.2,<6)"] [[package]] name = "ruff" version = "0.2.1" description = "An extremely fast Python linter and code formatter, written in Rust." category = "dev" optional = false python-versions = ">=3.7" [[package]] name = "six" version = "1.16.0" description = "Python 2 and 3 compatibility utilities" category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" [[package]] name = "tomli" version = "2.0.1" description = "A lil' TOML parser" category = "dev" optional = false python-versions = ">=3.7" [[package]] name = "typing-extensions" version = "4.9.0" description = "Backported and Experimental Type Hints for Python 3.8+" category = "dev" optional = false python-versions = ">=3.8" [[package]] name = "urllib3" version = "2.2.1" description = "HTTP library with thread-safe connection pooling, file post, and more." category = "dev" optional = false python-versions = ">=3.8" [package.extras] brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] h2 = ["h2 (>=4,<5)"] socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] zstd = ["zstandard (>=0.18.0)"] [[package]] name = "virtualenv" version = "20.25.0" description = "Virtual Python Environment builder" category = "dev" optional = false python-versions = ">=3.7" [package.dependencies] distlib = ">=0.3.7,<1" filelock = ">=3.12.2,<4" platformdirs = ">=3.9.1,<5" [package.extras] docs = ["furo (>=2023.7.26)", "proselint (>=0.13)", "sphinx-argparse (>=0.4)", "sphinx (>=7.1.2)", "sphinxcontrib-towncrier (>=0.2.1a0)", "towncrier (>=23.6)"] test = ["covdefaults (>=2.3)", "coverage-enable-subprocess (>=1)", "coverage (>=7.2.7)", "flaky (>=3.7)", "packaging (>=23.1)", "pytest-env (>=0.8.2)", "pytest-freezer (>=0.4.8)", "pytest-mock (>=3.11.1)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)", "pytest (>=7.4)", "setuptools (>=68)", "time-machine (>=2.10)"] [[package]] name = "watchdog" version = "4.0.0" description = "Filesystem events monitoring" category = "dev" optional = false python-versions = ">=3.8" [package.extras] watchmedo = ["PyYAML (>=3.10)"] [[package]] name = "yarl" version = "1.9.4" description = "Yet another URL library" category = "main" optional = false python-versions = ">=3.7" [package.dependencies] idna = ">=2.0" multidict = ">=4.0" [metadata] lock-version = "1.1" python-versions = "^3.10" content-hash = "e0d6ad57977cd611de643f5ba67c2250eeafe58f53da2f451dff2f637a7215fd" [metadata.files] aiohttp = [] aioresponses = [] aiosignal = [] async-timeout = [] attrs = [] black = [] certifi = [] cfgv = [] charset-normalizer = [] click = [] codecov = [] colorama = [] coverage = [] debugpy = [] distlib = [] exceptiongroup = [] filelock = [] flake8 = [] frozenlist = [] ghp-import = [] griffe = [] identify = [] idna = [] iniconfig = [] jinja2 = [] markdown = [] markdown-include = [] markupsafe = [] mccabe = [] mergedeep = [] mkdocs = [] mkdocs-autorefs = [] mkdocstrings = [] mkdocstrings-python = [] multidict = [] mypy-extensions = [] nodeenv = [] packaging = [] pathspec = [] platformdirs = [] pluggy = [] pre-commit = [] pycodestyle = [] pyflakes = [] pymdown-extensions = [] pytest = [] pytest-aiohttp = [] pytest-asyncio = [] pytest-cov = [] python-dateutil = [] pyyaml = [] pyyaml-env-tag = [] requests = [] ruff = [] six = [ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, ] tomli = [] typing-extensions = [] urllib3 = [] virtualenv = [] watchdog = [] yarl = [] dio-chacon-wifi-api-1.2.2/pyproject.toml000066400000000000000000000026341500177420200201420ustar00rootroot00000000000000[tool.poetry] name = "dio-chacon-wifi-api" version = "1.2.2" description = "Python library for DIO Chacon wifi's protocol for shutters and switches" authors = ["cnico"] license = "GPL-3.0-or-later" readme = "README.md" homepage = "https://github.com/cnico/dio-chacon-wifi-api" repository = "https://github.com/cnico/dio-chacon-wifi-api" documentation = "https://dio-chacon-wifi-api.readthedocs.io" keywords = ["dio", "chacon", "shutter", "switch", "api"] classifiers = [ "Operating System :: OS Independent", "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", ] [tool.poetry.dependencies] python = "^3.10" aiohttp = "^3.9.3" [tool.poetry.dev-dependencies] pytest = "^8.0.0" pytest-asyncio = "^0.23.5" black = "^24.2.0" ruff = "^0.2.1" pre-commit = "^3.6.1" flake8 = "^7.0.0" debugpy = "^1.8.1" mkdocs = "^1.5.3" mkdocstrings = "^0.24.3" markdown-include = "^0.8.1" mkdocstrings-python = "^1.9.2" pytest-aiohttp = "^1.0.5" aioresponses = "^0.7.6" coverage = "^7.4.4" codecov = "^2.1.13" pytest-cov = "^5.0.0" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.pytest.ini_options] log_cli = true log_cli_level = "DEBUG" # Cf : https://laszlo.substack.com/p/cq4ds-python-project-from-scratch [tool.black] skip-string-normalization = true line-length = 120 [tool.ruff] # Same as Black. line-length = 120 [tool.flake8] max-line-length = 120 dio-chacon-wifi-api-1.2.2/src/000077500000000000000000000000001500177420200160105ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/000077500000000000000000000000001500177420200217455ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/__init__.py000066400000000000000000000001701500177420200240540ustar00rootroot00000000000000"""DIO Chacon API REST + websocket Client.""" from .client import DIOChaconAPIClient __all__ = ["DIOChaconAPIClient"] dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/client.py000066400000000000000000000374231500177420200236060ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Client for the DIO Chacon wifi API.""" import asyncio import logging from asyncio import Lock from asyncio import Queue from typing import Any from .const import DeviceTypeEnum from .const import DIOCHACON_WS_URL from .const import ShutterMoveEnum from .const import SwitchOnOffEnum from .exceptions import DIOChaconAPIError from .exceptions import DIOChaconInvalidAuthError from .session import DIOChaconClientSession _LOGGER = logging.getLogger(__name__) class DIOChaconAPIClient: """Client to the DIO Chacon wifi API. It is mainly a proxy to the chacon's cloud server. It manages authentication, the protocol through the websocket connection and server side callback events. """ def __init__( self, login_email: str, password: str, service_name: str = "python_generic", callback_device_state: callable = None, ) -> None: """Initialize the client API. Actually do nothing but storing informations. The effective authentication and connection are lazyly achieved. Parameters: login_email: string containing your email in DIO app password: string containing your password in DIO app service_name: arbitrary string identifying this client callback_device_state: the callback method that will be called for server side events """ self._login_email: str = login_email self._password: str = password self._service_name: str = service_name self._callback_device_state: callable = callback_device_state self._callback_device_state_by_device: dict[str, callable] = {} self._session: DIOChaconClientSession | None = None # Unique message id for request / response correlation self._id: int = 0 # Queue to await connection response from server self._messages_connection_queue: Queue = Queue() # Queue to await responses for queries self._messages_responses_queue: Queue = Queue() # In case of server responses concurrency, uses this buffer to find correct message id response. self._messages_buffer: dict = dict() # Lock to prevent initialisation of WS connection concurrently self._init_lock: Lock = Lock() self._ws_url: str = DIOCHACON_WS_URL def set_callback_device_state(self, callback_device_state: callable) -> None: """Register after the constructor the global callback method that will be called for server side events""" self._callback_device_state = callback_device_state def set_callback_device_state_by_device(self, target_id, callback_device_state: callable) -> None: """Register the per device callback method that will be called for server side events""" self._callback_device_state_by_device[target_id] = callback_device_state def _set_server_urls(self, ws_url: str) -> None: # Simple method to easily mock the server url. self._ws_url = ws_url async def _get_or_init_session(self) -> None: if self._session and self._session.is_disconnected(): _LOGGER.warning("You have been disconnected. Automatic reconnection...") self._session = None if self._session is None: async with self._init_lock: if self._session is None: _LOGGER.debug("Session creation via init_session") session = DIOChaconClientSession( self._login_email, self._password, self._service_name, self._message_received_callback ) # Stores session to be able to call disconnect whatever happens next (ok or ko auth) self._session = session session._set_server_urls(self._ws_url) await session.ws_connect() # Wait for the reception of the connection success message from the server. try: connection_message = await asyncio.wait_for(self._messages_connection_queue.get(), 10) self._messages_connection_queue.task_done() if ( "name" in connection_message and connection_message["name"] == "connection" and connection_message["action"] == "invalid" ): _LOGGER.debug("Invalid auth response received : %s", connection_message) raise DIOChaconInvalidAuthError("Invalid username/password.") # Do nothing of the connection successful message. except TimeoutError: _LOGGER.error("Error connecting to the server !") raise DIOChaconAPIError("No connection aknowledge message received from the server !") _LOGGER.debug("End of session creation via init_session") def _message_received_callback(self, data: Any) -> None: """The callback called whenever a server side message is received. Parameters: data: the message which is a from json converted dict. """ if "name" in data and data["name"] == "connection": # Sends the connection message (success or invalid) in the dedicated queue self._messages_connection_queue.put_nowait(data) return if "id" in data: # Sends the response message which has the same id has the request self._messages_responses_queue.put_nowait(data) return if "name" in data and data["name"] == "deviceState" and data["action"] == "update": # Sends the device state pushed from the server to the calling client # Sends only pertinent data : result = {} device_data = data["data"] result["id"] = device_data["di"] result["connected"] = device_data["rc"] == 1 for link in device_data["links"]: if link["rt"] == "oic.r.openlevel": result["openlevel"] = link["openLevel"] if link["rt"] == "oic.r.movement.linear": result["movement"] = link["movement"] if link["rt"] == "oic.r.switch.binary": result["is_on"] = link["value"] == SwitchOnOffEnum.ON.value sent = False if self._callback_device_state: _LOGGER.debug("Sending global callback event.") self._callback_device_state(result) sent = True if result["id"] in self._callback_device_state_by_device: _LOGGER.debug("Sending callback event for device %s", result["id"]) self._callback_device_state_by_device[result["id"]](result) sent = True if sent: return _LOGGER.warning("Unknown message received and dropped / no callback registered for this message : %s", data) def _get_next_id(self) -> int: self._id = self._id + 1 return self._id async def _consume_message_queue_and_cache_it(self) -> None: while not self._messages_responses_queue.empty(): data = await self._messages_responses_queue.get() msg_id: int = int(data["id"]) cached = self._messages_buffer.get(msg_id) if not cached: self._messages_buffer[msg_id] = data self._messages_responses_queue.task_done() async def _get_message_response_with_id(self, message_id: int) -> Any: await self._consume_message_queue_and_cache_it() cached = self._messages_buffer.get(message_id) # Try another after a small sleep if not cached: await asyncio.sleep(0.5) await self._consume_message_queue_and_cache_it() cached = self._messages_buffer.get(message_id) if not cached: _LOGGER.error("No response received for message id : %s", message_id) raise DIOChaconAPIError("Unexpected situation : no response with correct id !") # Remove value from cache has it is considered as consumed self._messages_buffer.pop(message_id) _LOGGER.debug("Messages buffer in memory cached size = %s", len(self._messages_buffer)) return cached async def _send_ws_message(self, method: str, path: str, parameters: Any) -> Any: req_id = self._get_next_id() # Constructs the message that will be formated in JSON by the DIOChaconClientSession object msg = {} msg["method"] = method msg["path"] = path msg["parameters"] = parameters msg["id"] = req_id _LOGGER.debug("WS request to send = %s", msg) await self._get_or_init_session() await self._session.ws_send_message(msg) raw_results = await self._get_message_response_with_id(req_id) _LOGGER.debug("WS response with result : %s", raw_results) if raw_results["status"] != 200: raise DIOChaconAPIError(f"Error during API call : {raw_results}") return raw_results async def disconnect(self) -> None: """Disconnects for the cloud server and properly closes the connection. It must be called at the of API usage or before python program ending. """ if self._session: # Close the web socket await self._session.disconnect() async def get_user_id(self) -> str: """Search for the user technical id based on its authentification elements. Returns: A string for the unique user id from the server. """ raw_results = await self._send_ws_message("GET", "/user", {}) return raw_results["data"]["id"] async def search_all_devices( self, device_type_to_search: list[DeviceTypeEnum] = None, with_state: bool = False ) -> dict: """Search all the known devices with their states : positions for shutters and on/off for switches Parameters: device_type_to_search: the device type to search for. None means to return all type (SHUTTERS and SWITCHES) with_state: True to return the detailed states like shutter position and switches on or off. Returns: A list of tuples composed of id, name, type, openlevel and movement for shutter, is_on for switches. """ raw_results = await self._send_ws_message("GET", "/device", {}) results = dict() ids = [] for device in raw_results["data"]: result = {} id = device["id"] type = device["type"] device_type = DeviceTypeEnum.from_dio_api(type) if device_type is not DeviceTypeEnum.UNKNOWN and ( not device_type_to_search or (device_type in device_type_to_search) ): ids.append(id) result["id"] = id result["name"] = device["name"] result["type"] = device_type.value # Converts type to our constant definition result["model"] = device["modelName"] + "_" + device["softwareVersion"] results[id] = result if with_state: details = await self.get_status_details(ids, device_infos=results) for id in ids: if id not in details: continue results[id]["connected"] = details[id]["connected"] if "openlevel" in details[id]: results[id]["openlevel"] = details[id]["openlevel"] results[id]["movement"] = details[id]["movement"] if "is_on" in details[id]: results[id]["is_on"] = details[id]["is_on"] return results async def get_status_details(self, ids: list, notifyCallback: bool = False, device_infos: dict = None) -> dict: """Retrieves the status detailed of devices ids given. Parameters: ids: the device ids to search details for. notifyCallback: True to notify the callback function par device. device_infos: the devices infos (name and model) for requested ids. Used only to produce a log. Returns: A list of tuples composed of id, connected ; openlevel and movement for shutter, is_on for switch. """ parameters = {"devices": ids} raw_results = await self._send_ws_message("POST", "/device/states", parameters) results = dict() for device_key in raw_results["data"]: device_data = raw_results["data"][device_key] result = {} result["id"] = device_key if device_data is None: # The server sends no data on the device but it exists (e.g with a very old firmware), # so we consider it as disconnected as the DIO App. name = device_infos[device_key]["name"] if device_infos else "Unknown" device_type = device_infos[device_key]["type"] if device_infos else "Unknown" model = device_infos[device_key]["model"] if device_infos else "Unknown" _LOGGER.warn( "The device '%s' ('%s', '%s', '%s') is not fully recognized. " "Probably because of a too old firmware.", name, model, device_type, device_key, ) result["connected"] = False result["openlevel"] = 0 result["movement"] = ShutterMoveEnum.STOP.value result["is_on"] = SwitchOnOffEnum.ON.value else: # Nominal case result["connected"] = device_data["rc"] == 1 for link in device_data["links"]: if link["rt"] == "oic.r.openlevel": result["openlevel"] = link["openLevel"] if link["rt"] == "oic.r.movement.linear": result["movement"] = link["movement"] if link["rt"] == "oic.r.switch.binary": result["is_on"] = link["value"] == SwitchOnOffEnum.ON.value results[device_key] = result # Send the update via the callback by device. if notifyCallback and device_key in self._callback_device_state_by_device: _LOGGER.debug("Sending callback status details for device %s", device_key) self._callback_device_state_by_device[device_key](result) return results async def move_shutter_direction(self, shutter_id: str, direction: ShutterMoveEnum) -> None: """Moves the given shutter in the given direction. Parameters: shutter_id: the device id defining the chosen shutter. direction: up, down or stop movement. """ parameters = {"movement": direction.value.lower()} await self._send_ws_message("POST", f"/device/{shutter_id}/action/mvtlinear", parameters) async def move_shutter_percentage(self, shutter_id: str, openlevel: int) -> None: """Moves the given shutter at a given position. Parameters: shutter_id: the device id defining the chosen shutter. openlevel: the open level percentage between 0 and 100. """ parameters = {"openLevel": openlevel} await self._send_ws_message("POST", f"/device/{shutter_id}/action/openlevel", parameters) async def switch_switch(self, switch_id: str, set_on: bool) -> None: """Switches on or off the given switch. Parameters: switch_id: the device id defining the chosen switch. set_on: on or off as desired state. """ val = SwitchOnOffEnum.ON.value if set_on else SwitchOnOffEnum.OFF.value parameters = {"value": val} await self._send_ws_message("POST", f"/device/{switch_id}/action/switch", parameters) dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/const.py000066400000000000000000000021001500177420200234360ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Consts for Dio Chacon wifi python client API.""" from enum import Enum DIOCHACON_WS_URL = "wss://l4hfront-prod.chacon.cloud/ws" class DeviceTypeEnum(Enum): def from_dio_api(label: str): dict_array = [ {'label': ".wifi.shutter.", 'code': "SHUTTER"}, {'label': ".wifi.genericSwitch.", 'code': "SWITCH_LIGHT"}, {'label': ".wifi.plug.", 'code': "SWITCH_PLUG"}, ] for d in dict_array: if d['label'] in label: return DeviceTypeEnum(d['code']) return DeviceTypeEnum.UNKNOWN def equals(self, other_label: str) -> bool: if DeviceTypeEnum.from_dio_api(other_label) == self: return True if other_label in [e.value for e in DeviceTypeEnum]: return True return False SHUTTER = "SHUTTER" SWITCH_LIGHT = "SWITCH_LIGHT" SWITCH_PLUG = "SWITCH_PLUG" UNKNOWN = "UNKNOWN" class ShutterMoveEnum(Enum): UP = "up" STOP = "stop" DOWN = "down" class SwitchOnOffEnum(Enum): ON = 1 OFF = 0 dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/exceptions.py000066400000000000000000000005271500177420200245040ustar00rootroot00000000000000"""Exceptions for DIOChacon API.""" class DIOChaconAPIError(Exception): """Error from this api.""" def __init__(self, *args) -> None: Exception.__init__(self, *args) class DIOChaconInvalidAuthError(Exception): """Invalid auth detected""" def __init__(self, *args) -> None: Exception.__init__(self, *args) dio-chacon-wifi-api-1.2.2/src/dio_chacon_wifi_api/session.py000066400000000000000000000146501500177420200240100ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Session manager for the DIO Chacon wifi API in order to maintain authentication token between calls. And context between the various websockets calls. Largely inspired by https://github.com/jjlawren/python-plexwebsocket/blob/master/plexwebsocket.py """ import asyncio import json import logging import urllib import aiohttp MAX_FAILED_ATTEMPTS = 5 STATE_CONNECTED = "connected" STATE_DISCONNECTED = "disconnected" STATE_STARTING = "starting" STATE_STOPPED = "stopped" _LOGGER = logging.getLogger(__name__) class DIOChaconClientSession: """HTTP session manager for DIO Chacon API. This session object allows to manage the authentication in the API using a token. """ _state: str = None _failed_attempts: int = 0 _aiohttp_session: aiohttp.ClientSession | None = None _websocket: aiohttp.ClientWebSocketResponse | None = None _listen_task: asyncio.Task | None = None def __init__(self, login_email: str, password: str, service_name: str, callback: callable) -> None: """Initialize and authenticate. Parameters: username: the dio chacon user (mainly the email to log in the app) password: the dio chacon user's password service_name: arbitrary string identifying the client callback (Runnable): Called when interesting events occur. Provides arguments: data (str): websocket payload contents deserialized from json """ self._login_email = login_email self._password = password self._service_name = service_name self._callback = callback async def on_request_start(session, trace_config_ctx, params): _LOGGER.debug(f"aiohttp request start : {params}") async def on_request_chunk_sent(session, trace_config_ctx, params): _LOGGER.debug(f"aiohttp request chunk sent : {params}") async def on_response_chunk_received(session, trace_config_ctx, params): _LOGGER.debug(f"aiohttp response chunk received : {params}") async def on_request_end(session, trace_config_ctx, params): _LOGGER.debug(f"aiohttp request end : {params}") trace_config = aiohttp.TraceConfig() trace_config.on_request_start.append(on_request_start) trace_config.on_request_end.append(on_request_end) trace_config.on_request_chunk_sent.append(on_request_chunk_sent) trace_config.on_response_chunk_received.append(on_response_chunk_received) self._aiohttp_session = aiohttp.ClientSession(trace_configs=[trace_config]) def _set_server_urls(self, ws_url: str) -> None: # Simple method to easily mock the server url by overriding default values. self._ws_url = ws_url async def ws_connect(self) -> None: """Make a connection to the server via websocket protocol.""" # Starts a background parallel task to permanently listen to events # sent by the WS server and transfer them via callback. self._listen_task = asyncio.create_task(self._listen()) async def _listen(self) -> None: """Listen to messages""" # Infinite loop to listen to messages on the websocket and manage retries. self._failed_attempts = 0 while self._state != STATE_STOPPED: await self._running() async def _running(self) -> None: url = ( self._ws_url + "?" + urllib.parse.urlencode( { 'email': self._login_email, 'password': self._password, 'serviceName': self._service_name, } ) ) self._state = STATE_STARTING try: async with self._aiohttp_session.ws_connect(url, heartbeat=15, autoping=True) as ws_client: self._state = STATE_CONNECTED self._failed_attempts = 0 self._websocket = ws_client async for message in ws_client: if self._state == STATE_STOPPED: break if message.type == aiohttp.WSMsgType.ERROR: _LOGGER.error("Error received from WS server: %s", message) break if message.type == aiohttp.WSMsgType.CLOSED: _LOGGER.warning("AIOHTTP websocket connection closed") break if message.type == aiohttp.WSMsgType.TEXT: _LOGGER.debug("Websocket received data %s", message) msg = message.json() self._callback(msg) except aiohttp.ClientResponseError as error: _LOGGER.error("Unexpected response received from server : %s", error) self._state = STATE_STOPPED except (aiohttp.ClientConnectionError, asyncio.TimeoutError) as error: if self._failed_attempts >= MAX_FAILED_ATTEMPTS: _LOGGER.error("Too many retries to reconnect to server. Please restart globally.") self._state = STATE_STOPPED elif self._state != STATE_STOPPED: retry_delay = min(2 ** (self._failed_attempts - 1) * 30, 300) self._failed_attempts += 1 _LOGGER.error("Websocket connection failed, retrying in %ds: %s", retry_delay, error) self._state = STATE_DISCONNECTED await asyncio.sleep(retry_delay) except Exception as error: if self._state != STATE_STOPPED: _LOGGER.exception("Unexpected exception occurred: %s", error) self._state = STATE_STOPPED async def disconnect(self) -> None: _LOGGER.debug("Disconnection of the current session") self._state = STATE_STOPPED if self._websocket: await self._websocket.close() if self._aiohttp_session: await self._aiohttp_session.close() # Let the _listen infinite loop terminate correctly with STATE_STOPPED signal. await asyncio.sleep(0.5) _LOGGER.debug("Disconnection done") async def ws_send_message(self, msg) -> None: """Sends a message in the websocket by converting it to json. Parameters: msg: the message to be sent """ await self._websocket.send_str(json.dumps(msg)) def is_disconnected(self) -> bool: return self._state == STATE_STOPPED or self._websocket.closed dio-chacon-wifi-api-1.2.2/tests/000077500000000000000000000000001500177420200163635ustar00rootroot00000000000000dio-chacon-wifi-api-1.2.2/tests/aiohttp_fake_server_utils.py000066400000000000000000000270231500177420200242050ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Http server mocking requests/responses for test_client.py. Inspired from : https://gist.github.com/ex3cv/2bbbbaf748c604fd737e1bb8372336e7 """ import asyncio import json import logging from asyncio import Queue from functools import partial import aiohttp from aiohttp import web _LOGGER = logging.getLogger(__name__) MOCK_PORT = 38080 INVALID_PASSWORD = "PASS_INVALID_AUTH" async def endpoint( request: web.Request, recording_queue: Queue, ) -> web.Response: _LOGGER.debug("MOCK server. Request received = %s", request) for_assertions = {} for_assertions["protocol"] = "HTTP" for_assertions["method"] = request.method for_assertions["rel_url"] = str(request.rel_url) for_assertions["body"] = str(await request.text()) # record request for future inspection await recording_queue.put(for_assertions) if str(request.rel_url).startswith("/api/session/login"): if INVALID_PASSWORD in (await request.text()): _LOGGER.debug("MOCK server. Response with fake invalid authentication") return web.json_response(body='{"status":400,"data":"Invalid username/password."}', status=200) else: _LOGGER.debug("MOCK server. Response with fake session token") return web.json_response(body='{"status":200,"data":{"sessionToken":"r:myfakesessionToken"}}', status=200) _LOGGER.debug("MOCK server. Response None") return None async def websocket_messages_handler(ws: aiohttp.web_ws.WebSocketResponse, recording_queue: Queue): async for msg in ws: _LOGGER.debug("MOCK Server WS : received message : %s", msg) if msg.type == aiohttp.WSMsgType.TEXT: content = json.loads(msg.data) path = content["path"] id = content["id"] for_assertions = {} for_assertions["protocol"] = "WS" for_assertions["method"] = content["method"] for_assertions["parameters"] = content["parameters"] for_assertions["path"] = path for_assertions["id"] = id # record request for future inspection await recording_queue.put(for_assertions) if path == "/user": response = {} response["id"] = id response["status"] = 200 response["data"] = {} response["data"]["id"] = "mocked-user-id" response["data"]["name"] = "mocked-user-name" _LOGGER.debug("MOCK Server WS : response /user to send. %s", response) await ws.send_str(json.dumps(response)) if path == "/device": response = {} response["id"] = id response["status"] = 200 response["data"] = list() # Add one shutter response["data"].append({}) response["data"][0]["id"] = "L4HActuator_idmock1" response["data"][0]["name"] = "Shutter mock 1" response["data"][0]["type"] = ".dio1.wifi.shutter.mvt_linear." response["data"][0]["modelName"] = "CERSwd-3B" response["data"][0]["softwareVersion"] = "1.0.6" # Add one switch response["data"].append({}) response["data"][1]["id"] = "L4HActuator_idmock2" response["data"][1]["name"] = "Shutter mock 2" response["data"][1]["type"] = ".dio1.wifi.genericSwitch.switch." response["data"][1]["modelName"] = "CERNwd-3B" response["data"][1]["softwareVersion"] = "1.0.4" # Add one unknown device response["data"].append({}) response["data"][2]["id"] = "L4HActuator_idmock3" response["data"][2]["name"] = "Shutter mock 3 unknown" response["data"][2]["type"] = ".dio1.camera.unknown" response["data"][2]["modelName"] = "CERNwd-3B" response["data"][2]["softwareVersion"] = "X.0.X" _LOGGER.debug("MOCK Server WS : response /device to send. %s", response) await ws.send_str(json.dumps(response)) if path == "/device/states": response = {} response["id"] = id response["status"] = 200 response["data"] = {} response["data"]["L4HActuator_idmock1"] = {} response["data"]["L4HActuator_idmock1"]["rc"] = 1 response["data"]["L4HActuator_idmock1"]["links"] = list() response["data"]["L4HActuator_idmock1"]["links"].append({}) response["data"]["L4HActuator_idmock1"]["links"][0]["rt"] = "oic.r.openlevel" response["data"]["L4HActuator_idmock1"]["links"][0]["openLevel"] = 75 response["data"]["L4HActuator_idmock1"]["links"].append({}) response["data"]["L4HActuator_idmock1"]["links"][1]["rt"] = "oic.r.movement.linear" response["data"]["L4HActuator_idmock1"]["links"][1]["movement"] = "stop" response["data"]["L4HActuator_idmock2"] = {} response["data"]["L4HActuator_idmock2"]["rc"] = 1 response["data"]["L4HActuator_idmock2"]["links"] = list() response["data"]["L4HActuator_idmock2"]["links"].append({}) response["data"]["L4HActuator_idmock2"]["links"][0]["rt"] = "oic.r.switch.binary" response["data"]["L4HActuator_idmock2"]["links"][0]["value"] = 0 _LOGGER.debug("MOCK Server WS : response /device/states to send. %s", response) await ws.send_str(json.dumps(response)) if path == "/device/L4HActuator_idmock1/action/mvtlinear": response = {} response["id"] = id response["status"] = 200 _LOGGER.debug( "MOCK Server WS : response /device/L4HActuator_idmock1/action/mvtlinear to send. %s", response ) await ws.send_str(json.dumps(response)) # simulates asynchronous send then send a status message for callback server side event async def coro_callback(): await asyncio.sleep(0.200) response = {} response["name"] = "deviceState" response["action"] = "update" response["data"] = {} response["data"]["di"] = "L4HActuator_idmock1" response["data"]["rc"] = 1 response["data"]["links"] = list() response["data"]["links"].append({}) response["data"]["links"][0]["rt"] = "oic.r.openlevel" response["data"]["links"][0]["openLevel"] = 69 response["data"]["links"].append({}) response["data"]["links"][1]["rt"] = "oic.r.movement.linear" response["data"]["links"][1]["movement"] = "down" _LOGGER.debug("MOCK Server WS : callback status to send. %s", response) await ws.send_str(json.dumps(response)) asyncio.create_task(coro_callback()) if path == "/device/L4HActuator_idmock1/action/openlevel": response = {} response["id"] = id response["status"] = 200 _LOGGER.debug( "MOCK Server WS : response /device/L4HActuator_idmock1/action/openlevel to send. %s", response ) await ws.send_str(json.dumps(response)) # simulates asynchronous send then send a status message for callback server side event async def coro_callback(): await asyncio.sleep(0.200) response = {} response["name"] = "deviceState" response["action"] = "update" response["data"] = {} response["data"]["di"] = "L4HActuator_idmock1" response["data"]["rc"] = 1 response["data"]["links"] = list() response["data"]["links"].append({}) response["data"]["links"][0]["rt"] = "oic.r.openlevel" response["data"]["links"][0]["openLevel"] = 69 response["data"]["links"].append({}) response["data"]["links"][1]["rt"] = "oic.r.movement.linear" response["data"]["links"][1]["movement"] = "down" _LOGGER.debug("MOCK Server WS : callback status to send. %s", response) await ws.send_str(json.dumps(response)) asyncio.create_task(coro_callback()) if path == "/device/L4HActuator_idmock2/action/switch": response = {} response["id"] = id response["status"] = 200 _LOGGER.debug( "MOCK Server WS : response /device/L4HActuator_idmock2/action/switch to send. %s", response ) await ws.send_str(json.dumps(response)) # simulates asynchronous send then send a status message for callback server side event async def coro_callback(): await asyncio.sleep(0.200) response = {} response["name"] = "deviceState" response["action"] = "update" response["data"] = {} response["data"]["di"] = "L4HActuator_idmock2" response["data"]["rc"] = 1 response["data"]["links"] = list() response["data"]["links"].append({}) response["data"]["links"][0]["rt"] = "oic.r.switch.binary" response["data"]["links"][0]["value"] = 1 _LOGGER.debug("MOCK Server WS : callback status to send. %s", response) await ws.send_str(json.dumps(response)) asyncio.create_task(coro_callback()) if path == "/session/logout": response = {} response["id"] = id response["status"] = 200 response["name"] = "disconnection" response["action"] = "success" await ws.send_str(json.dumps(response)) await ws.close() break _LOGGER.debug('MOCK Server WS : Websocket connection closed') async def websocket_handler(request: web.Request, recording_queue: Queue): _LOGGER.debug('MOCK Server WS : Websocket connection starting') ws = web.WebSocketResponse() await ws.prepare(request) _LOGGER.debug('MOCK Server WS : Websocket connection ready') if request.query.get("password") == INVALID_PASSWORD: _LOGGER.debug('MOCK Server WS : Sending invalid auth for connection failure') await ws.send_str('{"name":"connection","action":"invalid","data":""}') else: _LOGGER.debug('MOCK Server WS : Sending connection success') await ws.send_str('{"name":"connection","action":"success","data":""}') await asyncio.create_task(websocket_messages_handler(ws, recording_queue)) return ws async def run_fake_http_server(aiohttp_server, recording_queue: Queue) -> None: _LOGGER.debug("Starting Mock server...") app = web.Application() call = partial(endpoint, recording_queue=recording_queue) call_ws = partial(websocket_handler, recording_queue=recording_queue) app.add_routes([web.route("*", "/api/{tail:.*}", call), web.route("*", "/ws", call_ws)]) await aiohttp_server(app, port=MOCK_PORT) dio-chacon-wifi-api-1.2.2/tests/test_client.py000066400000000000000000000151501500177420200212540ustar00rootroot00000000000000# coding: utf-8 """Tests client.py. DIOChaconAPIClient class.""" import asyncio import logging from typing import Any import pytest from aiohttp_fake_server_utils import MOCK_PORT from aiohttp_fake_server_utils import run_fake_http_server from dio_chacon_wifi_api.client import DIOChaconAPIClient from dio_chacon_wifi_api.const import ShutterMoveEnum from dio_chacon_wifi_api.exceptions import DIOChaconInvalidAuthError _LOGGER = logging.getLogger(__name__) USERNAME = 'toto@toto.com' PASSWORD = 'DUMMY_PASS' SERVICE_NAME = "test_client" INVALID_PASSWORD = 'PASS_INVALID_AUTH' def log_callback(data: Any) -> None: _LOGGER.info("******** CALLBACK MESSAGE RECEIVED *******") _LOGGER.info(data) assert data["id"] _LOGGER.info("******** CALLBACK MESSAGE DONE *******") @pytest.mark.asyncio async def test_client_invalid_auth(aiohttp_server) -> None: """Test invalid auth exception for client giving bad credential.""" recording_queue: asyncio.Queue = asyncio.Queue() await run_fake_http_server(aiohttp_server, recording_queue) _LOGGER.debug("Launching test client...") with pytest.raises(DIOChaconInvalidAuthError) as excinfo: client = DIOChaconAPIClient(USERNAME, INVALID_PASSWORD, SERVICE_NAME) client.set_callback_device_state(log_callback) client._set_server_urls(f"ws://localhost:{MOCK_PORT}/ws") await client.get_user_id() assert str(excinfo.value) == "Invalid username/password." _LOGGER.debug("Invalid auth test OK. Disconnecting...") await client.disconnect() @pytest.mark.asyncio async def test_client(aiohttp_server) -> None: """Test generic for client.""" recording_queue: asyncio.Queue = asyncio.Queue() await run_fake_http_server(aiohttp_server, recording_queue) _LOGGER.debug("Launching test client...") client = DIOChaconAPIClient(USERNAME, PASSWORD, SERVICE_NAME) client.set_callback_device_state(log_callback) client._set_server_urls(f"ws://localhost:{MOCK_PORT}/ws") # Test get_user_id effective_response = await client.get_user_id() _LOGGER.debug("Assertion queue size = %s", recording_queue.qsize()) effective_request = await asyncio.wait_for(recording_queue.get(), 2) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "GET" assert effective_request["path"] == "/user" assert effective_request["parameters"] == {} assert effective_request["id"] == 1 assert effective_response == "mocked-user-id" recording_queue.task_done() # Test search_all_devices effective_response = await client.search_all_devices(with_state=True) effective_request = await asyncio.wait_for(recording_queue.get(), 2) _LOGGER.debug("Request : %s .Response : %s", effective_request, effective_response) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "GET" assert effective_request["path"] == "/device" assert effective_request["parameters"] == {} assert effective_request["id"] == 2 recording_queue.task_done() effective_request = await asyncio.wait_for(recording_queue.get(), 2) _LOGGER.debug("Intermediairay WS Request : %s", effective_request) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "POST" assert effective_request["path"] == "/device/states" assert effective_request["parameters"] == {'devices': ['L4HActuator_idmock1', 'L4HActuator_idmock2']} assert effective_request["id"] == 3 recording_queue.task_done() assert len(effective_response) == 2 assert effective_response["L4HActuator_idmock1"]["id"] == "L4HActuator_idmock1" assert effective_response["L4HActuator_idmock1"]["name"] == "Shutter mock 1" assert effective_response["L4HActuator_idmock1"]["type"] == "SHUTTER" assert effective_response["L4HActuator_idmock1"]["model"] == "CERSwd-3B_1.0.6" assert effective_response["L4HActuator_idmock1"]["connected"] # == True assert effective_response["L4HActuator_idmock1"]["openlevel"] == 75 assert effective_response["L4HActuator_idmock1"]["movement"] == "stop" assert effective_response["L4HActuator_idmock2"]["id"] == "L4HActuator_idmock2" assert effective_response["L4HActuator_idmock2"]["name"] == "Shutter mock 2" assert effective_response["L4HActuator_idmock2"]["type"] == "SWITCH_LIGHT" assert effective_response["L4HActuator_idmock2"]["model"] == "CERNwd-3B_1.0.4" assert effective_response["L4HActuator_idmock2"]["connected"] # == True assert not effective_response["L4HActuator_idmock2"]["is_on"] # == False # Device 3 is unknown so not in the response since it is filtered by the client. # Test move_shutter_direction await client.move_shutter_direction(shutter_id="L4HActuator_idmock1", direction=ShutterMoveEnum.DOWN) effective_request = await asyncio.wait_for(recording_queue.get(), 2) _LOGGER.debug("Request : %s", effective_request) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "POST" assert effective_request["path"] == "/device/L4HActuator_idmock1/action/mvtlinear" assert effective_request["parameters"] == {'movement': "down"} assert effective_request["id"] == 4 recording_queue.task_done() # Returns is also done via a callback # Test move_shutter_percentage await client.move_shutter_percentage(shutter_id="L4HActuator_idmock1", openlevel=31) effective_request = await asyncio.wait_for(recording_queue.get(), 2) _LOGGER.debug("Request : %s", effective_request) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "POST" assert effective_request["path"] == "/device/L4HActuator_idmock1/action/openlevel" assert effective_request["parameters"] == {'openLevel': 31} assert effective_request["id"] == 5 recording_queue.task_done() # Returns is also done via a callback # Test switch_switch await client.switch_switch(switch_id="L4HActuator_idmock2", set_on=True) effective_request = await asyncio.wait_for(recording_queue.get(), 2) _LOGGER.debug("Request : %s", effective_request) assert effective_request["protocol"] == "WS" assert effective_request["method"] == "POST" assert effective_request["path"] == "/device/L4HActuator_idmock2/action/switch" assert effective_request["parameters"] == {'value': 1} assert effective_request["id"] == 6 recording_queue.task_done() # Returns is also done via a callback # Explicitly awaits that the callbacks are executed by the fake server before disconnecting. _LOGGER.debug("Waiting for callbacks executions...") await asyncio.sleep(0.500) await client.disconnect() dio-chacon-wifi-api-1.2.2/tests/test_const.py000066400000000000000000000014631500177420200211260ustar00rootroot00000000000000# coding: utf-8 """Tests consts.""" from dio_chacon_wifi_api.const import DeviceTypeEnum def test_enum() -> None: """Test DeviceTypeEnum.""" assert DeviceTypeEnum.from_dio_api(".dio1.wifi.genericSwitch.switch.").value == "SWITCH_LIGHT" assert DeviceTypeEnum.SWITCH_LIGHT != DeviceTypeEnum.SHUTTER assert DeviceTypeEnum.SWITCH_LIGHT.equals(".dio1.wifi.genericSwitch.switch.") assert DeviceTypeEnum.SWITCH_LIGHT.equals("SWITCH_LIGHT") assert not DeviceTypeEnum.SWITCH_LIGHT.equals("toto") assert DeviceTypeEnum("SWITCH_PLUG") in [DeviceTypeEnum.SWITCH_LIGHT, DeviceTypeEnum.SWITCH_PLUG] assert "SWITCH_PLUG" not in [DeviceTypeEnum.SWITCH_LIGHT, DeviceTypeEnum.SWITCH_PLUG] # ValueError : assert DeviceTypeEnum("toto") not in [DeviceTypeEnum.SWITCH_LIGHT, DeviceTypeEnum.SWITCH_PLUG] dio-chacon-wifi-api-1.2.2/tests/test_exception.py000066400000000000000000000006411500177420200217730ustar00rootroot00000000000000# coding: utf-8 """Tests exceptions.""" import pytest from dio_chacon_wifi_api.exceptions import DIOChaconAPIError from dio_chacon_wifi_api.exceptions import DIOChaconInvalidAuthError def test_exceptions() -> None: with pytest.raises(DIOChaconAPIError): raise DIOChaconAPIError("Dumb test coverage") with pytest.raises(DIOChaconInvalidAuthError): raise DIOChaconInvalidAuthError("Dumb 2") dio-chacon-wifi-api-1.2.2/tests/test_integrations_shutter.py000066400000000000000000000053351500177420200242660ustar00rootroot00000000000000# coding: utf-8 """Integration tests for DIO Chacon wifi api.""" import asyncio import logging import os from typing import Any import pytest from dio_chacon_wifi_api import DIOChaconAPIClient from dio_chacon_wifi_api.const import DeviceTypeEnum from dio_chacon_wifi_api.const import ShutterMoveEnum # Enter correct real values here for the tests to complete successfully with real Server calls. USERNAME = os.environ.get('DIO_USERNAME') PASSWORD = os.environ.get('DIO_PASSWORD') MY_SHUTTER_ID = os.environ.get('DIO_SHUTTER_ID_TEST') logging.basicConfig(level=logging.DEBUG) _LOGGER = logging.getLogger(__name__) if os.environ.get('PYDBG', None): # This code will block execution until you run your Python: Remote Attach port = 5678 host = 'localhost' print(f"Blocking for remote attach for vscode {host} {port}") import debugpy debugpy.listen((host, port)) debugpy.wait_for_client() @pytest.mark.skip("Not an automated test but an example of usage with real values.") @pytest.mark.asyncio async def test_integration_simple() -> None: """Connect then lists all the devices.""" assert USERNAME is not None, "Please set env var before running integration tests !" def log_callback(data: Any) -> None: _LOGGER.info("******** CALLBACK MESSAGE RECEIVED *******") _LOGGER.info(data) _LOGGER.info("******** CALLBACK MESSAGE DONE *******") # Init client client = DIOChaconAPIClient(USERNAME, PASSWORD, callback_device_state=log_callback) user_id = await client.get_user_id() _LOGGER.info(f"User Id retrieved : {user_id}") list_devices = await client.search_all_devices(device_type_to_search=[DeviceTypeEnum.SHUTTER], with_state=False) _LOGGER.info(f"Devices found : {list_devices}") my_device = list_devices[MY_SHUTTER_ID] _LOGGER.info(f"My device found {MY_SHUTTER_ID} : {my_device}") assert my_device['name'] == 'Test' assert my_device['type'] == DeviceTypeEnum.SHUTTER.value # get shutter position list_pos = await client.get_status_details([MY_SHUTTER_ID]) _LOGGER.info(f"Positions found : {list_pos}") _LOGGER.info("---------- Moving UP ---------") await client.move_shutter_direction(MY_SHUTTER_ID, ShutterMoveEnum.UP) await asyncio.sleep(10) list_pos = await client.get_status_details([MY_SHUTTER_ID]) _LOGGER.info(f"Positions found after move UP: {list_pos}") _LOGGER.info("---------- Moving 75% ---------") await client.move_shutter_percentage(MY_SHUTTER_ID, 75) await asyncio.sleep(10) list_pos = await client.get_status_details([MY_SHUTTER_ID]) _LOGGER.info(f"Positions found after move 75%: {list_pos}") _LOGGER.info("End of integration tests : deconnecting...") await client.disconnect() dio-chacon-wifi-api-1.2.2/tests/test_integrations_switch.py000066400000000000000000000051541500177420200240700ustar00rootroot00000000000000# coding: utf-8 """Integration tests for DIO Chacon wifi api.""" import asyncio import logging import os from typing import Any import pytest from dio_chacon_wifi_api import DIOChaconAPIClient from dio_chacon_wifi_api.const import DeviceTypeEnum # Enter correct real values here for the tests to complete successfully with real Server calls. USERNAME = os.environ.get('DIO_USERNAME') PASSWORD = os.environ.get('DIO_PASSWORD') MY_SWITCH_ID = os.environ.get('DIO_SHUTTER_ID_TEST_SWITCH') logging.basicConfig(level=logging.DEBUG) _LOGGER = logging.getLogger(__name__) if os.environ.get('PYDBG', None): # This code will block execution until you run your Python: Remote Attach port = 5678 host = 'localhost' print(f"Blocking for remote attach for vscode {host} {port}") import debugpy debugpy.listen((host, port)) debugpy.wait_for_client() @pytest.mark.skip("Not an automated test but an example of usage with real values.") @pytest.mark.asyncio async def test_integration_simple() -> None: """Connect then lists all the devices.""" assert USERNAME is not None, "Please set env var before running integration tests !" def log_callback(data: Any) -> None: _LOGGER.info("******** CALLBACK MESSAGE RECEIVED *******") _LOGGER.info(data) _LOGGER.info("******** CALLBACK MESSAGE DONE *******") # Init client client = DIOChaconAPIClient(USERNAME, PASSWORD, callback_device_state=log_callback) user_id = await client.get_user_id() _LOGGER.info(f"User Id retrieved : {user_id}") list_devices = await client.search_all_devices(device_type_to_search=[DeviceTypeEnum.SWITCH_LIGHT], with_state=True) _LOGGER.info(f"Devices found : {list_devices}") my_device = list_devices[MY_SWITCH_ID] _LOGGER.info(f"My device found {MY_SWITCH_ID} : {my_device}") assert my_device['name'] == 'Lumiere Test' assert my_device['type'] == DeviceTypeEnum.SWITCH_LIGHT.value # get shutter position list_details = await client.get_status_details([MY_SWITCH_ID]) _LOGGER.info(f"Details found : {list_details}") _LOGGER.info("---------- Switch On ---------") await client.switch_switch(MY_SWITCH_ID, True) await asyncio.sleep(5) list_details = await client.get_status_details([MY_SWITCH_ID]) _LOGGER.info(f"Details after swith on: {list_details}") await client.switch_switch(MY_SWITCH_ID, False) await asyncio.sleep(5) list_details = await client.get_status_details([MY_SWITCH_ID]) _LOGGER.info(f"Details after swith off: {list_details}") _LOGGER.info("End of integration tests : disconnecting...") await client.disconnect() dio-chacon-wifi-api-1.2.2/tests/test_session.py000066400000000000000000000025541500177420200214650ustar00rootroot00000000000000# coding: utf-8 """Tests session.py. DIOChaconClientSession class.""" import asyncio import logging from typing import Any import pytest from aiohttp_fake_server_utils import MOCK_PORT from aiohttp_fake_server_utils import run_fake_http_server from dio_chacon_wifi_api.session import DIOChaconClientSession _LOGGER = logging.getLogger(__name__) USERNAME = 'toto@toto.com' PASSWORD = 'DUMMY_PASS' SERVICE_NAME = "test_client" @pytest.mark.asyncio async def test_session(aiohttp_server) -> None: """Test generic for session.""" recording_queue: asyncio.Queue = asyncio.Queue() message_queue: asyncio.Queue = asyncio.Queue() await run_fake_http_server(aiohttp_server, recording_queue) _LOGGER.debug("Launching test session...") def message_callback(data: Any) -> None: _LOGGER.info("******** CALLBACK MESSAGE RECEIVED *******") _LOGGER.info(data) _LOGGER.info("******** CALLBACK MESSAGE DONE *******") message_queue.put_nowait(data) session = DIOChaconClientSession(USERNAME, PASSWORD, SERVICE_NAME, message_callback) session._set_server_urls(f"ws://localhost:{MOCK_PORT}/ws") await session.ws_connect() message = await asyncio.wait_for(message_queue.get(), 2) assert message["name"] == 'connection' assert message["action"] == 'success' message_queue.task_done() await session.disconnect()