Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
system:homeautomation:home-assistant
python-zigpy-zigate
_service:obs_scm:zigpy-zigate-0.12.0.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:zigpy-zigate-0.12.0.obscpio of Package python-zigpy-zigate
07070100000000000081A4000000000000000000000001655B78D20000001C000000000000000000000000000000000000002000000000zigpy-zigate-0.12.0/.coveragerc[run] source = zigpy_zigate 07070100000001000041ED000000000000000000000003655B78D200000000000000000000000000000000000000000000001C00000000zigpy-zigate-0.12.0/.github07070100000002000041ED000000000000000000000003655B78D200000000000000000000000000000000000000000000002600000000zigpy-zigate-0.12.0/.github/workflows07070100000003000081A4000000000000000000000001655B78D200000155000000000000000000000000000000000000002D00000000zigpy-zigate-0.12.0/.github/workflows/ci.ymlname: CI # yamllint disable-line rule:truthy on: push: pull_request: ~ jobs: shared-ci: uses: zigpy/workflows/.github/workflows/ci.yml@main with: CODE_FOLDER: zigpy_zigate CACHE_VERSION: 2 PYTHON_VERSION_DEFAULT: 3.8.14 PRE_COMMIT_CACHE_PATH: ~/.cache/pre-commit MINIMUM_COVERAGE_PERCENTAGE: 4607070100000004000041ED000000000000000000000002655B78D200000000000000000000000000000000000000000000002F00000000zigpy-zigate-0.12.0/.github/workflows/matchers07070100000005000081A4000000000000000000000001655B78D200000100000000000000000000000000000000000000003E00000000zigpy-zigate-0.12.0/.github/workflows/matchers/codespell.json{ "problemMatcher": [ { "owner": "codespell", "severity": "warning", "pattern": [ { "regexp": "^(.+):(\\d+):\\s(.+)$", "file": 1, "line": 2, "message": 3 } ] } ] } 07070100000006000081A4000000000000000000000001655B78D200000241000000000000000000000000000000000000003B00000000zigpy-zigate-0.12.0/.github/workflows/matchers/flake8.json{ "problemMatcher": [ { "owner": "flake8-error", "severity": "error", "pattern": [ { "regexp": "^(.*):(\\d+):(\\d+):\\s([EF]\\d{3}\\s.*)$", "file": 1, "line": 2, "column": 3, "message": 4 } ] }, { "owner": "flake8-warning", "severity": "warning", "pattern": [ { "regexp": "^(.*):(\\d+):(\\d+):\\s([CDNW]\\d{3}\\s.*)$", "file": 1, "line": 2, "column": 3, "message": 4 } ] } ] } 07070100000007000081A4000000000000000000000001655B78D200000150000000000000000000000000000000000000003B00000000zigpy-zigate-0.12.0/.github/workflows/matchers/python.json{ "problemMatcher": [ { "owner": "python", "pattern": [ { "regexp": "^\\s*File\\s\\\"(.*)\\\",\\sline\\s(\\d+),\\sin\\s(.*)$", "file": 1, "line": 2 }, { "regexp": "^\\s*raise\\s(.*)\\(\\'(.*)\\'\\)$", "message": 2 } ] } ] } 07070100000008000081A4000000000000000000000001655B78D2000000F2000000000000000000000000000000000000003A00000000zigpy-zigate-0.12.0/.github/workflows/publish-to-pypi.ymlname: Publish distributions to PyPI on: release: types: - published jobs: shared-build-and-publish: uses: zigpy/workflows/.github/workflows/publish-to-pypi.yml@main secrets: PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} 07070100000009000081A4000000000000000000000001655B78D200000367000000000000000000000000000000000000001F00000000zigpy-zigate-0.12.0/.gitignore# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache coverage.xml *,cover .pytest_cache/ # Translations *.mo *.pot # Sphinx documentation docs/_build/ # PyBuilder target/ # pyenv .python-version # dotenv .env # virtualenv .venv/ venv/ ENV/ # Editor temp files .*.swp # Visual Studio Code .vscode /.project /.pydevproject /build_upload.sh 0707010000000A000081A4000000000000000000000001655B78D200000414000000000000000000000000000000000000002C00000000zigpy-zigate-0.12.0/.pre-commit-config.yamlrepos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: debug-statements - repo: https://github.com/psf/black rev: 23.10.1 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 entry: pflake8 additional_dependencies: - pyproject-flake8==6.1.0 - flake8-bugbear==23.1.20 - flake8-comprehensions==3.10.1 - flake8_2020==1.7.0 - mccabe==0.7.0 - pycodestyle==2.11.1 - pyflakes==3.1.0 - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.6.1 hooks: - id: mypy additional_dependencies: - zigpy - types-setuptools - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade - repo: https://github.com/fsouza/autoflake8 rev: v0.4.1 hooks: - id: autoflake8 0707010000000B000081A4000000000000000000000001655B78D200000297000000000000000000000000000000000000001C00000000zigpy-zigate-0.12.0/COPYINGzigpy-zigate Copyright (C) 2018 Sébastien RAMAGE 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 <http://www.gnu.org/licenses/>. 0707010000000C000081A4000000000000000000000001655B78D200000097000000000000000000000000000000000000002400000000zigpy-zigate-0.12.0/Contributors.md# Contributors - [Sébastien RAMAGE] (https://github.com/doudz) - [Alexei Chetroi] (https://github.com/Adminiuga) - [Hedda] (https://github.com/Hedda) 0707010000000D000081A4000000000000000000000001655B78D20000894B000000000000000000000000000000000000001C00000000zigpy-zigate-0.12.0/LICENSE GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. 0707010000000E000081A4000000000000000000000001655B78D200002C7B000000000000000000000000000000000000001E00000000zigpy-zigate-0.12.0/README.md# zigpy-zigate ![Build & Tests](https://github.com/zigpy/zigpy-zigate/workflows/Build%20&%20Tests/badge.svg?branch=master) [![Coverage](https://coveralls.io/repos/github/zigpy/zigpy-zigate/badge.svg?branch=master)](https://coveralls.io/github/zigpy/zigpy-zigate?branch=master) [zigpy-zigate](https://github.com/zigpy/zigpy-zigate) is a Python 3 implementation for the [Zigpy](https://github.com/zigpy/) project to implement [ZiGate](https://www.zigate.fr/) based [Zigbee](https://www.zigbee.org) radio devices. - https://github.com/zigpy/zigpy-zigate ZiGate is a open source ZigBee adapter hardware that was initially launched on Kickstarter by @fairecasoimeme - https://www.zigate.fr - https://www.kickstarter.com/projects/1361563794/zigate-universal-zigbee-gateway-for-smarthome ## Hardware and firmware compatibility The ZiGate USB adapter communicates via a PL-2303HX USB to Serial Bridge Controller module by Prolific. There's also a Wi-Fi adapter to communicate with ZiGate over network. Note! ZiGate open source ZigBee USB and GPIO adapter hardware requires ZiGate 3.1a firmware or later to work with this zigpy-zigate module, however ZiGate 3.1d firmware or later is recommended as it contains a specific bug-fix related to zigpy. See all available official ZiGate firmware releases [here (link)](https://github.com/fairecasoimeme/ZiGate/releases). ### Known working ZiGate compatible Zigbee radio modules - [ZiGate + USB / ZiGate USB-TTL](https://zigate.fr/produit/zigate-USB/) - [ZiGate + USB-DIN / ZiGate USB-DIN](https://zigate.fr/produit/zigatev2-usb-din/) - [PiZiGate + / PiZiGate (ZiGate HAT/Shield module for Raspberry Pi compatible GPIO header)](https://zigate.fr/produit/pizigatev2/) - Tip! PiZiGate are not limited to Raspberry Pi series as works with all computers with a Raspberry Pi compatible GPIO header. - [ZiGate Ethernet (ZiGate Ethernet serial-to-IP server)](https://zigate.fr/produit/zigate-ethernet/) (Note! Requires the [PiZiGate + radio module](https://zigate.fr/produit/pizigatev2/)) - Tip! [ZiGate Ethernet](https://zigate.fr/produit/zigate-ethernet/) can as alternativly also be used via [ESPHome serial bridge firmware for ESP32](https://github.com/thegroove/esphome-zbbridge/) as an option. - [ZiGate + WiFi Pack / ZiGate WiFi Pack (ZiGate WiFi serial-to-IP server)](https://zigate.fr/produit/zigatev2-pack-wifi/) - Tip! [ZiGate compatible WiFi module](https://zigate.fr/produit/module-wifi-v1-3-compatible-zigate/) can also be used to convert radio board from [ZiGate USB-TTL](https://zigate.fr/produit/zigate-ttl/) into this "ZiGate WiFi Pack". ### Experimental ZiGate compatible Zigbee radio modules - [Open Lumi Gateway](https://github.com/openlumi) - [DIY ZiGate WiFi bridge hacked from an Xiaomi Lumi Gateway with modded OpenWRT firmware](https://github.com/zigpy/zigpy-zigate/issues/59) ## Port configuration - To configure __usb__ ZiGate (USB TTL or DIN) port, just specify the port, example : `/dev/ttyUSB0` - Alternatively you could manually set port to `auto` to enable automatic usb port discovery - To configure __pizigate__ port, specify the port, example : `/dev/serial0` or `/dev/ttyAMA0` - To configure __wifi__ ZiGate, manually specify IP address and port, example : `socket://192.168.1.10:9999` __pizigate__ does require some additional adjustements on Raspberry Pi 3/Zero, and 4: - [Raspberry Pi 3 and Raspberry Pi Zero configuration adjustements](https://zigate.fr/documentation/compatibilite-raspberry-pi-3-et-zero-w/) - [Raspberry Pi 4 configuration adjustements](https://zigate.fr/documentation/compatibilite-raspberry-pi-4-b/) ## Flasher (ZiGate Firmware Tool) zigpy-zigate has an integrated Python "flasher" tool to flash firmware updates on your ZiGate (NXP Jennic JN5168). Thanks to Sander Hoentjen (tjikkun) zigpy-zigate now has an integrated firmware flasher tool! - [tjikkun original zigate-flasher repo](https://github.com/tjikkun/zigate-flasher) See all available official ZiGate firmware releases [here (link)](https://github.com/fairecasoimeme/ZiGate/releases). ### Flasher Usage ```bash usage: python3 -m zigpy_zigate.tools.flasher [-h] -p {/dev/ttyUSB0} [-w WRITE] [-s SAVE] [-u] [-d] [--gpio] [--din] optional arguments: -h, --help show this help message and exit -p {/dev/ttyUSB0}, --serialport {/dev/ttyUSB0} Serial port, e.g. /dev/ttyUSB0 -w WRITE, --write WRITE Firmware bin to flash onto the chip -s SAVE, --save SAVE File to save the currently loaded firmware to -u, --upgrade Download and flash the lastest available firmware -d, --debug Set log level to DEBUG --gpio Configure GPIO for PiZiGate flash --din Configure USB for ZiGate DIN flash ``` ## Testing new releases Testing a new release of the zigpy-zigate library before it is released in Home Assistant. If you are using Supervised Home Assistant (formerly known as the Hassio/Hass.io distro): - Add https://github.com/home-assistant/hassio-addons-development as "add-on" repository - Install "Custom deps deployment" addon - Update config like: ``` pypi: - zigpy-zigate==0.5.1 apk: [] ``` where 0.5.1 is the new version - Start the addon If you are instead using some custom python installation of Home Assistant then do this: - Activate your python virtual env - Update package with ``pip`` ``` pip install zigpy-zigate==0.5.1 ## Releases via PyPI Tagged versions are also released via PyPI - https://pypi.org/project/zigpy-zigate/ - https://pypi.org/project/zigpy-zigate/#history - https://pypi.org/project/zigpy-zigate/#files ## Developer references Documents that layout the serial protocol used for ZiGate serial interface communication can be found here: - https://github.com/fairecasoimeme/ZiGate/tree/master/Protocol - https://github.com/doudz/zigate - https://github.com/Neonox31/zigate - https://github.com/nouknouk/node-zigate ## How to contribute If you are looking to make a contribution to this project we suggest that you follow the steps in these guides: - https://github.com/firstcontributions/first-contributions/blob/master/README.md - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md Some developers might also be interested in receiving donations in the form of hardware such as Zigbee modules or devices, and even if such donations are most often donated with no strings attached it could in many cases help the developers motivation and indirect improve the development of this project. ## Related projects #### Zigpy [Zigpy](https://github.com/zigpy/zigpy) is [Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee) integration project to implement the [Zigbee Home Automation](https://www.zigbee.org/) standard as a Python 3 library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee based devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g., motion and door sensors), sensors (e.g., temperature sensors), lightbulbs, switches, and fans. A working implementation of zigbe exist in [Home Assistant](https://www.home-assistant.io) (Python based open source home automation software) as part of its [ZHA component](https://www.home-assistant.io/components/zha/) #### ZHA Device Handlers ZHA deviation handling in Home Assistant relies on the third-party [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) project. Zigbee devices that deviate from or do not fully conform to the standard specifications set by the [Zigbee Alliance](https://www.zigbee.org) may require the development of custom [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) (ZHA custom quirks handler implementation) to for all their functions to work properly with the ZHA component in Home Assistant. These ZHA Device Handlers for Home Assistant can thus be used to parse custom messages to and from non-compliant Zigbee devices. The custom quirks implementations for zigpy implemented as ZHA Device Handlers for Home Assistant are a similar concept to that of [Hub-connected Device Handlers for the SmartThings platform](https://docs.smartthings.com/en/latest/device-type-developers-guide/) as well as that of [zigbee-herdsman converters as used by Zigbee2mqtt](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html), meaning they are each virtual representations of a physical device that expose additional functionality that is not provided out-of-the-box by the existing integration between these platforms. #### ZHA integration component for Home Assistant [ZHA integration component for Home Assistant](https://www.home-assistant.io/integrations/zha/) is a reference implementation of the zigpy library as integrated into the core of [Home Assistant](https://www.home-assistant.io) (a Python based open source home automation software). There are also other GUI and non-GUI projects for Home Assistant's ZHA components which builds on or depends on its features and functions to enhance or improve its user-experience, some of those are listed and linked below. #### ZHA Custom Radios [zha-custom-radios](https://github.com/zha-ng/zha-custom-radios) adds support for custom radio modules for zigpy to [[Home Assistant's ZHA (Zigbee Home Automation) integration component]](https://www.home-assistant.io/integrations/zha/). This custom component for Home Assistant allows users to test out new modules for zigpy in Home Assistant's ZHA integration component before they are integrated into zigpy ZHA and also helps developers new zigpy radio modules without having to modify the Home Assistant's source code. #### ZHA Custom [zha_custom](https://github.com/Adminiuga/zha_custom) is a custom component package for Home Assistant (with its ZHA component for zigpy integration) that acts as zigpy commands service wrapper, when installed it allows you to enter custom commands via to zigy to example change advanced configuration and settings that are not available in the UI. #### ZHA Map [zha-map](https://github.com/zha-ng/zha-map) for Home Assistant's ZHA component can build a Zigbee network topology map. #### ZHA Network Visualization Card [zha-network-visualization-card](https://github.com/dmulcahey/zha-network-visualization-card) is a custom Lovelace element for Home Assistant which visualize the Zigbee network for the ZHA component. #### ZHA Network Card [zha-network-card](https://github.com/dmulcahey/zha-network-card) is a custom Lovelace card for Home Assistant that displays ZHA component Zigbee network and device information in Home Assistant #### Zigzag [Zigzag](https://github.com/Samantha-uk/zigzag) is an custom card/panel for [Home Assistant](https://www.home-assistant.io/) that displays a graphical layout of Zigbee devices and the connections between them. Zigzag can be installed as a panel or a custom card and relies on the data provided by the [zha-map](https://github.com/zha-ng/zha-map) integration commponent. #### ZHA Device Exporter [zha-device-exporter](https://github.com/dmulcahey/zha-device-exporter) is a custom component for Home Assistant to allow the ZHA component to export lists of Zigbee devices. 0707010000000F000081A4000000000000000000000001655B78D20000069A000000000000000000000000000000000000002300000000zigpy-zigate-0.12.0/pyproject.toml[build-system] requires = ["setuptools>=61.0.0", "wheel", "setuptools-git-versioning<2"] build-backend = "setuptools.build_meta" [project] name = "zigpy-zigate" dynamic = ["version"] description = "A library which communicates with ZiGate radios for zigpy" urls = {repository = "https://github.com/zigpy/zigpy-zigate"} authors = [ {name = "Sébastien RAMAGE", email = "sebatien.ramage@gmail.com"} ] readme = "README.md" license = {text = "GPL-3.0"} requires-python = ">=3.8" dependencies = [ "voluptuous", "zigpy>=0.60.0", "pyusb>=1.1.0", "gpiozero", 'async-timeout; python_version<"3.11"', ] [tool.setuptools.packages.find] exclude = ["tests", "tests.*"] [project.optional-dependencies] testing = [ "pytest>=7.1.2", "pytest-asyncio>=0.19.0", "pytest-timeout>=2.1.0", "pytest-mock>=3.8.2", "pytest-cov>=3.0.0", ] [tool.setuptools-git-versioning] enabled = true [tool.isort] profile = "black" # will group `import x` and `from x import` of the same module. force_sort_within_sections = true known_first_party = ["zigpy_zigate", "tests"] forced_separate = "tests" combine_as_imports = true [tool.mypy] ignore_errors = true [tool.pytest.ini_options] asyncio_mode = "auto" [tool.flake8] exclude = [".venv", ".git", ".tox", "docs", "venv", "bin", "lib", "deps", "build"] # To work with Black max-line-length = 88 # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # E501: line too long # D202 No blank lines allowed after function docstring ignore = [ "W503", "E203", "E501", "D202", "D103", "D102", "D101", # TODO: remove these once docstrings are added ] per-file-ignores = ["tests/*:F811,F401,F403"]07070100000010000081A4000000000000000000000001655B78D2000000E2000000000000000000000000000000000000002A00000000zigpy-zigate-0.12.0/requirements_test.txt# Test dependencies. asynctest isort black flake8 codecov colorlog codespell mypy==1.2.0 pre-commit pylint pytest-cov pytest-sugar pytest-timeout pytest-asyncio>=0.17 pytest>=7.1.3 zigpy>=0.54.1 ruff==0.0.261 Flake8-pyproject07070100000011000081A4000000000000000000000001655B78D200000045000000000000000000000000000000000000001D00000000zigpy-zigate-0.12.0/setup.pyimport setuptools if __name__ == "__main__": setuptools.setup() 07070100000012000041ED000000000000000000000002655B78D200000000000000000000000000000000000000000000001A00000000zigpy-zigate-0.12.0/tests07070100000013000081A4000000000000000000000001655B78D200000000000000000000000000000000000000000000002600000000zigpy-zigate-0.12.0/tests/__init__.py07070100000014000081A4000000000000000000000001655B78D200000CAA000000000000000000000000000000000000002600000000zigpy-zigate-0.12.0/tests/test_api.pyimport asyncio from unittest.mock import AsyncMock, MagicMock, patch, sentinel import pytest import serial import serial_asyncio from zigpy_zigate import api as zigate_api import zigpy_zigate.config as config import zigpy_zigate.uart DEVICE_CONFIG = config.SCHEMA_DEVICE({config.CONF_DEVICE_PATH: "/dev/null"}) @pytest.fixture def api(): api = zigate_api.ZiGate(DEVICE_CONFIG) api._uart = MagicMock() return api def test_set_application(api): api.set_application(sentinel.app) assert api._app == sentinel.app @pytest.mark.asyncio async def test_connect(monkeypatch): api = zigate_api.ZiGate(DEVICE_CONFIG) async def mock_conn(loop, protocol_factory, **kwargs): protocol = protocol_factory() loop.call_soon(protocol.connection_made, None) return None, protocol monkeypatch.setattr(serial_asyncio, "create_serial_connection", mock_conn) await api.connect() def test_close(api): uart = api._uart api.close() assert uart.close.call_count == 1 assert api._uart is None @pytest.mark.asyncio @patch.object(zigpy_zigate.uart, "connect") async def test_api_new(conn_mck): """Test new class method.""" api = await zigate_api.ZiGate.new(DEVICE_CONFIG, sentinel.application) assert isinstance(api, zigate_api.ZiGate) assert conn_mck.call_count == 1 assert conn_mck.await_count == 1 @pytest.mark.asyncio @patch.object(zigate_api.ZiGate, "set_raw_mode", new_callable=AsyncMock) @pytest.mark.parametrize( "port", ("/dev/null", "pizigate:/dev/ttyAMA0"), ) async def test_probe_success(mock_raw_mode, port, monkeypatch): """Test device probing.""" async def mock_conn(loop, protocol_factory, **kwargs): protocol = protocol_factory() loop.call_soon(protocol.connection_made, None) return None, protocol monkeypatch.setattr(serial_asyncio, "create_serial_connection", mock_conn) DEVICE_CONFIG = zigpy_zigate.config.SCHEMA_DEVICE( {zigpy_zigate.config.CONF_DEVICE_PATH: port} ) res = await zigate_api.ZiGate.probe(DEVICE_CONFIG) assert res is True assert mock_raw_mode.call_count == 1 @pytest.mark.asyncio @patch.object(zigate_api.ZiGate, "set_raw_mode", side_effect=asyncio.TimeoutError) @patch.object(zigpy_zigate.uart, "connect") @pytest.mark.parametrize( "exception", (asyncio.TimeoutError, serial.SerialException, zigate_api.NoResponseError), ) async def test_probe_fail(mock_connect, mock_raw_mode, exception): """Test device probing fails.""" mock_raw_mode.side_effect = exception mock_connect.reset_mock() mock_raw_mode.reset_mock() res = await zigate_api.ZiGate.probe(DEVICE_CONFIG) assert res is False assert mock_connect.call_count == 1 assert mock_connect.await_count == 1 assert mock_connect.call_args[0][0] == DEVICE_CONFIG assert mock_raw_mode.call_count == 1 assert mock_connect.return_value.close.call_count == 1 @pytest.mark.asyncio @patch.object(asyncio, "wait", return_value=([], [])) async def test_api_command(mock_command, api): """Test command method.""" try: await api.set_raw_mode() except zigate_api.NoResponseError: pass assert mock_command.call_count == 3 07070100000015000081A4000000000000000000000001655B78D200001ACB000000000000000000000000000000000000002E00000000zigpy-zigate-0.12.0/tests/test_application.pyimport logging from unittest.mock import AsyncMock, MagicMock, call, patch import pytest import zigpy.exceptions import zigpy.types as zigpy_t import zigpy_zigate.api import zigpy_zigate.config as config import zigpy_zigate.types as t import zigpy_zigate.zigbee.application APP_CONFIG = zigpy_zigate.zigbee.application.ControllerApplication.SCHEMA( { config.CONF_DEVICE: {config.CONF_DEVICE_PATH: "/dev/null"}, config.CONF_DATABASE: None, } ) FAKE_FIRMWARE_VERSION = "3.1z" @pytest.fixture def app(): a = zigpy_zigate.zigbee.application.ControllerApplication(APP_CONFIG) a.version = FAKE_FIRMWARE_VERSION a._api = MagicMock(spec_set=zigpy_zigate.api.ZiGate) return a def test_zigpy_ieee(app): cluster = MagicMock() cluster.cluster_id = 0x0000 data = b"\x01\x02\x03\x04\x05\x06\x07\x08" zigate_ieee, _ = t.EUI64.deserialize(data) app.state.node_info.ieee = zigpy_t.EUI64(zigate_ieee) dst_addr = app.get_dst_address(cluster) assert dst_addr.serialize() == b"\x03" + data[::-1] + b"\x01" def test_model_detection(app): device = zigpy_zigate.zigbee.application.ZiGateDevice(app, 0, 0) assert device.model == "ZiGate USB-TTL {}".format(FAKE_FIRMWARE_VERSION) @pytest.mark.asyncio async def test_form_network_success(app): app._api.erase_persistent_data = AsyncMock() app._api.set_channel = AsyncMock() app._api.set_extended_panid = AsyncMock() app._api.reset = AsyncMock() async def mock_start_network(): return [[0x00, 0x1234, 0x0123456789ABCDEF], 0] app._api.start_network = mock_start_network async def mock_get_network_state(): return [ [ 0x0000, t.EUI64([0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01]), 0x1234, 0x1234ABCDEF012345, 0x11, ], 0, ] app._api.get_network_state = mock_get_network_state await app.form_network() await app.load_network_info() assert app.state.node_info.nwk == 0x0000 assert app.state.node_info.ieee == zigpy.types.EUI64.convert( "01:23:45:67:89:ab:cd:ef" ) assert app.state.network_info.pan_id == 0x1234 assert app.state.network_info.extended_pan_id == zigpy.types.ExtendedPanId.convert( "12:34:ab:cd:ef:01:23:45" ) assert app._api.reset.call_count == 0 @pytest.mark.asyncio async def test_form_network_failed(app): app._api.erase_persistent_data = AsyncMock() app._api.set_channel = AsyncMock() app._api.set_extended_panid = AsyncMock() app._api.reset = AsyncMock() async def mock_start_network(): return [[0x06], 0] app._api.start_network = mock_start_network async def mock_get_network_state(): return [[0xFFFF, 0x0123456789ABCDEF, 0x1234, 0, 0x11], 0] app._api.get_network_state = mock_get_network_state with pytest.raises(zigpy.exceptions.FormationFailure): await app.form_network() @pytest.mark.asyncio async def test_disconnect_success(app): api = MagicMock() app._api = api await app.disconnect() api.close.assert_called_once() assert app._api is None @pytest.mark.asyncio async def test_disconnect_failure(app, caplog): api = MagicMock() api.disconnect = MagicMock(side_effect=RuntimeError("Broken")) app._api = api with caplog.at_level(logging.WARNING): await app.disconnect() assert "disconnect" in caplog.text api.close.assert_called_once() assert app._api is None @pytest.mark.asyncio async def test_disconnect_multiple(app): app._api = None await app.disconnect() await app.disconnect() await app.disconnect() assert app._api is None @pytest.mark.asyncio @patch("zigpy_zigate.zigbee.application.ZiGate.new") @pytest.mark.parametrize( "version_rsp, expected_version", [[((261, 798), 0), "3.1e"], [((5, 801), 0), "3.21"]], ) async def test_startup_connect(zigate_new, app, version_rsp, expected_version): api = zigate_new.return_value api.version.return_value = version_rsp await app.connect() assert app.version == expected_version @pytest.mark.asyncio @pytest.mark.parametrize( "version, addr_mode", [ ["3.1z", t.AddressMode.NWK_NO_ACK], ["3.1d", t.AddressMode.NWK], ], ) async def test_send_unicast_request(app, version, addr_mode): packet = zigpy_t.ZigbeePacket( src=zigpy_t.AddrModeAddress(addr_mode=zigpy_t.AddrMode.NWK, address=0x0000), src_ep=1, dst=zigpy_t.AddrModeAddress(addr_mode=zigpy_t.AddrMode.NWK, address=0xFA5D), dst_ep=1, source_route=None, extended_timeout=False, tsn=20, profile_id=260, cluster_id=6, data=zigpy_t.SerializableBytes(b"\x01\x14\x00"), tx_options=zigpy_t.TransmitOptions.NONE, radius=0, non_member_radius=0, lqi=None, rssi=None, ) app.version = version app._api.raw_aps_data_request.return_value = ( [t.Status.Success, 163, 1328, b"\x00\x00"], 0, ) await app.send_packet(packet) # The packet was sent with ACKs, even though zigpy didn't ask for it assert app._api.raw_aps_data_request.mock_calls[0].kwargs["addr_mode"] == addr_mode app._api.raw_aps_data_request.assert_called_once() @pytest.mark.asyncio async def test_send_group_request(app): packet = zigpy_t.ZigbeePacket( src=None, src_ep=1, dst=zigpy_t.AddrModeAddress(addr_mode=zigpy_t.AddrMode.Group, address=0x0002), dst_ep=None, source_route=None, extended_timeout=False, tsn=21, profile_id=260, cluster_id=6, data=zigpy_t.SerializableBytes(b"\x01\x15\x00"), tx_options=zigpy_t.TransmitOptions.NONE, radius=0, non_member_radius=3, lqi=None, rssi=None, ) app._api.raw_aps_data_request.return_value = ( [t.Status.Success, 0, 1328, b"\x01\xea\x00\x00"], 0, ) await app.send_packet(packet) app._api.raw_aps_data_request.assert_called_once() @pytest.mark.asyncio async def test_energy_scanning(app, caplog): with caplog.at_level(logging.WARNING): scan_results = await app.energy_scan( channels=zigpy_t.Channels.ALL_CHANNELS, duration_exp=2, count=5 ) assert scan_results == {c: 0 for c in zigpy_t.Channels.ALL_CHANNELS} # We never send a request when scanning assert len(app._api.raw_aps_data_request.mock_calls) == 0 assert "does not support energy scanning" in caplog.text @pytest.mark.asyncio async def test_channel_migration(app, caplog): app._api.set_channel = AsyncMock() await app._move_network_to_channel(17, new_nwk_update_id=2) assert app._api.set_channel.mock_calls == [call(17)] 07070100000016000081A4000000000000000000000001655B78D200000F27000000000000000000000000000000000000002800000000zigpy-zigate-0.12.0/tests/test_types.pyimport binascii from zigpy_zigate import types as t from zigpy_zigate.api import COMMANDS, RESPONSES def test_deserialize(): extra = b"\xBE\xEF" data = b"\x00\x01\x00\x02" schema = RESPONSES[0x8000] result, rest = t.deserialize(data + extra, schema) assert rest == b"" assert result[0] == 0x00 assert result[1] == 0x01 assert result[2] == 0x0002 assert result[3] == extra extra = b"\xBE\xEF" data = b"\x00\x00\x01\x00\x01\x01\x01\x02\x12\x34\x02\xab\xcd\x01\x00" schema = RESPONSES[0x8002] result, rest = t.deserialize(data + extra, schema) assert result[0] == 0x00 assert result[1] == 0x0001 assert result[2] == 0x0001 assert result[3] == 0x01 assert result[4] == 0x01 assert result[5] == t.Address(address_mode=t.AddressMode.NWK, address=t.NWK(0x1234)) assert result[6] == t.Address(address_mode=t.AddressMode.NWK, address=t.NWK(0xABCD)) assert result[7] == b"\x01\x00\xBE\xEF" assert rest == b"" data = b"\x00\x01\x01\x02\x12\x34\xff" schema = RESPONSES[0x8702] result, rest = t.deserialize(data + extra, schema) assert result[0] == 0x00 assert result[1] == 0x01 assert result[2] == 0x01 assert result[3] == t.Address(address_mode=t.AddressMode.NWK, address=t.NWK(0x1234)) assert result[4] == 0xFF data = b"\x00\x01\x01\x03\x12\x34\x56\x78\x9a\xbc\xde\xf0\xff" schema = RESPONSES[0x8702] result, rest = t.deserialize(data + extra, schema) assert result[0] == 0x00 assert result[1] == 0x01 assert result[2] == 0x01 assert result[3] == t.Address( address_mode=t.AddressMode.IEEE, address=t.EUI64.deserialize(b"\x12\x34\x56\x78\x9a\xbc\xde\xf0")[0], ) assert result[4] == 0xFF data = b"\x00\x01\x01\x12\x34\x56\x78\x9a\xbc\xde\xf0\xff" schema = RESPONSES[0x8024] result, rest = t.deserialize(data, schema) assert result[0] == 0x00 assert result[1] == 0x0101 assert result[2] == t.EUI64.deserialize(b"\x12\x34\x56\x78\x9a\xbc\xde\xf0")[0] assert result[3] == 0xFF data = b"\x06" schema = RESPONSES[0x8024] result, rest = t.deserialize(data, schema) assert result[0] == 0x06 assert result[1] is None assert result[2] is None assert result[3] is None assert len(result) == 4 # Frame received: 8012000a2800010102bc8c73000100 # data received 0x8012 b'00010102bc8c730001' data = binascii.unhexlify(b"00010102bc8c730001") schema = RESPONSES[0x8012] result, rest = t.deserialize(data, schema) assert result[0] == 0x00 assert result[1] == 0x01 assert result[2] == 0x01 assert result[3] == t.Address( address_mode=t.AddressMode.NWK, address=t.NWK.deserialize(b"\xbc\x8c")[0] ) assert result[4] == 0x73 assert len(result) == 5 # Frame received: 99990002828000 # data received 0x9999 b'80' LQI:0 data = binascii.unhexlify(b"80") schema = RESPONSES[0x9999] result, rest = t.deserialize(data, schema) assert result[0] == 0x80 assert len(result) == 1 def test_serialize(): data = [True] schema = COMMANDS[0x0002] result = t.serialize(data, schema) assert result == b"\x01" data = [b"\x12\x34"] schema = (t.LBytes,) result = t.serialize(data, schema) assert result == b"\x02\x124" def test_EUI64(): data = b"\x12\x34\x56\x78\x9a\xbc\xde\xf0\x00" ieee, rest = t.EUI64.deserialize(data) assert rest == b"\x00" assert ieee == t.EUI64.deserialize(b"\x12\x34\x56\x78\x9a\xbc\xde\xf0")[0] data2 = ieee.serialize() assert data2 == b"\x12\x34\x56\x78\x9a\xbc\xde\xf0" assert str(ieee) == "12:34:56:78:9a:bc:de:f0" def test_NWK(): data = b"\x124" nwk, rest = t.NWK.deserialize(data) assert nwk == t.NWK(0x1234) data2 = nwk.serialize() assert data2 == data assert repr(nwk) == "0x1234" 07070100000017000081A4000000000000000000000001655B78D20000138E000000000000000000000000000000000000002700000000zigpy-zigate-0.12.0/tests/test_uart.pyfrom unittest.mock import AsyncMock, MagicMock import gpiozero import pytest import serial.tools.list_ports import serial_asyncio from zigpy_zigate import common, uart import zigpy_zigate.config @pytest.fixture def gw(): gw = uart.Gateway(MagicMock()) gw._transport = MagicMock() return gw @pytest.mark.asyncio @pytest.mark.parametrize( "port", ("/dev/null", "pizigate:/dev/ttyAMA0"), ) async def test_connect(port, monkeypatch): api = MagicMock() async def mock_conn(loop, protocol_factory, url, **kwargs): protocol = protocol_factory() loop.call_soon(protocol.connection_made, None) assert url.startswith("/") is True return None, protocol monkeypatch.setattr(serial_asyncio, "create_serial_connection", mock_conn) monkeypatch.setattr(common, "set_pizigate_running_mode", AsyncMock()) DEVICE_CONFIG = zigpy_zigate.config.SCHEMA_DEVICE( {zigpy_zigate.config.CONF_DEVICE_PATH: port} ) await uart.connect(DEVICE_CONFIG, api) def test_send(gw): frame = b"\x01\x02\x150\x02\x10\x02\x114\x02\x10\x03" data = b"\x00" gw.send(0x0530, data) assert gw._transport.write.call_count == 1 assert gw._transport.write.call_args[0][0] == frame def test_close(gw): gw.close() assert gw._transport.close.call_count == 1 def test_data_received_chunk_frame(gw): data = b"\x01\x80\x10\x02\x10\x02\x15\xaa\x02\x10\x02\x1f?\xf0\xff\x03" gw.data_received(data[:-4]) assert gw._api.data_received.call_count == 0 gw.data_received(data[-4:]) assert gw._api.data_received.call_count == 1 assert gw._api.data_received.call_args[0] == (0x8010, b"\x00\x0f?\xf0", 255) def test_data_received_full_frame(gw): data = b"\x01\x80\x10\x02\x10\x02\x15\xaa\x02\x10\x02\x1f?\xf0\xff\x03" gw.data_received(data) assert gw._api.data_received.call_count == 1 assert gw._api.data_received.call_args[0] == (0x8010, b"\x00\x0f?\xf0", 255) def test_data_received_incomplete_frame(gw): data = b"~\x00\x00" gw.data_received(data) assert gw._api.data_received.call_count == 0 def test_data_received_runt_frame(gw): data = b"\x02\x44\xC0" gw.data_received(data) assert gw._api.data_received.call_count == 0 def test_data_received_extra(gw): data = b"\x01\x80\x10\x02\x10\x02\x15\xaa\x02\x10\x02\x1f?\xf0\xff\x03\x00" gw.data_received(data) assert gw._api.data_received.call_count == 1 assert gw._api.data_received.call_args[0] == (0x8010, b"\x00\x0f?\xf0", 255) assert gw._buffer == b"\x00" def test_data_received_wrong_checksum(gw): data = b"\x01\x80\x10\x02\x10\x02\x15\xab\x02\x10\x02\x1f?\xf0\xff\x03" gw.data_received(data) assert gw._api.data_received.call_count == 0 def test_unescape(gw): data = b"\x80\x10\x02\x10\x02\x15\xaa\x02\x10\x02\x1f?\xf0\xff" data_unescaped = b"\x80\x10\x00\x05\xaa\x00\x0f?\xf0\xff" r = gw._unescape(data) assert r == data_unescaped def test_escape(gw): data = b"\x80\x10\x00\x05\xaa\x00\x0f?\xf0\xff" data_escaped = b"\x80\x10\x02\x10\x02\x15\xaa\x02\x10\x02\x1f?\xf0\xff" r = gw._escape(data) assert r == data_escaped def test_length(gw): data = b"\x80\x10\x00\x05\xaa\x00\x0f?\xf0\xff" length = 5 r = gw._length(data) assert r == length def test_checksum(gw): data = b"\x00\x0f?\xf0" checksum = 0xAA r = gw._checksum(b"\x80\x10", 5, 0xFF, data) assert r == checksum @pytest.mark.parametrize( "port", ("/dev/ttyAMA0", "/dev/serial0", "pizigate:/dev/ttyAMA0"), ) def test_is_pizigate(port): r = common.is_pizigate(port) assert r is True def test_is_not_pizigate(): port = "/dev/ttyUSB1" r = common.is_pizigate(port) assert r is False def test_is_zigatedin(monkeypatch): def mock_grep(*args, **kwargs): device = MagicMock() device.description = "ZiGate" device.manufacturer = "FTDI" return iter([device]) monkeypatch.setattr(serial.tools.list_ports, "grep", mock_grep) port = "/dev/ttyUSB1" r = common.is_zigate_din(port) assert r is True @pytest.mark.parametrize( "port", ("/dev/ttyUSB1", "/dev/ttyAMA0", "/dev/serial0"), ) def test_is_not_zigatedin(port, monkeypatch): def mock_grep(*args, **kwargs): device = MagicMock() device.description = "Other" device.manufacturer = "FTDI" return iter([device]) monkeypatch.setattr(serial.tools.list_ports, "grep", mock_grep) r = common.is_zigate_din(port) assert r is False def test_is_zigate_wifi(): port = "socket://192.168.1.10:9999" r = common.is_zigate_wifi(port) assert r is True def test_is_not_zigate_wifi(): port = "/dev/ttyUSB1" r = common.is_zigate_wifi(port) assert r is False def test_startup_gpio_toggling(monkeypatch): monkeypatch.setattr(gpiozero.Device, "_default_pin_factory", MagicMock()) common.set_pizigate_running_mode() common.set_pizigate_flashing_mode() 07070100000018000041ED000000000000000000000004655B78D200000000000000000000000000000000000000000000002100000000zigpy-zigate-0.12.0/zigpy_zigate07070100000019000081A4000000000000000000000001655B78D200000000000000000000000000000000000000000000002D00000000zigpy-zigate-0.12.0/zigpy_zigate/__init__.py0707010000001A000081A4000000000000000000000001655B78D200004AA2000000000000000000000000000000000000002800000000zigpy-zigate-0.12.0/zigpy_zigate/api.pyimport asyncio import binascii import datetime import enum import functools import logging from typing import Any, Dict import serial import zigpy.exceptions import zigpy_zigate.config import zigpy_zigate.uart from . import types as t LOGGER = logging.getLogger(__name__) COMMAND_TIMEOUT = 1.5 PROBE_TIMEOUT = 3.0 class CommandId(enum.IntEnum): SET_RAWMODE = 0x0002 NETWORK_STATE_REQ = 0x0009 GET_VERSION = 0x0010 RESET = 0x0011 ERASE_PERSISTENT_DATA = 0x0012 GET_DEVICES_LIST = 0x0015 SET_TIMESERVER = 0x0016 GET_TIMESERVER = 0x0017 SET_LED = 0x0018 SET_CE_FCC = 0x0019 SET_EXT_PANID = 0x0020 SET_CHANNELMASK = 0x0021 START_NETWORK = 0x0024 NETWORK_REMOVE_DEVICE = 0x0026 PERMIT_JOINING_REQUEST = 0x0049 MANAGEMENT_NETWORK_UPDATE_REQUEST = 0x004A SEND_RAW_APS_DATA_PACKET = 0x0530 AHI_SET_TX_POWER = 0x0806 class ResponseId(enum.IntEnum): DEVICE_ANNOUNCE = 0x004D STATUS = 0x8000 LOG = 0x8001 DATA_INDICATION = 0x8002 PDM_LOADED = 0x0302 NODE_NON_FACTORY_NEW_RESTART = 0x8006 NODE_FACTORY_NEW_RESTART = 0x8007 HEART_BEAT = 0x8008 NETWORK_STATE_RSP = 0x8009 VERSION_LIST = 0x8010 ACK_DATA = 0x8011 APS_DATA_CONFIRM = 0x8012 PERMIT_JOIN_RSP = 0x8014 GET_DEVICES_LIST_RSP = 0x8015 GET_TIMESERVER_LIST = 0x8017 NETWORK_JOINED_FORMED = 0x8024 PDM_EVENT = 0x8035 NODE_DESCRIPTOR_RSP = 0x8042 LEAVE_INDICATION = 0x8048 ROUTE_DISCOVERY_CONFIRM = 0x8701 APS_DATA_CONFIRM_FAILED = 0x8702 AHI_SET_TX_POWER_RSP = 0x8806 EXTENDED_ERROR = 0x9999 class SendSecurity(t.uint8_t, enum.Enum): NETWORK = 0x00 APPLINK = 0x01 TEMP_APPLINK = 0x02 class NonFactoryNewRestartStatus(t.uint8_t, enum.Enum): Startup = 0 Running = 1 Start = 2 class FactoryNewRestartStatus(t.uint8_t, enum.Enum): Startup = 0 Start = 2 Running = 6 RESPONSES = { ResponseId.DEVICE_ANNOUNCE: (t.NWK, t.EUI64, t.uint8_t, t.uint8_t), ResponseId.STATUS: (t.Status, t.uint8_t, t.uint16_t, t.Bytes), ResponseId.LOG: (t.LogLevel, t.Bytes), ResponseId.DATA_INDICATION: ( t.Status, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.Address, t.Address, t.Bytes, ), ResponseId.PDM_LOADED: (t.uint8_t,), ResponseId.NODE_NON_FACTORY_NEW_RESTART: (NonFactoryNewRestartStatus,), ResponseId.NODE_FACTORY_NEW_RESTART: (FactoryNewRestartStatus,), ResponseId.HEART_BEAT: (t.uint32_t,), ResponseId.NETWORK_STATE_RSP: (t.NWK, t.EUI64, t.uint16_t, t.uint64_t, t.uint8_t), ResponseId.VERSION_LIST: (t.uint16_t, t.uint16_t), ResponseId.ACK_DATA: (t.Status, t.NWK, t.uint8_t, t.uint16_t, t.uint8_t), ResponseId.APS_DATA_CONFIRM: ( t.Status, t.uint8_t, t.uint8_t, t.Address, t.uint8_t, ), ResponseId.PERMIT_JOIN_RSP: (t.uint8_t,), ResponseId.GET_DEVICES_LIST_RSP: (t.DeviceEntryArray,), ResponseId.GET_TIMESERVER_LIST: (t.uint32_t,), ResponseId.NETWORK_JOINED_FORMED: (t.uint8_t, t.NWK, t.EUI64, t.uint8_t), ResponseId.PDM_EVENT: (t.Status, t.uint32_t), ResponseId.NODE_DESCRIPTOR_RSP: ( t.uint8_t, t.Status, t.NWK, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint16_t, ), ResponseId.LEAVE_INDICATION: (t.EUI64, t.uint8_t), ResponseId.ROUTE_DISCOVERY_CONFIRM: (t.uint8_t, t.uint8_t), ResponseId.APS_DATA_CONFIRM_FAILED: ( t.Status, t.uint8_t, t.uint8_t, t.Address, t.uint8_t, ), ResponseId.AHI_SET_TX_POWER_RSP: (t.uint8_t,), ResponseId.EXTENDED_ERROR: (t.Status,), } COMMANDS = { CommandId.SET_RAWMODE: (t.uint8_t,), CommandId.SET_TIMESERVER: (t.uint32_t,), CommandId.SET_LED: (t.uint8_t,), CommandId.SET_CE_FCC: (t.uint8_t,), CommandId.SET_EXT_PANID: (t.uint64_t,), CommandId.SET_CHANNELMASK: (t.uint32_t,), CommandId.NETWORK_REMOVE_DEVICE: (t.EUI64, t.EUI64), CommandId.PERMIT_JOINING_REQUEST: (t.NWK, t.uint8_t, t.uint8_t), CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST: ( t.NWK, t.uint32_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint16_t, ), CommandId.SEND_RAW_APS_DATA_PACKET: ( t.uint8_t, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.LBytes, ), CommandId.AHI_SET_TX_POWER: (t.uint8_t,), } class AutoEnum(enum.IntEnum): def _generate_next_value_(name, start, count, last_values): return count class PDM_EVENT(enum.IntEnum): E_PDM_SYSTEM_EVENT_WEAR_COUNT_TRIGGER_VALUE_REACHED = 0 E_PDM_SYSTEM_EVENT_DESCRIPTOR_SAVE_FAILED = 1 E_PDM_SYSTEM_EVENT_PDM_NOT_ENOUGH_SPACE = 2 E_PDM_SYSTEM_EVENT_LARGEST_RECORD_FULL_SAVE_NO_LONGER_POSSIBLE = 3 E_PDM_SYSTEM_EVENT_SEGMENT_DATA_CHECKSUM_FAIL = 4 E_PDM_SYSTEM_EVENT_SEGMENT_SAVE_OK = 5 E_PDM_SYSTEM_EVENT_EEPROM_SEGMENT_HEADER_REPAIRED = 6 E_PDM_SYSTEM_EVENT_SYSTEM_INTERNAL_BUFFER_WEAR_COUNT_SWAP = 7 E_PDM_SYSTEM_EVENT_SYSTEM_DUPLICATE_FILE_SEGMENT_DETECTED = 8 E_PDM_SYSTEM_EVENT_SYSTEM_ERROR = 9 E_PDM_SYSTEM_EVENT_SEGMENT_PREWRITE = 10 E_PDM_SYSTEM_EVENT_SEGMENT_POSTWRITE = 11 E_PDM_SYSTEM_EVENT_SEQUENCE_DUPLICATE_DETECTED = 12 E_PDM_SYSTEM_EVENT_SEQUENCE_VERIFY_FAIL = 13 E_PDM_SYSTEM_EVENT_PDM_SMART_SAVE = 14 E_PDM_SYSTEM_EVENT_PDM_FULL_SAVE = 15 class NoResponseError(zigpy.exceptions.APIException): pass class NoStatusError(NoResponseError): pass class CommandError(zigpy.exceptions.APIException): pass class ZiGate: def __init__(self, device_config: Dict[str, Any]): self._app = None self._config = device_config self._uart = None self._awaiting = {} self._status_awaiting = {} self._lock = asyncio.Lock() self._conn_lost_task = None self.network_state = None @classmethod async def new(cls, config: Dict[str, Any], application=None) -> "ZiGate": api = cls(config) await api.connect() api.set_application(application) return api async def connect(self): assert self._uart is None self._uart = await zigpy_zigate.uart.connect(self._config, self) def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" LOGGER.warning( "Serial '%s' connection lost unexpectedly: %s", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], exc, ) self._uart = None if self._conn_lost_task and not self._conn_lost_task.done(): self._conn_lost_task.cancel() self._conn_lost_task = asyncio.ensure_future(self._connection_lost()) async def _connection_lost(self) -> None: """Reconnect serial port.""" try: await self._reconnect_till_done() except asyncio.CancelledError: LOGGER.debug("Cancelling reconnection attempt") async def _reconnect_till_done(self) -> None: attempt = 1 while True: try: await asyncio.wait_for(self.reconnect(), timeout=10) break except (asyncio.TimeoutError, OSError) as exc: wait = 2 ** min(attempt, 5) attempt += 1 LOGGER.debug( "Couldn't re-open '%s' serial port, retrying in %ss: %s", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], wait, str(exc), ) await asyncio.sleep(wait) LOGGER.debug( "Reconnected '%s' serial port after %s attempts", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], attempt, ) def close(self): if self._uart: self._uart.close() self._uart = None def reconnect(self): """Reconnect using saved parameters.""" LOGGER.debug( "Reconnecting '%s' serial port", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], ) return self.connect() def set_application(self, app): self._app = app def data_received(self, cmd, data, lqi): if cmd not in RESPONSES: LOGGER.warning( "Received unhandled response 0x%04x: %r", cmd, binascii.hexlify(data) ) return cmd = ResponseId(cmd) data, rest = t.deserialize(data, RESPONSES[cmd]) LOGGER.debug("Response received: %s %s %s (LQI:%s)", cmd, data, rest, lqi) if cmd == ResponseId.STATUS: if data[2] in self._status_awaiting: fut = self._status_awaiting.pop(data[2]) fut.set_result((data, lqi)) if cmd in self._awaiting: fut = self._awaiting.pop(cmd) fut.set_result((data, lqi)) self.handle_callback(cmd, data, lqi) async def wait_for_status(self, cmd): LOGGER.debug("Wait for status to command %s", cmd) if cmd in self._status_awaiting: self._status_awaiting[cmd].cancel() status_fut = asyncio.Future() self._status_awaiting[cmd] = status_fut try: return await status_fut finally: if cmd in self._status_awaiting: self._status_awaiting[cmd].cancel() del self._status_awaiting[cmd] async def wait_for_response(self, wait_response): LOGGER.debug("Wait for response %s", wait_response) if wait_response in self._awaiting: self._awaiting[wait_response].cancel() response_fut = asyncio.Future() self._awaiting[wait_response] = response_fut try: return await response_fut finally: if wait_response in self._awaiting: self._awaiting[wait_response].cancel() del self._awaiting[wait_response] async def command( self, cmd, data=b"", wait_response=None, wait_status=True, timeout=COMMAND_TIMEOUT, ): async with self._lock: tries = 3 tasks = [] status_task = None response_task = None LOGGER.debug( "Sending %s (%s), waiting for status: %s, waiting for response: %s", cmd, data, wait_status, wait_response, ) if wait_status: status_task = asyncio.create_task(self.wait_for_status(cmd)) tasks.append(status_task) if wait_response is not None: response_task = asyncio.create_task( self.wait_for_response(wait_response) ) tasks.append(response_task) try: while tries > 0: if self._uart is None: # connection was lost raise CommandError("API is not running") tries -= 1 self._uart.send(cmd, data) done, pending = await asyncio.wait(tasks, timeout=timeout) if wait_status and tries == 0 and status_task in pending: raise NoStatusError() elif wait_response and tries == 0 and response_task in pending: raise NoResponseError() if wait_response and response_task in done: if wait_status and status_task in pending: continue elif wait_status: await status_task return await response_task elif wait_status and status_task in done: return await status_task elif not wait_response and not wait_status: return finally: for task in tasks: if not task.done(): task.cancel() await asyncio.gather(*tasks, return_exceptions=True) async def version(self): return await self.command( CommandId.GET_VERSION, wait_response=ResponseId.VERSION_LIST ) async def version_str(self): version, lqi = await self.version() version = "{:x}".format(version[1]) version = "{}.{}".format(version[0], version[1:]) return version async def get_network_state(self): return await self.command( CommandId.NETWORK_STATE_REQ, wait_response=ResponseId.NETWORK_STATE_RSP ) async def set_raw_mode(self, enable=True): data = t.serialize([enable], COMMANDS[CommandId.SET_RAWMODE]) await self.command(CommandId.SET_RAWMODE, data) async def reset(self, *, wait=True): wait_response = ResponseId.NODE_NON_FACTORY_NEW_RESTART if wait else None await self.command(CommandId.RESET, wait_response=wait_response) async def erase_persistent_data(self): await self.command( CommandId.ERASE_PERSISTENT_DATA, wait_status=False, wait_response=ResponseId.PDM_LOADED, timeout=10, ) await asyncio.sleep(1) await self.command( CommandId.RESET, wait_response=ResponseId.NODE_FACTORY_NEW_RESTART ) async def set_time(self, dt=None): """set internal time if timestamp is None, now is used """ dt = dt or datetime.datetime.now() timestamp = int((dt - datetime.datetime(2000, 1, 1)).total_seconds()) data = t.serialize([timestamp], COMMANDS[CommandId.SET_TIMESERVER]) await self.command(CommandId.SET_TIMESERVER, data) async def get_time_server(self): timestamp, lqi = await self.command( CommandId.GET_TIMESERVER, wait_response=ResponseId.GET_TIMESERVER_LIST ) dt = datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds=timestamp[0]) return dt async def set_led(self, enable=True): data = t.serialize([enable], COMMANDS[CommandId.SET_LED]) await self.command(CommandId.SET_LED, data) async def set_certification(self, typ="CE"): cert = {"CE": 1, "FCC": 2}[typ] data = t.serialize([cert], COMMANDS[CommandId.SET_CE_FCC]) await self.command(CommandId.SET_CE_FCC, data) async def management_network_request(self): data = t.serialize( [0x0000, 0x07FFF800, 0xFF, 5, 0xFF, 0x0000], COMMANDS[CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST], ) return await self.command( CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST, data ) # , wait_response=0x804a, timeout=10) async def set_tx_power(self, power=63): if power > 63: power = 63 if power < 0: power = 0 data = t.serialize([power], COMMANDS[CommandId.AHI_SET_TX_POWER]) power, lqi = await self.command( CommandId.AHI_SET_TX_POWER, data, wait_response=CommandId.AHI_SET_TX_POWER_RSP, ) return power[0] async def set_channel(self, channels=None): channels = channels or [11, 14, 15, 19, 20, 24, 25, 26] if not isinstance(channels, list): channels = [channels] mask = functools.reduce(lambda acc, x: acc ^ 2**x, channels, 0) data = t.serialize([mask], COMMANDS[CommandId.SET_CHANNELMASK]) await self.command(CommandId.SET_CHANNELMASK, data) async def set_extended_panid(self, extended_pan_id): data = t.serialize([extended_pan_id], COMMANDS[CommandId.SET_EXT_PANID]) await self.command(CommandId.SET_EXT_PANID, data) async def get_devices_list(self): (entries,), lqi = await self.command( CommandId.GET_DEVICES_LIST, wait_response=ResponseId.GET_DEVICES_LIST_RSP ) return list(entries or []) async def permit_join(self, duration=60): data = t.serialize( [0x0000, duration, 1], COMMANDS[CommandId.PERMIT_JOINING_REQUEST] ) return await self.command(CommandId.PERMIT_JOINING_REQUEST, data) async def start_network(self): return await self.command( CommandId.START_NETWORK, wait_response=ResponseId.NETWORK_JOINED_FORMED ) async def remove_device(self, zigate_ieee, ieee): data = t.serialize( [zigate_ieee, ieee], COMMANDS[CommandId.NETWORK_REMOVE_DEVICE] ) return await self.command(CommandId.NETWORK_REMOVE_DEVICE, data) async def raw_aps_data_request( self, addr, src_ep, dst_ep, profile, cluster, payload, addr_mode=t.AddressMode.NWK, security=SendSecurity.NETWORK, radius=0, ): """ Send raw APS Data request """ data = t.serialize( [ addr_mode, addr, src_ep, dst_ep, cluster, profile, security, radius, payload, ], COMMANDS[CommandId.SEND_RAW_APS_DATA_PACKET], ) return await self.command(CommandId.SEND_RAW_APS_DATA_PACKET, data) def handle_callback(self, *args): """run application callback handler""" if self._app: try: self._app.zigate_callback_handler(*args) except Exception as e: LOGGER.exception("Exception running handler", exc_info=e) @classmethod async def probe(cls, device_config: Dict[str, Any]) -> bool: """Probe port for the device presence.""" api = cls(zigpy_zigate.config.SCHEMA_DEVICE(device_config)) try: await asyncio.wait_for(api._probe(), timeout=PROBE_TIMEOUT) return True except ( asyncio.TimeoutError, serial.SerialException, zigpy.exceptions.ZigbeeException, ) as exc: LOGGER.debug( "Unsuccessful radio probe of '%s' port", device_config[zigpy_zigate.config.CONF_DEVICE_PATH], exc_info=exc, ) finally: api.close() return False async def _probe(self) -> None: """Open port and try sending a command""" try: device = next( serial.tools.list_ports.grep( self._config[zigpy_zigate.config.CONF_DEVICE_PATH] ) ) if device.description == "ZiGate": return except StopIteration: pass await self.connect() await self.set_raw_mode() 0707010000001B000081A4000000000000000000000001655B78D20000129F000000000000000000000000000000000000002B00000000zigpy-zigate-0.12.0/zigpy_zigate/common.pyimport asyncio import logging import os.path import re import time from gpiozero import OutputDevice import serial import serial.tools.list_ports LOGGER = logging.getLogger(__name__) GPIO_PIN0 = 17 GPIO_PIN2 = 27 class UnclosableOutputDevice(OutputDevice): """ `OutputDevice` that never closes its pins. Allows for the last-written pin state to be retained even after the `OutputDevice` is garbage collected. """ def __init__( self, pin=None, *, active_high=True, initial_value=False, pin_factory=None ): super().__init__( pin, active_high=active_high, initial_value=initial_value, pin_factory=pin_factory, ) self._pin.close = lambda *args, **kwargs: None self.pin_factory.close = lambda *args, **kwargs: None def discover_port(): """discover zigate port""" devices = list(serial.tools.list_ports.grep("ZiGate")) if devices: port = devices[0].device LOGGER.info("ZiGate found at %s", port) else: devices = list(serial.tools.list_ports.grep("067b:2303|CP2102")) if devices: port = devices[0].device LOGGER.info("ZiGate probably found at %s", port) else: LOGGER.error("Unable to find ZiGate using auto mode") raise serial.SerialException("Unable to find Zigate using auto mode") return port def is_pizigate(port): """detect pizigate""" # Suppose pizigate on /dev/ttyAMAx or /dev/serialx if port.startswith("pizigate:"): return True port = os.path.realpath(port) return re.match(r"/dev/(tty(S|AMA)|serial)\d+", port) is not None def is_zigate_din(port): """detect zigate din""" port = os.path.realpath(port) if re.match(r"/dev/ttyUSB\d+", port): try: device = next(serial.tools.list_ports.grep(port)) # Suppose zigate din /dev/ttyUSBx return device.description == "ZiGate" and device.manufacturer == "FTDI" except StopIteration: pass return False def is_zigate_wifi(port): """detect zigate din""" return port.startswith("socket://") def set_pizigate_running_mode(): LOGGER.info("Put PiZiGate in running mode") gpio0 = UnclosableOutputDevice(pin=GPIO_PIN0, initial_value=None) gpio2 = UnclosableOutputDevice(pin=GPIO_PIN2, initial_value=None) gpio2.on() time.sleep(0.5) gpio0.off() time.sleep(0.5) gpio0.on() time.sleep(0.5) def set_pizigate_flashing_mode(): LOGGER.info("Put PiZiGate in flashing mode") gpio0 = UnclosableOutputDevice(pin=GPIO_PIN0, initial_value=None) gpio2 = UnclosableOutputDevice(pin=GPIO_PIN2, initial_value=None) gpio2.off() time.sleep(0.5) gpio0.off() time.sleep(0.5) gpio0.on() time.sleep(0.5) def ftdi_set_bitmode(dev, bitmask): """ Set mode for ZiGate DIN module """ import usb BITMODE_CBUS = 0x20 SIO_SET_BITMODE_REQUEST = 0x0B bmRequestType = usb.util.build_request_type( usb.util.CTRL_OUT, usb.util.CTRL_TYPE_VENDOR, usb.util.CTRL_RECIPIENT_DEVICE ) wValue = bitmask | (BITMODE_CBUS << BITMODE_CBUS) dev.ctrl_transfer(bmRequestType, SIO_SET_BITMODE_REQUEST, wValue) def set_zigatedin_running_mode(): import usb dev = usb.core.find(idVendor=0x0403, idProduct=0x6001) if not dev: raise RuntimeError("ZiGate DIN not found.") LOGGER.info("Put ZiGate DIN in running mode") ftdi_set_bitmode(dev, 0xC8) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) def set_zigatedin_flashing_mode(): import usb dev = usb.core.find(idVendor=0x0403, idProduct=0x6001) if not dev: raise RuntimeError("ZiGate DIN not found.") LOGGER.info("Put ZiGate DIN in flashing mode") ftdi_set_bitmode(dev, 0x00) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) ftdi_set_bitmode(dev, 0xC0) time.sleep(0.5) ftdi_set_bitmode(dev, 0xC4) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) def async_run_in_executor(function): """Decorator to make a sync function async.""" async def replacement(*args): return asyncio.get_running_loop().run_in_executor(None, function, *args) replacement._sync_func = function return replacement # Create async version of all of the above functions async_set_pizigate_running_mode = async_run_in_executor(set_pizigate_running_mode) async_set_pizigate_flashing_mode = async_run_in_executor(set_pizigate_flashing_mode) async_set_zigatedin_running_mode = async_run_in_executor(set_zigatedin_running_mode) async_set_zigatedin_flashing_mode = async_run_in_executor(set_zigatedin_flashing_mode) 0707010000001C000081A4000000000000000000000001655B78D2000000A9000000000000000000000000000000000000002B00000000zigpy-zigate-0.12.0/zigpy_zigate/config.pyfrom zigpy.config import ( # noqa: F401 pylint: disable=unused-import CONF_DATABASE, CONF_DEVICE, CONF_DEVICE_PATH, CONFIG_SCHEMA, SCHEMA_DEVICE, ) 0707010000001D000041ED000000000000000000000002655B78D200000000000000000000000000000000000000000000002700000000zigpy-zigate-0.12.0/zigpy_zigate/tools0707010000001E000081A4000000000000000000000001655B78D200000000000000000000000000000000000000000000003300000000zigpy-zigate-0.12.0/zigpy_zigate/tools/__init__.py0707010000001F000081A4000000000000000000000001655B78D200000BCE000000000000000000000000000000000000002E00000000zigpy-zigate-0.12.0/zigpy_zigate/tools/cli.py""" Simple CLI ZiGate tool """ import argparse import asyncio import logging from zigpy_zigate.api import LOGGER, CommandError, NoResponseError, ZiGate import zigpy_zigate.config async def main(): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument( "command", help="Command to start", choices=[ "version", "reset", "erase_persistent", "set_time", "get_time", "set_led", "set_certification", "set_tx_power", "management_network_request", "loop", ], ) parser.add_argument("-p", "--port", help="Port", default="auto") parser.add_argument("-d", "--debug", help="Debug log", action="store_true") parser.add_argument("-v", "--value", help="Set command's value") args = parser.parse_args() print("Port set to", args.port) if args.debug: logging.root.setLevel(logging.DEBUG) device_config = {zigpy_zigate.config.CONF_DEVICE_PATH: args.port} api = ZiGate(device_config) await api.connect() if args.command == "version": print("Firmware version", await api.version_str()) elif args.command == "reset": await api.reset() print("ZiGate reseted") elif args.command == "erase_persistent": await api.erase_persistent_data() print("ZiGate pesistent date erased") elif args.command == "set_time": await api.set_time() print("ZiGate internal time server set to current time") elif args.command == "get_time": print("ZiGate internal time server is", await api.get_time_server()) elif args.command == "set_led": enable = int(args.value or 1) print("Set ZiGate led to", enable) await api.set_led(enable) elif args.command == "set_certification": _type = args.value or "CE" print("Set ZiGate Certification to", _type) await api.set_certification(_type) elif args.command == "set_tx_power": power = int(args.value or 63) print("Set ZiGate TX Power to", power) print("Tx power set to", await api.set_tx_power(power)) elif args.command == "management_network_request": await api.reset() # await api.set_raw_mode(False) await api.management_network_request() print("ok") await asyncio.sleep(10) elif args.command == "loop": # for testing purpose enable = True while True: try: LOGGER.info("Set led %s", enable) await api.set_led(enable) enable = not enable await asyncio.sleep(1) except KeyboardInterrupt: break except (NoResponseError, CommandError): LOGGER.exception("NoResponseError") await asyncio.sleep(1) continue api.close() if __name__ == "__main__": asyncio.run(main()) 07070100000020000081A4000000000000000000000001655B78D20000095C000000000000000000000000000000000000003300000000zigpy-zigate-0.12.0/zigpy_zigate/tools/firmware.pyimport argparse from collections import OrderedDict import json import logging import os import urllib.request URL = "https://api.github.com/repos/fairecasoimeme/ZiGate/releases" LOGGER = logging.getLogger("ZiGate Firmware") def get_releases(): LOGGER.info("Searching for ZiGate firmware") releases = OrderedDict() r = urllib.request.urlopen(URL) if r.status == 200: for release in json.loads(r.read()): if release.get("draft"): continue if release.get("prerelease"): continue for asset in release["assets"]: if "pdm" in asset["name"].lower(): continue if asset["name"].endswith(".bin"): LOGGER.info("Found %s", asset["name"]) releases[asset["name"]] = asset["browser_download_url"] return releases def download(url, dest="/tmp"): filename = url.rsplit("/", 1)[1] LOGGER.info("Downloading %s to %s", url, dest) r = urllib.request.urlopen(url) if r.status == 200: filename = os.path.join(dest, filename) with open(filename, "wb") as fp: fp.write(r.read()) LOGGER.info("Done") return filename else: LOGGER.error("Error downloading %s %s", r.status, r.reason) def download_latest(dest="/tmp"): LOGGER.info("Download latest firmware") releases = get_releases() if releases: latest = list(releases.keys())[0] LOGGER.info("Latest is %s", latest) return download(releases[latest], dest) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument( "command", help="Command to start", choices=["list", "download", "download-latest"], ) parser.add_argument("--url", help="Download URL") parser.add_argument( "--dest", help="Download folder, default to /tmp", default="/tmp" ) args = parser.parse_args() if args.command == "list": for k, v in get_releases().items(): print(k, v) elif args.command == "download": if not args.url: LOGGER.error("You have to give a URL to download using --url") else: download(args.url, args.dest) elif args.command == "download-latest": download_latest(args.dest) 07070100000021000081A4000000000000000000000001655B78D2000037C5000000000000000000000000000000000000003200000000zigpy-zigate-0.12.0/zigpy_zigate/tools/flasher.py#!/usr/bin/python3 # # Copyright (c) 2018 Sébastien RAMAGE # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. # # Thanks to Sander Hoentjen (tjikkun) we now have a flasher ! # https://github.com/tjikkun/zigate-flasher import argparse import datetime import functools import itertools import logging from operator import xor import struct import serial from serial.tools.list_ports import comports from zigpy_zigate import common as c from .firmware import download_latest LOGGER = logging.getLogger(__name__) _responses = {} ZIGATE_CHIP_ID = 0x10408686 ZIGATE_BINARY_VERSION = bytes.fromhex("07030008") ZIGATE_FLASH_START = 0x00000000 ZIGATE_FLASH_END = 0x00040000 class Command: def __init__(self, type_, fmt=None, raw=False): assert not (raw and fmt), "Raw commands cannot use built-in struct formatting" LOGGER.debug("Command {} {} {}".format(type_, fmt, raw)) self.type = type_ self.raw = raw if fmt: self.struct = struct.Struct(fmt) else: self.struct = None def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): rv = func(*args, **kwargs) if self.struct: try: data = self.struct.pack(*rv) except TypeError: data = self.struct.pack(rv) elif self.raw: data = rv else: data = bytearray() return prepare(self.type, data) return wrapper class Response: def __init__(self, type_, data, chksum): LOGGER.debug("Response {} {} {}".format(type_, data, chksum)) self.type = type_ self.data = data[1:] self.chksum = chksum self.status = data[0] @property def ok(self): return self.status == 0 def __str__(self): return "Response(type=0x{:02x}, data=0x{}, checksum=0x{:02x})".format( self.type, self.data.hex(), self.chksum, ) def register(type_): assert type_ not in _responses, "Duplicate response type 0x%02x" % type_ def decorator(func): _responses[type_] = func return func return decorator def prepare(type_, data): length = len(data) + 2 checksum = functools.reduce( xor, itertools.chain(type_.to_bytes(2, "big"), length.to_bytes(2, "big"), data), 0, ) message = struct.pack("!BB%dsB" % len(data), length, type_, data, checksum) # print('Prepared command 0x%s' % message.hex()) return message def read_response(ser): length = ser.read() length = int.from_bytes(length, "big") LOGGER.debug("read_response length {}".format(length)) answer = ser.read(length) LOGGER.debug("read_response answer {}".format(answer)) return _unpack_raw_message(length, answer) # type_, data, chksum = struct.unpack('!B%dsB' % (length - 2), answer) # return {'type': type_, 'data': data, 'chksum': chksum} def _unpack_raw_message(length, decoded): LOGGER.debug("unpack raw message {} {}".format(length, decoded)) if len(decoded) != length or length < 2: LOGGER.exception("Unpack failed, length: %d, msg %s" % (length, decoded.hex())) return type_, data, chksum = struct.unpack("!B%dsB" % (length - 2), decoded) return _responses.get(type_, Response)(type_, data, chksum) @Command(0x07) def req_flash_erase(): pass @Command(0x09, raw=True) def req_flash_write(addr, data): msg = struct.pack("<L%ds" % len(data), addr, data) return msg @Command(0x0B, "<LH") def req_flash_read(addr, length): return (addr, length) @Command(0x1F, "<LH") def req_ram_read(addr, length): return (addr, length) @Command(0x25) def req_flash_id(): pass @Command(0x27, "!B") def req_change_baudrate(rate): # print(serial.Serial.BAUDRATES) clockspeed = 1000000 divisor = round(clockspeed / rate) # print(divisor) return divisor @Command(0x2C, "<BL") def req_select_flash_type(type_, custom_jump=0): return (type_, custom_jump) @Command(0x32) def req_chip_id(): pass @Command(0x36, "B") def req_eeprom_erase(pdm_only=False): return not pdm_only @register(0x26) class ReadFlashIDResponse(Response): def __init__(self, *args): super().__init__(*args) self.manufacturer_id, self.device_id = struct.unpack("!BB", self.data) def __str__(self): return ( "ReadFlashIDResponse %d (ok=%s, manufacturer_id=0x%02x, device_id=0x%02x)" % (self.status, self.ok, self.manufacturer_id, self.device_id) ) @register(0x28) class ChangeBaudrateResponse(Response): def __init__(self, *args): super().__init__(*args) def __str__(self): return "ChangeBaudrateResponse %d (ok=%s)" % (self.status, self.ok) @register(0x33) class GetChipIDResponse(Response): def __init__(self, *args): super().__init__(*args) (self.chip_id,) = struct.unpack("!L", self.data) def __str__(self): return "GetChipIDResponse (ok={}, chip_id=0x{:04x})".format( self.ok, self.chip_id ) @register(0x37) class EraseEEPROMResponse(Response): def __init__(self, *args): super().__init__(*args) def __str__(self): return "EraseEEPROMResponse %d (ok=%s)" % (self.status, self.ok) def change_baudrate(ser, baudrate): ser.write(req_change_baudrate(baudrate)) res = read_response(ser) if not res or not res.ok: LOGGER.exception("Change baudrate failed") raise SystemExit(1) ser.baudrate = baudrate def check_chip_id(ser): ser.write(req_chip_id()) res = read_response(ser) if not res or not res.ok: LOGGER.exception("Getting Chip ID failed") raise SystemExit(1) if res.chip_id != ZIGATE_CHIP_ID: LOGGER.exception("This is not a supported chip, patches welcome") raise SystemExit(1) def get_flash_type(ser): ser.write(req_flash_id()) res = read_response(ser) if not res or not res.ok: print("Getting Flash ID failed") raise SystemExit(1) if res.manufacturer_id != 0xCC or res.device_id != 0xEE: print("Unsupported Flash ID, patches welcome") raise SystemExit(1) else: return 8 def get_mac(ser): ser.write(req_ram_read(0x01001570, 8)) res = read_response(ser) if res.data == bytes.fromhex("ffffffffffffffff"): ser.write(req_ram_read(0x01001580, 8)) res = read_response(ser) return ":".join("".join(x) for x in zip(*[iter(res.data.hex())] * 2)) def select_flash(ser, flash_type): ser.write(req_select_flash_type(flash_type)) res = read_response(ser) if not res or not res.ok: print("Selecting flash type failed") raise SystemExit(1) def printProgressBar( iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r", ): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + "-" * (length - filledLength) print("\r{} |{}| {}% {}".format(prefix, bar, percent, suffix), end=printEnd) # Print New Line on Complete if iteration == total: print() def write_flash_to_file(ser, filename): # flash_start = cur = ZIGATE_FLASH_START cur = ZIGATE_FLASH_START flash_end = ZIGATE_FLASH_END LOGGER.info("Backup firmware to %s", filename) with open(filename, "wb") as fd: fd.write(ZIGATE_BINARY_VERSION) read_bytes = 128 while cur < flash_end: if cur + read_bytes > flash_end: read_bytes = flash_end - cur ser.write(req_flash_read(cur, read_bytes)) res = read_response(ser) if not res or not res.ok: print("Reading flash failed") raise SystemExit(1) if cur == 0: (flash_end,) = struct.unpack(">L", res.data[0x20:0x24]) fd.write(res.data) printProgressBar(cur, flash_end, "Reading") cur += read_bytes printProgressBar(flash_end, flash_end, "Reading") LOGGER.info("Backup firmware done") def write_file_to_flash(ser, filename): LOGGER.info("Writing new firmware from %s", filename) with open(filename, "rb") as fd: ser.write(req_flash_erase()) res = read_response(ser) if not res or not res.ok: print("Erasing flash failed") raise SystemExit(1) # flash_start = cur = ZIGATE_FLASH_START cur = ZIGATE_FLASH_START flash_end = ZIGATE_FLASH_END bin_ver = fd.read(4) if bin_ver != ZIGATE_BINARY_VERSION: print("Not a valid image for Zigate") raise SystemExit(1) read_bytes = 128 while cur < flash_end: data = fd.read(read_bytes) if not data: break ser.write(req_flash_write(cur, data)) res = read_response(ser) if not res.ok: print( "writing failed at 0x%08x, status: 0x%x, data: %s" % (cur, res.status, data.hex()) ) raise SystemExit(1) printProgressBar(cur, flash_end, "Writing") cur += read_bytes printProgressBar(flash_end, flash_end, "Writing") LOGGER.info("Writing new firmware done") def erase_EEPROM(ser, pdm_only=False): ser.timeout = 10 # increase timeout because official NXP programmer do it ser.write(req_eeprom_erase(pdm_only)) res = read_response(ser) if not res or not res.ok: print("Erasing EEPROM failed") raise SystemExit(1) def flash(serialport="auto", write=None, save=None, erase=False, pdm_only=False): """ Read or write firmware """ if serialport == "auto": serialport = c.discover_port() try: ser = serial.Serial(serialport, 38400, timeout=5) except serial.SerialException: LOGGER.exception("Could not open serial device %s", serialport) return change_baudrate(ser, 115200) check_chip_id(ser) flash_type = get_flash_type(ser) mac_address = get_mac(ser) LOGGER.info("Found MAC-address: %s", mac_address) if write or save or erase: select_flash(ser, flash_type) if save: write_flash_to_file(ser, save) if write: write_file_to_flash(ser, write) if erase: erase_EEPROM(ser, pdm_only) change_baudrate(ser, 38400) ser.close() def upgrade_firmware(port): backup_filename = "zigate_backup_{:%Y%m%d%H%M%S}.bin".format( datetime.datetime.now() ) flash(port, save=backup_filename) print("ZiGate backup created {}".format(backup_filename)) firmware_path = download_latest() print("Firmware downloaded", firmware_path) flash(port, write=firmware_path) print("ZiGate flashed with {}".format(firmware_path)) def main(): ports_available = [port for (port, _, _) in sorted(comports())] parser = argparse.ArgumentParser() parser.add_argument( "-p", "--serialport", choices=ports_available, help="Serial port, e.g. /dev/ttyUSB0", required=True, ) parser.add_argument("-w", "--write", help="Firmware bin to flash onto the chip") parser.add_argument( "-s", "--save", help="File to save the currently loaded firmware to" ) parser.add_argument( "-u", "--upgrade", help="Download and flash the lastest available firmware", action="store_true", default=False, ) # parser.add_argument('-e', '--erase', help='Erase EEPROM', action='store_true') # parser.add_argument('--pdm-only', help='Erase PDM only, use it with --erase', action='store_true') parser.add_argument( "-d", "--debug", help="Set log level to DEBUG", action="store_true" ) parser.add_argument( "--gpio", help="Configure GPIO for PiZiGate flash", action="store_true", default=False, ) parser.add_argument( "--din", help="Configure USB for ZiGate DIN flash", action="store_true", default=False, ) args = parser.parse_args() LOGGER.setLevel(logging.INFO) if args.debug: LOGGER.setLevel(logging.DEBUG) if args.gpio: c.set_pizigate_flashing_mode() elif args.din: c.set_zigatedin_flashing_mode() if args.upgrade: upgrade_firmware(args.serialport) else: try: ser = serial.Serial(args.serialport, 38400, timeout=5) except serial.SerialException: LOGGER.exception("Could not open serial device %s", args.serialport) raise SystemExit(1) change_baudrate(ser, 115200) check_chip_id(ser) flash_type = get_flash_type(ser) mac_address = get_mac(ser) LOGGER.info("Found MAC-address: %s", mac_address) if args.write or args.save: # or args.erase: select_flash(ser, flash_type) if args.save: write_flash_to_file(ser, args.save) if args.write: write_file_to_flash(ser, args.write) # if args.erase: # erase_EEPROM(ser, args.pdm_only) if args.gpio: c.set_pizigate_running_mode() elif args.din: c.set_zigatedin_running_mode() if __name__ == "__main__": logging.basicConfig() main() 07070100000022000081A4000000000000000000000001655B78D200002BA4000000000000000000000000000000000000002A00000000zigpy-zigate-0.12.0/zigpy_zigate/types.pyimport enum import zigpy.types def deserialize(data, schema): result = [] for type_ in schema: # value, data = type_.deserialize(data) if data: value, data = type_.deserialize(data) else: value = None result.append(value) return result, data def serialize(data, schema): return b"".join(t(v).serialize() for t, v in zip(schema, data)) class Bytes(bytes): def serialize(self): return self @classmethod def deserialize(cls, data): return cls(data), b"" class LBytes(bytes): def serialize(self): return uint8_t(len(self)).serialize() + self @classmethod def deserialize(cls, data, byteorder="big"): _bytes = int.from_bytes(data[:1], byteorder) s = data[1 : _bytes + 1] return s, data[_bytes + 1 :] class int_t(int): _signed = True _size = 0 def serialize(self, byteorder="big"): return self.to_bytes(self._size, byteorder, signed=self._signed) @classmethod def deserialize(cls, data, byteorder="big"): # Work around https://bugs.python.org/issue23640 r = cls(int.from_bytes(data[: cls._size], byteorder, signed=cls._signed)) data = data[cls._size :] return r, data class int8s(int_t): _size = 1 class int16s(int_t): _size = 2 class int24s(int_t): _size = 3 class int32s(int_t): _size = 4 class int40s(int_t): _size = 5 class int48s(int_t): _size = 6 class int56s(int_t): _size = 7 class int64s(int_t): _size = 8 class uint_t(int_t): _signed = False class uint8_t(uint_t): _size = 1 class uint16_t(uint_t): _size = 2 class uint24_t(uint_t): _size = 3 class uint32_t(uint_t): _size = 4 class uint40_t(uint_t): _size = 5 class uint48_t(uint_t): _size = 6 class uint56_t(uint_t): _size = 7 class uint64_t(uint_t): _size = 8 class EUI64(zigpy.types.EUI64): @classmethod def deserialize(cls, data): r, data = super().deserialize(data) return cls(r[::-1]), data def serialize(self): assert self._length == len(self) return super().serialize()[::-1] class NWK(uint16_t): def __repr__(self): return "0x{:04x}".format(self) def __str__(self): return "0x{:04x}".format(self) class AddressMode(uint8_t, enum.Enum): # Address modes used in zigate protocol BOUND = 0x00 GROUP = 0x01 NWK = 0x02 IEEE = 0x03 BROADCAST = 0x04 NO_TRANSMIT = 0x05 BOUND_NO_ACK = 0x06 NWK_NO_ACK = 0x07 IEEE_NO_ACK = 0x08 BOUND_NON_BLOCKING = 0x09 BOUND_NON_BLOCKING_NO_ACK = 0x0A class Status(uint8_t, enum.Enum): Success = 0x00 IncorrectParams = 0x01 UnhandledCommand = 0x02 CommandFailed = 0x03 Busy = 0x04 StackAlreadyStarted = 0x05 # Errors below are due to resource shortage, retrying may succeed OR There are no # free Network PDUs. The number of NPDUs is set in the “Number of NPDUs” property # of the “PDU Manager” section of the config editor ResourceShortage = 0x80 # There are no free Application PDUs. The number of APDUs is set in the “Instances” # property of the appropriate “APDU” child of the “PDU Manager” section of the # config editor NoFreeAppPDUs = 0x81 # There are no free simultaneous data request handles. The number of handles is set # in the “Maximum Number of Simultaneous Data Requests” field of the “APS layer # configuration” section of the config editor NoFreeDataReqHandles = 0x82 # There are no free APS acknowledgement handles. The number of handles is set in # the “Maximum Number of Simultaneous Data Requests with Acks” field of the “APS # layer configuration” section of the config editor NoFreeAPSAckHandles = 0x83 # There are no free fragment record handles. The number of handles is set in # the “Maximum Number of Transmitted Simultaneous Fragmented Messages” field of # the “APS layer configuration” section of the config editor NoFreeFragRecHandles = 0x84 # There are no free MCPS request descriptors. There are 8 MCPS request descriptors. # These are only ever likely to be exhausted under very heavy network load or when # trying to transmit too many frames too close together. NoFreeMCPSReqDesc = 0x85 # The loop back send is currently busy. There can be only one loopback request at a # time. LoopbackSendBusy = 0x86 # There are no free entries in the extended address table. The extended address # table is configured in the config editor NoFreeExtAddrTableEntries = 0x87 # The simple descriptor does not exist for this endpoint / cluster. SimpleDescDoesNotExist = 0x88 # A bad parameter has been found while processing an APSDE request or response BadAPSDEParam = 0x89 # No free Routing table entries left NoFreeRoutingTableEntries = 0x8A # No free BTR entries left. NoFreeBTREntries = 0x8B # A transmit request failed since the ASDU is too large and fragmentation is not # supported. AsduTooLong = 0xA0 # A received fragmented frame could not be defragmented at the current time. DefragDeferred = 0xA1 # A received fragmented frame could not be defragmented since the device does not # support fragmentation. DefragUnsupported = 0xA2 # A parameter value was out of range. IllegalRequest = 0xA3 # An APSME-UNBIND.request failed due to the requested binding link not existing in # the binding table. InvalidBinding = 0xA4 # An APSME-REMOVE-GROUP.request has been issued with a group identifier that does # not appear in the group table. InvalidGroup = 0xA5 # A parameter value was invalid or out of range. InvalidParameter = 0xA6 # An APSDE-DATA.request requesting acknowledged transmission failed due to no # acknowledgement being received. NoAck = 0xA7 # An APSDE-DATA.request with a destination addressing mode set to 0x00 failed due to # there being no devices bound to this device. NoBoundDevice = 0xA8 # An APSDE-DATA.request with a destination addressing mode set to 0x03 failed due to # no corresponding short address found in the address map table. NoShortAddress = 0xA9 # An APSDE-DATA.request with a destination addressing mode set to 0x00 failed due to # a binding table not being supported on the device. NotSupported = 0xAA # An ASDU was received that was secured using a link key. SecuredLinkKey = 0xAB # An ASDU was received that was secured using a network key. SecuredNwkKey = 0xAC # An APSDE-DATA.request requesting security has resulted in an error during the # corresponding security processing. SecurityFail = 0xAD # An APSME-BIND.request or APSME.ADDGROUP.request issued when the binding or group # tables, respectively, were full. TableFull = 0xAE # An ASDU was received without any security. Unsecured = 0xAF # An APSME-GET.request or APSMESET. request has been issued with an unknown # attribute identifier. UnsupportedAttribute = 0xB0 @classmethod def _missing_(cls, value): if not isinstance(value, int): raise ValueError(f"{value} is not a valid {cls.__name__}") new_member = cls._member_type_.__new__(cls, value) new_member._name_ = f"unknown_0x{value:02X}" new_member._value_ = cls._member_type_(value) return new_member class LogLevel(uint8_t, enum.Enum): Emergency = 0 Alert = 1 Critical = 2 Error = 3 Warning = 4 Notice = 5 Information = 6 Debug = 7 class Struct: _fields = [] def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], self.__class__): # copy constructor for field in self._fields: if hasattr(args[0], field[0]): setattr(self, field[0], getattr(args[0], field[0])) elif len(args) == len(self._fields): for arg, field in zip(args, self._fields): setattr(self, field[0], field[1](arg)) elif kwargs: for k, v in kwargs.items(): setattr(self, k, v) def serialize(self): r = b"" for field in self._fields: if hasattr(self, field[0]): r += getattr(self, field[0]).serialize() return r @classmethod def deserialize(cls, data): r = cls() for field_name, field_type in cls._fields: v, data = field_type.deserialize(data) setattr(r, field_name, v) return r, data def __repr__(self): r = "<{} ".format(self.__class__.__name__) r += " ".join( ["{}={}".format(f[0], getattr(self, f[0], None)) for f in self._fields] ) r += ">" return r ZIGPY_TO_ZIGATE_ADDR_MODE = { # With ACKs (zigpy.types.AddrMode.NWK, True): AddressMode.NWK, (zigpy.types.AddrMode.IEEE, True): AddressMode.IEEE, (zigpy.types.AddrMode.Broadcast, True): AddressMode.BROADCAST, (zigpy.types.AddrMode.Group, True): AddressMode.GROUP, # Without ACKs (zigpy.types.AddrMode.NWK, False): AddressMode.NWK_NO_ACK, (zigpy.types.AddrMode.IEEE, False): AddressMode.IEEE_NO_ACK, (zigpy.types.AddrMode.Broadcast, False): AddressMode.BROADCAST, (zigpy.types.AddrMode.Group, False): AddressMode.GROUP, } ZIGATE_TO_ZIGPY_ADDR_MODE = { zigate_addr: (zigpy_addr, ack) for (zigpy_addr, ack), zigate_addr in ZIGPY_TO_ZIGATE_ADDR_MODE.items() } class Address(Struct): _fields = [ ("address_mode", AddressMode), ("address", EUI64), ] def __eq__(self, other): return other.address_mode == self.address_mode and other.address == self.address @classmethod def deserialize(cls, data): r = cls() r.address_mode, data = AddressMode.deserialize(data) if r.address_mode in (AddressMode.IEEE, AddressMode.IEEE_NO_ACK): r.address, data = EUI64.deserialize(data) else: r.address, data = NWK.deserialize(data) return r, data def to_zigpy_type(self): zigpy_addr_mode, ack = ZIGATE_TO_ZIGPY_ADDR_MODE[self.address_mode] return ( zigpy.types.AddrModeAddress( addr_mode=zigpy_addr_mode, address=self.address ), ack, ) class DeviceEntry(Struct): _fields = [ ("id", uint8_t), ("short_addr", NWK), ("ieee_addr", EUI64), ("power_source", uint8_t), ("link_quality", uint8_t), ] class DeviceEntryArray(tuple): @classmethod def deserialize(cls, data): if len(data) % 13 != 0: raise ValueError("Data is not an array of DeviceEntry") entries = [] while data: entry, data = DeviceEntry.deserialize(data) entries.append(entry) return cls(entries), data def serialize(self): return b"".join([e.serialize() for e in self]) 07070100000023000081A4000000000000000000000001655B78D200001594000000000000000000000000000000000000002900000000zigpy-zigate-0.12.0/zigpy_zigate/uart.pyimport asyncio import binascii import logging import struct from typing import Any, Dict import zigpy.serial from . import common as c from .config import CONF_DEVICE_PATH LOGGER = logging.getLogger(__name__) ZIGATE_BAUDRATE = 115200 class Gateway(asyncio.Protocol): START = b"\x01" END = b"\x03" def __init__(self, api, connected_future=None): self._buffer = b"" self._connected_future = connected_future self._api = api def connection_lost(self, exc) -> None: """Port was closed expecteddly or unexpectedly.""" if self._connected_future and not self._connected_future.done(): if exc is None: self._connected_future.set_result(True) else: self._connected_future.set_exception(exc) if exc is None: LOGGER.debug("Closed serial connection") return LOGGER.error("Lost serial connection: %s", exc) self._api.connection_lost(exc) def connection_made(self, transport): """Callback when the uart is connected""" LOGGER.debug("Connection made") self._transport = transport if self._connected_future: self._connected_future.set_result(True) def close(self): if self._transport: self._transport.close() def send(self, cmd, data=b""): """Send data, taking care of escaping and framing""" LOGGER.debug("Send: 0x%04x %s", cmd, binascii.hexlify(data)) length = len(data) byte_head = struct.pack("!HH", cmd, length) checksum = self._checksum(byte_head, data) frame = struct.pack("!HHB%ds" % length, cmd, length, checksum, data) LOGGER.debug("Frame to send: %s", frame) frame = self._escape(frame) LOGGER.debug("Frame escaped: %s", frame) self._transport.write(self.START + frame + self.END) def data_received(self, data): """Callback when there is data received from the uart""" self._buffer += data # LOGGER.debug('data_received %s', self._buffer) endpos = self._buffer.find(self.END) while endpos != -1: startpos = self._buffer.rfind(self.START, 0, endpos) if startpos != -1 and startpos < endpos: frame = self._buffer[startpos : endpos + 1] frame = self._unescape(frame[1:-1]) cmd, length, checksum, f_data, lqi = struct.unpack( "!HHB%dsB" % (len(frame) - 6), frame ) if self._length(frame) != length: LOGGER.warning( "Invalid length: %s, data: %s", length, len(frame) - 6 ) self._buffer = self._buffer[endpos + 1 :] endpos = self._buffer.find(self.END) continue if self._checksum(frame[:4], lqi, f_data) != checksum: LOGGER.warning( "Invalid checksum: %s, data: 0x%s", checksum, binascii.hexlify(frame).decode(), ) self._buffer = self._buffer[endpos + 1 :] endpos = self._buffer.find(self.END) continue LOGGER.debug("Frame received: %s", binascii.hexlify(frame).decode()) self._api.data_received(cmd, f_data, lqi) else: LOGGER.warning("Malformed packet received, ignore it") self._buffer = self._buffer[endpos + 1 :] endpos = self._buffer.find(self.END) def _unescape(self, data): flip = False ret = [] for b in data: if flip: flip = False ret.append(b ^ 0x10) elif b == 0x02: flip = True else: ret.append(b) return bytes(ret) def _escape(self, data): ret = [] for b in data: if b < 0x10: ret.extend([0x02, 0x10 ^ b]) else: ret.append(b) return bytes(ret) def _checksum(self, *args): chcksum = 0 for arg in args: if isinstance(arg, int): chcksum ^= arg continue for x in arg: chcksum ^= x return chcksum def _length(self, frame): length = len(frame) - 5 return length async def connect(device_config: Dict[str, Any], api, loop=None): if loop is None: loop = asyncio.get_event_loop() connected_future = asyncio.Future() protocol = Gateway(api, connected_future) port = device_config[CONF_DEVICE_PATH] if port == "auto": port = c.discover_port() if c.is_pizigate(port): LOGGER.debug("PiZiGate detected") await c.async_set_pizigate_running_mode() # in case of pizigate:/dev/ttyAMA0 syntax if port.startswith("pizigate:"): port = port.replace("pizigate:", "", 1) elif c.is_zigate_din(port): LOGGER.debug("ZiGate USB DIN detected") await c.async_set_zigatedin_running_mode() elif c.is_zigate_wifi(port): LOGGER.debug("ZiGate WiFi detected") _, protocol = await zigpy.serial.create_serial_connection( loop, lambda: protocol, url=port, baudrate=ZIGATE_BAUDRATE, xonxoff=False, ) await connected_future return protocol 07070100000024000041ED000000000000000000000002655B78D200000000000000000000000000000000000000000000002800000000zigpy-zigate-0.12.0/zigpy_zigate/zigbee07070100000025000081A4000000000000000000000001655B78D200000000000000000000000000000000000000000000003400000000zigpy-zigate-0.12.0/zigpy_zigate/zigbee/__init__.py07070100000026000081A4000000000000000000000001655B78D200003050000000000000000000000000000000000000003700000000zigpy-zigate-0.12.0/zigpy_zigate/zigbee/application.pyfrom __future__ import annotations import asyncio import importlib.metadata import logging from typing import Any import zigpy.application import zigpy.config import zigpy.device import zigpy.exceptions import zigpy.types import zigpy.util import zigpy.zdo from zigpy_zigate import common as c, types as t from zigpy_zigate.api import PDM_EVENT, NoResponseError, ResponseId, ZiGate from zigpy_zigate.config import ( CONF_DEVICE, CONF_DEVICE_PATH, CONFIG_SCHEMA, SCHEMA_DEVICE, ) LOGGER = logging.getLogger(__name__) class ControllerApplication(zigpy.application.ControllerApplication): SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE probe = ZiGate.probe def __init__(self, config: dict[str, Any]): super().__init__(zigpy.config.ZIGPY_SCHEMA(config)) self._api: ZiGate | None = None self._pending = {} self._pending_join = [] self.version: str = "" async def connect(self): api = await ZiGate.new(self._config[CONF_DEVICE], self) await api.set_raw_mode() await api.set_time() (_, version), lqi = await api.version() major, minor = version.to_bytes(2, "big") self.version = f"{major:x}.{minor:x}" self._api = api if self.version < "3.21": LOGGER.error( "Old ZiGate firmware detected, you should upgrade to 3.21 or newer" ) async def disconnect(self): # TODO: how do you stop the network? Is it possible? if self._api is not None: try: await self._api.reset(wait=False) except Exception as e: LOGGER.warning("Failed to reset before disconnect: %s", e) finally: self._api.close() self._api = None async def start_network(self): # TODO: how do you start the network? Is it always automatically started? dev = ZiGateDevice(self, self.state.node_info.ieee, self.state.node_info.nwk) self.devices[dev.ieee] = dev await dev.schedule_initialize() async def load_network_info(self, *, load_devices: bool = False): network_state, lqi = await self._api.get_network_state() if not network_state or network_state[3] == 0 or network_state[0] == 0xFFFF: raise zigpy.exceptions.NetworkNotFormed() self.state.node_info = zigpy.state.NodeInfo( nwk=zigpy.types.NWK(network_state[0]), ieee=zigpy.types.EUI64(network_state[1]), logical_type=zigpy.zdo.types.LogicalType.Coordinator, ) epid, _ = zigpy.types.ExtendedPanId.deserialize( zigpy.types.uint64_t(network_state[3]).serialize() ) self.state.network_info = zigpy.state.NetworkInfo( source=f"zigpy-zigate@{importlib.metadata.version('zigpy-zigate')}", extended_pan_id=epid, pan_id=zigpy.types.PanId(network_state[2]), nwk_update_id=0, nwk_manager_id=zigpy.types.NWK(0x0000), channel=network_state[4], channel_mask=zigpy.types.Channels.from_channel_list([network_state[4]]), security_level=5, # TODO: is it possible to read keys? # network_key=zigpy.state.Key(), # tc_link_key=zigpy.state.Key(), children=[], key_table=[], nwk_addresses={}, stack_specific={}, metadata={ "zigate": { "version": self.version, } }, ) self.state.network_info.tc_link_key.partner_ieee = self.state.node_info.ieee if not load_devices: return for device in await self._api.get_devices_list(): if device.power_source != 0: # only battery-powered devices continue ieee = zigpy.types.EUI64(device.ieee_addr) self.state.network_info.children.append(ieee) self.state.network_info.nwk_addresses[ieee] = zigpy.types.NWK( device.short_addr ) async def reset_network_info(self): await self._api.erase_persistent_data() async def write_network_info(self, *, network_info, node_info): LOGGER.warning("Setting the pan_id is not supported by ZiGate") await self.reset_network_info() await self._api.set_channel(network_info.channel) epid, _ = zigpy.types.uint64_t.deserialize( network_info.extended_pan_id.serialize() ) await self._api.set_extended_panid(epid) network_formed, lqi = await self._api.start_network() if network_formed[0] not in ( t.Status.Success, t.Status.IncorrectParams, t.Status.Busy, ): raise zigpy.exceptions.FormationFailure( f"Unexpected error starting network: {network_formed!r}" ) LOGGER.warning("Starting network got status %s, wait...", network_formed[0]) for attempt in range(3): await asyncio.sleep(1) try: await self.load_network_info() except zigpy.exceptions.NetworkNotFormed as e: if attempt == 2: raise zigpy.exceptions.FormationFailure() from e async def permit_with_link_key(self, node, link_key, time_s=60): LOGGER.warning("ZiGate does not support joins with link keys") async def _move_network_to_channel( self, new_channel: int, *, new_nwk_update_id: int ) -> None: """Moves the network to a new channel.""" await self._api.set_channel(new_channel) async def energy_scan( self, channels: zigpy.types.Channels, duration_exp: int, count: int ) -> dict[int, float]: """Runs an energy detection scan and returns the per-channel scan results.""" LOGGER.warning("Coordinator does not support energy scanning") return {c: 0 for c in channels} async def force_remove(self, dev): await self._api.remove_device(self.state.node_info.ieee, dev.ieee) async def add_endpoint(self, descriptor): # ZiGate does not support adding new endpoints pass def zigate_callback_handler(self, msg, response, lqi): LOGGER.debug("zigate_callback_handler %s %s", msg, response) if msg == ResponseId.LEAVE_INDICATION: nwk = 0 ieee = zigpy.types.EUI64(response[0]) self.handle_leave(nwk, ieee) elif msg == ResponseId.DEVICE_ANNOUNCE: nwk = response[0] ieee = zigpy.types.EUI64(response[1]) parent_nwk = 0 self.handle_join(nwk, ieee, parent_nwk) # Temporary disable two stages pairing due to firmware bug # rejoin = response[3] # if nwk in self._pending_join or rejoin: # LOGGER.debug('Finish pairing {} (2nd device announce)'.format(nwk)) # if nwk in self._pending_join: # self._pending_join.remove(nwk) # self.handle_join(nwk, ieee, parent_nwk) # else: # LOGGER.debug('Start pairing {} (1st device announce)'.format(nwk)) # self._pending_join.append(nwk) elif msg == ResponseId.DATA_INDICATION: ( status, profile_id, cluster_id, src_ep, dst_ep, src, dst, payload, ) = response packet = zigpy.types.ZigbeePacket( src=src.to_zigpy_type()[0], src_ep=src_ep, dst=dst.to_zigpy_type()[0], dst_ep=dst_ep, profile_id=profile_id, cluster_id=cluster_id, data=zigpy.types.SerializableBytes(payload), lqi=lqi, rssi=None, ) self.packet_received(packet) elif msg == ResponseId.ACK_DATA: LOGGER.debug("ACK Data received %s %s", response[4], response[0]) # disabled because of https://github.com/fairecasoimeme/ZiGate/issues/324 # self._handle_frame_failure(response[4], response[0]) elif msg == ResponseId.APS_DATA_CONFIRM: LOGGER.debug( "ZPS Event APS data confirm, message routed to %s %s", response[3], response[0], ) elif msg == ResponseId.PDM_EVENT: try: event = PDM_EVENT(response[0]).name except ValueError: event = "Unknown event" LOGGER.debug("PDM Event %s %s, record %s", response[0], event, response[1]) elif msg == ResponseId.APS_DATA_CONFIRM_FAILED: LOGGER.debug("APS Data confirm Fail %s %s", response[4], response[0]) self._handle_frame_failure(response[4], response[0]) elif msg == ResponseId.EXTENDED_ERROR: LOGGER.warning("Extended error code %s", response[0]) def _handle_frame_failure(self, message_tag, status): try: send_fut = self._pending.pop(message_tag) send_fut.set_result(status) except KeyError: LOGGER.warning("Unexpected message send failure") except asyncio.futures.InvalidStateError as exc: LOGGER.debug( "Invalid state on future - probably duplicate response: %s", exc ) async def send_packet(self, packet): LOGGER.debug("Sending packet %r", packet) # Firmwares 3.1d and below allow a couple of _NO_ACK packets to send but all # subsequent ones will fail. ACKs must be enabled. ack = ( zigpy.types.TransmitOptions.ACK in packet.tx_options or self.version <= "3.1d" ) try: (status, tsn, packet_type, _), _ = await self._api.raw_aps_data_request( addr=packet.dst.address, src_ep=( 1 if packet.dst_ep is None or packet.dst_ep > 0 else 0 ), # ZiGate only support endpoint 1 dst_ep=packet.dst_ep or 0, profile=packet.profile_id, cluster=packet.cluster_id, payload=packet.data.serialize(), addr_mode=t.ZIGPY_TO_ZIGATE_ADDR_MODE[packet.dst.addr_mode, ack], radius=packet.radius, ) except NoResponseError: raise zigpy.exceptions.DeliveryError("ZiGate did not respond to command") self._pending[tsn] = asyncio.get_running_loop().create_future() if status != t.Status.Success: self._pending.pop(tsn) # Firmwares 3.1d and below fail to send packets on every request if status == t.Status.InvalidParameter and self.version <= "3.1d": pass else: raise zigpy.exceptions.DeliveryError( f"Failed to send packet: {status!r}", status=status ) # disabled because of https://github.com/fairecasoimeme/ZiGate/issues/324 # try: # v = await asyncio.wait_for(send_fut, 120) # except asyncio.TimeoutError: # return 1, "timeout waiting for message %s send ACK" % (sequence, ) # finally: # self._pending.pop(tsn) # return v, "Message sent" async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 status, lqi = await self._api.permit_join(time_s) if status[0] != t.Status.Success: await self._api.reset() class ZiGateDevice(zigpy.device.Device): def __init__(self, application, ieee, nwk): """Initialize instance.""" super().__init__(application, ieee, nwk) port = application._config[CONF_DEVICE][CONF_DEVICE_PATH] model = "ZiGate USB-TTL" if c.is_zigate_wifi(port): model = "ZiGate WiFi" elif c.is_pizigate(port): model = "PiZiGate" elif c.is_zigate_din(port): model = "ZiGate USB-DIN" self._model = f"{model} {application.version}" @property def manufacturer(self): return "ZiGate" @property def model(self): return self._model 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!295 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor