pax_global_header00006660000000000000000000000064147100107720014511gustar00rootroot0000000000000052 comment=c2d2f5b18ba65f5f4d26e44bddc228c3cd7db38f zigpy-xbee-0.21.0/000077500000000000000000000000001471001077200136545ustar00rootroot00000000000000zigpy-xbee-0.21.0/.coveragerc000066400000000000000000000000321471001077200157700ustar00rootroot00000000000000[run] source = zigpy_xbee zigpy-xbee-0.21.0/.github/000077500000000000000000000000001471001077200152145ustar00rootroot00000000000000zigpy-xbee-0.21.0/.github/workflows/000077500000000000000000000000001471001077200172515ustar00rootroot00000000000000zigpy-xbee-0.21.0/.github/workflows/ci.yml000066400000000000000000000006241471001077200203710ustar00rootroot00000000000000name: 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_xbee CACHE_VERSION: 2 PYTHON_VERSION_DEFAULT: 3.9.15 PRE_COMMIT_CACHE_PATH: ~/.cache/pre-commit MINIMUM_COVERAGE_PERCENTAGE: 100 secrets: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} zigpy-xbee-0.21.0/.github/workflows/matchers/000077500000000000000000000000001471001077200210575ustar00rootroot00000000000000zigpy-xbee-0.21.0/.github/workflows/matchers/codespell.json000066400000000000000000000004001471001077200237160ustar00rootroot00000000000000{ "problemMatcher": [ { "owner": "codespell", "severity": "warning", "pattern": [ { "regexp": "^(.+):(\\d+):\\s(.+)$", "file": 1, "line": 2, "message": 3 } ] } ] } zigpy-xbee-0.21.0/.github/workflows/matchers/flake8.json000066400000000000000000000011011471001077200231150ustar00rootroot00000000000000{ "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 } ] } ] } zigpy-xbee-0.21.0/.github/workflows/matchers/python.json000066400000000000000000000005201471001077200232700ustar00rootroot00000000000000{ "problemMatcher": [ { "owner": "python", "pattern": [ { "regexp": "^\\s*File\\s\\\"(.*)\\\",\\sline\\s(\\d+),\\sin\\s(.*)$", "file": 1, "line": 2 }, { "regexp": "^\\s*raise\\s(.*)\\(\\'(.*)\\'\\)$", "message": 2 } ] } ] } zigpy-xbee-0.21.0/.github/workflows/publish-to-pypi.yml000066400000000000000000000003611471001077200230410ustar00rootroot00000000000000name: 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 }} zigpy-xbee-0.21.0/.gitignore000066400000000000000000000015021471001077200156420ustar00rootroot00000000000000# 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 tags # Visual Studio Code .vscode zigpy-xbee-0.21.0/.pre-commit-config.yaml000066400000000000000000000026051471001077200201400ustar00rootroot00000000000000repos: - repo: https://github.com/asottile/pyupgrade rev: v3.15.0 hooks: - id: pyupgrade args: [--py38-plus] - repo: https://github.com/PyCQA/autoflake rev: v2.2.1 hooks: - id: autoflake - repo: https://github.com/psf/black rev: 23.9.1 hooks: - id: black args: - --quiet - --safe - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 additional_dependencies: - flake8-docstrings==1.7.0 - pydocstyle==6.3.0 - Flake8-pyproject==1.2.3 - flake8-bugbear==23.9.16 - flake8-comprehensions==3.14.0 - flake8_2020==1.8.1 - mccabe==0.7.0 - pycodestyle==2.11.0 - pyflakes==3.1.0 - flake8-async==22.11.14 - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort - repo: https://github.com/codespell-project/codespell rev: v2.2.6 hooks: - id: codespell args: - --ignore-words-list=ser,nd,hass - --skip="./.*" - --quiet-level=2 - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.6.0 hooks: - id: mypy additional_dependencies: - zigpy - repo: https://github.com/charliermarsh/ruff-pre-commit rev: v0.0.291 hooks: - id: ruff args: - --fix zigpy-xbee-0.21.0/COPYING000066400000000000000000000012221471001077200147040ustar00rootroot00000000000000zigpy-xbee Copyright (C) 2018 Russell Cloran 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 . zigpy-xbee-0.21.0/Contributors.md000066400000000000000000000003521471001077200166730ustar00rootroot00000000000000# Contributors - [Alexei Chetroi] (https://github.com/Adminiuga) - [Russell Cloran] (https://github.com/rcloran) - [damarco] (https://github.com/damarco) - [Hedda] (https://github.com/Hedda) - [Shulyaka] (https://github.com/Shulyaka) zigpy-xbee-0.21.0/LICENSE000066400000000000000000001045131471001077200146650ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . zigpy-xbee-0.21.0/README.md000066400000000000000000000127661471001077200151470ustar00rootroot00000000000000# zigpy-xbee [![Build Status](https://github.com/zigpy/zigpy-xbee/workflows/CI/badge.svg)](https://github.com/zigpy/zigpy-xbee/actions) [![Coverage Status](https://codecov.io/gh/zigpy/zigpy-xbee/branch/dev/graph/badge.svg?token=Y1994N9D74)](https://codecov.io/gh/zigpy/zigpy-xbee) [zigpy-xbee](https://github.com/zigpy/zigpy-xbee/) is a Python implementation for the [Zigpy](https://github.com/zigpy/) project to implement [XBee](https://en.wikipedia.org/wiki/XBee) based [Zigbee](https://www.zigbee.org) radio devices from Digi. - https://github.com/zigpy/zigpy-xbee Digi XBee is the brand name of a family of form factor compatible radio modules from Digi International. The XBee radios can all be used with the minimum number of connections — power (3.3 V), ground, data in and data out (UART), with other recommended lines being Reset and Sleep.[5] Additionally, most XBee families have some other flow control, input/output (I/O), analog-to-digital converter (A/D) and indicator lines built in. - https://en.wikipedia.org/wiki/XBee Zigbee Home Automation integration with **[zigpy](https://github.com/zigpy/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, including this **[zigpy-xbee](https://github.com/zigpy/zigpy-xbee/)** library for Xbee based Zigbee radio modules. [zigpy](https://github.com/zigpy/zigpy/)** currently has 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/)** ## Compatible hardware zigpy works with separate radio libraries which can each interface with multiple USB and GPIO radio hardware adapters/modules over different native UART serial protocols. Such radio libraries includes **[zigpy-xbee](https://github.com/zigpy/zigpy-xbee)** (which communicates with XBee based Zigbee radios), **[bellows](https://github.com/zigpy/bellows)** (which communicates with EZSP/EmberZNet based radios), and as **[zigpy-deconz](https://github.com/zigpy/zigpy-deconz)** for deCONZ serial protocol (for communicating with ConBee and RaspBee USB and GPIO radios from Dresden-Elektronik). There are also an experimental radio library called **[zigpy-zigate](https://github.com/doudz/zigpy-zigate)** for communicating with ZiGate based radios. ### Known working XBee based Zigbee radio modules for Zigpy These are XBee Zigbee based radios that have been tested with the [zigpy-xbee](https://github.com/zigpy/zigpy-xbee) library for zigpy - [Digi XBee Series 3 (xbee3-24)](https://www.digi.com/products/embedded-systems/digi-xbee/rf-modules/2-4-ghz-rf-modules/xbee3-zigbee-3) and [Digi XBee Series S2C](https://www.digi.com/products/embedded-systems/digi-xbee/rf-modules/2-4-ghz-rf-modules/xbee-zigbee) modules - Note! While not a must, [it is recommend to upgrade XBee Series 3 and S2C to newest firmware firmware using XCTU](https://www.digi.com/resources/documentation/Digidocs/90002002/Default.htm#Tasks/t_load_zb_firmware.htm) - [Digi XBee Series 2 (S2)](https://www.digi.com/support/productdetail?pid=3430) modules (Note! This first have to be [flashed with Zigbee Coordinator API firmware](https://www.digi.com/support/productdetail?pid=3430)) # Port configuration - To configure __usb__ port path for your XBee serial device, just specify the TTY (serial com) port, example : `/dev/ttyACM0` Note! Users can change UART baud rate of your Digi XBee using the Digi's XCTU configuration tool. Using XCTU tool enable the API communication mode -- `ATAP2`, set baudrate to 57600 -- `ATBD6`, save parameters. # Testing new releases Testing a new release of the zigpy-xbee 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-xbee==0.12.0 apk: [] ``` where 0.12.0 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-xbee==0.12.0 # Releases of zigpy-xbee via PyPI New packages of tagged versions are also released via the "zigpy-xbee" project on PyPI - https://pypi.org/project/zigpy-xbee/ - https://pypi.org/project/zigpy-xbee/#history - https://pypi.org/project/zigpy-xbee/#files Older packages of tagged versions are still available on the "zigpy-xbee-homeassistant" project on PyPI - https://pypi.org/project/zigpy-xbee-homeassistant/ # 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. zigpy-xbee-0.21.0/pyproject.toml000066400000000000000000000026001471001077200165660ustar00rootroot00000000000000[build-system] requires = ["setuptools>=61.0.0", "wheel", "setuptools-git-versioning<2"] build-backend = "setuptools.build_meta" [project] name = "zigpy-xbee" dynamic = ["version"] description = "A library which communicates with XBee radios for zigpy" urls = {repository = "https://github.com/zigpy/zigpy-xbee"} authors = [ {name = "Russell Cloran", email = "rcloran@gmail.com"} ] readme = "README.md" license = {text = "GPL-3.0"} requires-python = ">=3.8" dependencies = [ "zigpy>=0.70.0", ] [tool.setuptools.packages.find] exclude = ["tests", "tests.*"] [project.optional-dependencies] testing = [ "pytest>=7.1.2", "asynctest>=0.13.0", "pytest-asyncio>=0.19.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_xbee", "tests"] forced_separate = "tests" combine_as_imports = true [tool.mypy] ignore_errors = true [tool.pytest.ini_options] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" [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 ':' # D202 No blank lines allowed after function docstring ignore = ["W503", "E203", "D202"] zigpy-xbee-0.21.0/requirements_test.txt000066400000000000000000000003431471001077200201770ustar00rootroot00000000000000# Test dependencies. asynctest isort black flake8 codecov colorlog codespell mypy==1.6.0 pre-commit pylint pytest-cov pytest-sugar pytest-timeout pytest-asyncio>=0.17 pytest>=7.1.3 zigpy>=0.56.0 ruff>=0.0.291 Flake8-pyproject zigpy-xbee-0.21.0/setup.py000066400000000000000000000001521471001077200153640ustar00rootroot00000000000000"""Setup stub for legacy builds.""" import setuptools if __name__ == "__main__": setuptools.setup() zigpy-xbee-0.21.0/tests/000077500000000000000000000000001471001077200150165ustar00rootroot00000000000000zigpy-xbee-0.21.0/tests/__init__.py000066400000000000000000000000341471001077200171240ustar00rootroot00000000000000"""Tests for zigpy_xbee.""" zigpy-xbee-0.21.0/tests/test_api.py000066400000000000000000000501071471001077200172030ustar00rootroot00000000000000"""Tests for API.""" import asyncio from unittest import mock import pytest import zigpy.config import zigpy.exceptions import zigpy.types as t from zigpy_xbee import api as xbee_api, types as xbee_t from zigpy_xbee.exceptions import ATCommandError, ATCommandException, InvalidCommand from zigpy_xbee.zigbee.application import ControllerApplication DEVICE_CONFIG = zigpy.config.SCHEMA_DEVICE( { zigpy.config.CONF_DEVICE_PATH: "/dev/null", zigpy.config.CONF_DEVICE_BAUDRATE: 57600, } ) @pytest.fixture def api(): """Sample XBee API fixture.""" api = xbee_api.XBee(DEVICE_CONFIG) api._uart = mock.AsyncMock() return api async def test_connect(): """Test connect.""" api = xbee_api.XBee(DEVICE_CONFIG) api._command = mock.AsyncMock(spec=api._command) with mock.patch("zigpy_xbee.uart.connect"): await api.connect() async def test_connect_initial_timeout_success(): """Test connect, initial command times out.""" api = xbee_api.XBee(DEVICE_CONFIG) api._at_command = mock.AsyncMock(side_effect=asyncio.TimeoutError) api.init_api_mode = mock.AsyncMock(return_value=True) with mock.patch("zigpy_xbee.uart.connect"): await api.connect() async def test_connect_initial_timeout_failure(): """Test connect, initial command times out.""" api = xbee_api.XBee(DEVICE_CONFIG) api._at_command = mock.AsyncMock(side_effect=asyncio.TimeoutError) api.init_api_mode = mock.AsyncMock(return_value=False) with mock.patch("zigpy_xbee.uart.connect") as mock_connect: with pytest.raises(zigpy.exceptions.APIException): await api.connect() assert mock_connect.return_value.disconnect.mock_calls == [mock.call()] async def test_disconnect(api): """Test connection close.""" uart = api._uart await api.disconnect() assert api._uart is None assert uart.disconnect.call_count == 1 def test_commands(): """Test command requests and command responses description.""" import string anum = string.ascii_letters + string.digits + "_" commands = {**xbee_api.COMMAND_REQUESTS, **xbee_api.COMMAND_RESPONSES} for cmd_name, cmd_opts in commands.items(): assert isinstance(cmd_name, str) is True assert all(c in anum for c in cmd_name), cmd_name assert len(cmd_opts) == 3 cmd_id, schema, reply = cmd_opts assert isinstance(cmd_id, int) is True assert isinstance(schema, tuple) is True assert reply is None or isinstance(reply, int) async def test_command(api): """Test AT commands.""" def mock_api_frame(name, *args): c = xbee_api.COMMAND_REQUESTS[name] return mock.sentinel.api_frame_data, c[2] api._api_frame = mock.MagicMock(side_effect=mock_api_frame) api._uart.send = mock.MagicMock() for cmd_name, cmd_opts in xbee_api.COMMAND_REQUESTS.items(): cmd_id, schema, expect_reply = cmd_opts ret = api._command(cmd_name, mock.sentinel.cmd_data) if expect_reply: assert asyncio.isfuture(ret) is True ret.cancel() else: assert ret is None assert api._api_frame.call_count == 1 assert api._api_frame.call_args[0][0] == cmd_name assert api._api_frame.call_args[0][1] == api._seq - 1 assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data assert api._uart.send.call_count == 1 assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data api._api_frame.reset_mock() api._uart.send.reset_mock() ret = api._command(cmd_name, mock.sentinel.cmd_data, mask_frame_id=True) assert ret is None assert api._api_frame.call_count == 1 assert api._api_frame.call_args[0][0] == cmd_name assert api._api_frame.call_args[0][1] == 0 assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data assert api._uart.send.call_count == 1 assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data api._api_frame.reset_mock() api._uart.send.reset_mock() async def test_command_not_connected(api): """Test AT command while disconnected to the device.""" api._uart = None def mock_api_frame(name, *args): return mock.sentinel.api_frame_data, api._seq api._api_frame = mock.MagicMock(side_effect=mock_api_frame) for cmd, _cmd_opts in xbee_api.COMMAND_REQUESTS.items(): with pytest.raises(zigpy.exceptions.APIException): await api._command(cmd, mock.sentinel.cmd_data) assert api._api_frame.call_count == 0 api._api_frame.reset_mock() async def _test_at_or_queued_at_command(api, cmd, monkeypatch, do_reply=True): monkeypatch.setattr( t, "serialize", mock.MagicMock(return_value=mock.sentinel.serialize) ) """Call api._at_command() or api._queued_at() with every possible command.""" def mock_command(name, *args): rsp = xbee_api.COMMAND_REQUESTS[name][2] ret = None if rsp: ret = asyncio.Future() if do_reply: ret.set_result(mock.sentinel.at_result) return ret api._command = mock.MagicMock(side_effect=mock_command) api._seq = mock.sentinel.seq for at_cmd in xbee_api.AT_COMMANDS: res = await cmd(at_cmd, mock.sentinel.args) assert t.serialize.call_count == 1 assert api._command.call_count == 1 assert api._command.call_args[0][0] in ("at", "queued_at") assert api._command.call_args[0][1] == at_cmd.encode("ascii") assert api._command.call_args[0][2] == mock.sentinel.serialize assert res == mock.sentinel.at_result t.serialize.reset_mock() api._command.reset_mock() async def test_at_command(api, monkeypatch): """Test api._at_command.""" await _test_at_or_queued_at_command(api, api._at_command, monkeypatch) async def test_at_command_no_response(api, monkeypatch): """Test api._at_command with no response.""" with pytest.raises(asyncio.TimeoutError): await _test_at_or_queued_at_command( api, api._at_command, monkeypatch, do_reply=False ) async def test_queued_at_command(api, monkeypatch): """Test api._queued_at.""" await _test_at_or_queued_at_command(api, api._queued_at, monkeypatch) async def _test_remote_at_command(api, monkeypatch, do_reply=True): monkeypatch.setattr( t, "serialize", mock.MagicMock(return_value=mock.sentinel.serialize) ) """Call api._remote_at_command().""" def mock_command(name, *args): rsp = xbee_api.COMMAND_REQUESTS[name][2] ret = None if rsp: ret = asyncio.Future() if do_reply: ret.set_result(mock.sentinel.at_result) return ret api._command = mock.MagicMock(side_effect=mock_command) api._seq = mock.sentinel.seq for at_cmd in xbee_api.AT_COMMANDS: res = await api._remote_at_command( mock.sentinel.ieee, mock.sentinel.nwk, mock.sentinel.opts, at_cmd, mock.sentinel.args, ) assert t.serialize.call_count == 1 assert api._command.call_count == 1 assert api._command.call_args[0][0] == "remote_at" assert api._command.call_args[0][1] == mock.sentinel.ieee assert api._command.call_args[0][2] == mock.sentinel.nwk assert api._command.call_args[0][3] == mock.sentinel.opts assert api._command.call_args[0][4] == at_cmd.encode("ascii") assert api._command.call_args[0][5] == mock.sentinel.serialize assert res == mock.sentinel.at_result t.serialize.reset_mock() api._command.reset_mock() async def test_remote_at_cmd(api, monkeypatch): """Test remote AT command.""" await _test_remote_at_command(api, monkeypatch) async def test_remote_at_cmd_no_rsp(api, monkeypatch): """Test remote AT command with no response.""" monkeypatch.setattr(xbee_api, "REMOTE_AT_COMMAND_TIMEOUT", 0.1) with pytest.raises(asyncio.TimeoutError): await _test_remote_at_command(api, monkeypatch, do_reply=False) def test_api_frame(api): """Test api._api_frame.""" ieee = t.EUI64([t.uint8_t(a) for a in range(0, 8)]) for cmd_name, cmd_opts in xbee_api.COMMAND_REQUESTS.items(): cmd_id, schema, repl = cmd_opts if schema: args = [ieee if issubclass(a, t.EUI64) else a() for a in schema] frame, repl = api._api_frame(cmd_name, *args) else: frame, repl = api._api_frame(cmd_name) def test_frame_received(api, monkeypatch): """Test api.frame_received().""" monkeypatch.setattr( t, "deserialize", mock.MagicMock( return_value=( [ mock.sentinel.arg_0, mock.sentinel.arg_1, mock.sentinel.arg_2, mock.sentinel.arg_3, mock.sentinel.arg_4, mock.sentinel.arg_5, mock.sentinel.arg_6, mock.sentinel.arg_7, mock.sentinel.arg_8, ], b"", ) ), ) my_handler = mock.MagicMock() for cmd, cmd_opts in xbee_api.COMMAND_RESPONSES.items(): cmd_id = cmd_opts[0] payload = b"\x01\x02\x03\x04" data = cmd_id.to_bytes(1, "big") + payload setattr(api, f"_handle_{cmd}", my_handler) api.frame_received(data) assert t.deserialize.call_count == 1 assert t.deserialize.call_args[0][0] == payload assert my_handler.call_count == 1 assert my_handler.call_args[0][0] == mock.sentinel.arg_0 assert my_handler.call_args[0][1] == mock.sentinel.arg_1 assert my_handler.call_args[0][2] == mock.sentinel.arg_2 assert my_handler.call_args[0][3] == mock.sentinel.arg_3 t.deserialize.reset_mock() my_handler.reset_mock() def test_frame_received_no_handler(api, monkeypatch): """Test frame received with no handler defined.""" monkeypatch.setattr( t, "deserialize", mock.MagicMock(return_value=(b"deserialized data", b"")) ) my_handler = mock.MagicMock() cmd = "no_handler" cmd_id = 0x00 xbee_api.COMMAND_RESPONSES[cmd] = (cmd_id, (), None) api._commands_by_id[cmd_id] = cmd cmd_opts = xbee_api.COMMAND_RESPONSES[cmd] cmd_id = cmd_opts[0] payload = b"\x01\x02\x03\x04" data = cmd_id.to_bytes(1, "big") + payload api.frame_received(data) assert t.deserialize.call_count == 1 assert t.deserialize.call_args[0][0] == payload assert my_handler.call_count == 0 def _handle_at_response(api, tsn, status, at_response=b""): """Call api._handle_at_response.""" data = (tsn, b"AI", status, at_response) response = asyncio.Future() api._awaiting[tsn] = (response,) api._handle_at_response(*data) return response def test_handle_at_response_none(api): """Test AT successful response with no value.""" tsn = 123 fut = _handle_at_response(api, tsn, 0) assert fut.done() is True assert fut.result() is None assert fut.exception() is None def test_handle_at_response_data(api): """Test AT successful response with data.""" tsn = 123 status, response = 0, 0x23 fut = _handle_at_response(api, tsn, status, [response]) assert fut.done() is True assert fut.result() == response assert fut.exception() is None def test_handle_at_response_error(api): """Test AT unsuccessful response.""" tsn = 123 status, response = 1, 0x23 fut = _handle_at_response(api, tsn, status, [response]) assert fut.done() is True assert isinstance(fut.exception(), ATCommandError) def test_handle_at_response_invalid_command(api): """Test invalid AT command response.""" tsn = 123 status, response = 2, 0x23 fut = _handle_at_response(api, tsn, status, [response]) assert fut.done() is True assert isinstance(fut.exception(), InvalidCommand) def test_handle_at_response_undef_error(api): """Test AT unsuccessful response with undefined error.""" tsn = 123 status, response = 0xEE, 0x23 fut = _handle_at_response(api, tsn, status, [response]) assert fut.done() is True assert isinstance(fut.exception(), ATCommandException) def test_handle_remote_at_rsp(api): """Test handling the response.""" api._handle_at_response = mock.MagicMock() s = mock.sentinel api._handle_remote_at_response(s.frame_id, s.ieee, s.nwk, s.cmd, s.status, s.data) assert api._handle_at_response.call_count == 1 assert api._handle_at_response.call_args[0][0] == s.frame_id assert api._handle_at_response.call_args[0][1] == s.cmd assert api._handle_at_response.call_args[0][2] == s.status assert api._handle_at_response.call_args[0][3] == s.data def _send_modem_event(api, event): """Call api._handle_modem_status().""" api._app = mock.MagicMock(spec=ControllerApplication) api._handle_modem_status(event) assert api._app.handle_modem_status.call_count == 1 assert api._app.handle_modem_status.call_args[0][0] == event def test_handle_modem_status(api): """Test api._handle_modem_status().""" api._running.clear() api._reset.set() _send_modem_event(api, xbee_t.ModemStatus.COORDINATOR_STARTED) assert api.is_running is True assert api.reset_event.is_set() is True api._running.set() api._reset.set() _send_modem_event(api, xbee_t.ModemStatus.DISASSOCIATED) assert api.is_running is False assert api.reset_event.is_set() is True api._running.set() api._reset.clear() _send_modem_event(api, xbee_t.ModemStatus.HARDWARE_RESET) assert api.is_running is False assert api.reset_event.is_set() is True def test_handle_explicit_rx_indicator(api): """Test receiving explicit_rx_indicator frame.""" s = mock.sentinel data = [ s.src_ieee, s.src_nwk, s.src_ep, s.dst_ep, s.cluster_id, s.profile, s.opts, b"abcdef", ] api._app = mock.MagicMock() api._app.handle_rx = mock.MagicMock() api._handle_explicit_rx_indicator(*data) assert api._app.handle_rx.call_count == 1 def _handle_tx_status(api, status, wrong_frame_id=False): """Call api._handle_tx_status.""" status = xbee_t.TXStatus(status) frame_id = 0x12 send_fut = mock.MagicMock(spec=asyncio.Future) api._awaiting[frame_id] = (send_fut,) s = mock.sentinel if wrong_frame_id: frame_id += 1 api._handle_tx_status( frame_id, s.dst_nwk, s.retries, status, xbee_t.DiscoveryStatus() ) return send_fut def test_handle_tx_status_success(api): """Test handling successful TX Status.""" fut = _handle_tx_status(api, xbee_t.TXStatus.SUCCESS) assert len(api._awaiting) == 0 assert fut.set_result.call_count == 1 assert fut.set_exception.call_count == 0 def test_handle_tx_status_except(api): """Test exceptional TXStatus.""" fut = _handle_tx_status(api, xbee_t.TXStatus.ADDRESS_NOT_FOUND) assert len(api._awaiting) == 0 assert fut.set_result.call_count == 0 assert fut.set_exception.call_count == 1 def test_handle_tx_status_unexpected(api): """Test TX status reply on unexpected frame.""" fut = _handle_tx_status(api, 1, wrong_frame_id=True) assert len(api._awaiting) == 1 assert fut.set_result.call_count == 0 assert fut.set_exception.call_count == 0 def test_handle_tx_status_duplicate(api): """Test TX status duplicate reply.""" status = xbee_t.TXStatus.SUCCESS frame_id = 0x12 send_fut = mock.MagicMock(spec=asyncio.Future) send_fut.set_result.side_effect = asyncio.InvalidStateError api._awaiting[frame_id] = (send_fut,) s = mock.sentinel api._handle_tx_status(frame_id, s.dst_nwk, s.retries, status, s.disc) assert len(api._awaiting) == 0 assert send_fut.set_result.call_count == 1 assert send_fut.set_exception.call_count == 0 def test_handle_registration_status(api): """Test device registration status.""" frame_id = 0x12 status = xbee_t.RegistrationStatus.SUCCESS fut = asyncio.Future() api._awaiting[frame_id] = (fut,) api._handle_registration_status(frame_id, status) assert fut.done() is True assert fut.result() == xbee_t.RegistrationStatus.SUCCESS assert fut.exception() is None frame_id = 0x13 status = xbee_t.RegistrationStatus.KEY_TABLE_IS_FULL fut = asyncio.Future() api._awaiting[frame_id] = (fut,) api._handle_registration_status(frame_id, status) assert fut.done() is True with pytest.raises(RuntimeError, match="Registration Status: KEY_TABLE_IS_FULL"): fut.result() async def test_command_mode_at_cmd(api): """Test AT in command mode.""" command = "+++" def cmd_mode_send(cmd): api._cmd_mode_future.set_result(True) api._uart.command_mode_send = cmd_mode_send result = await api.command_mode_at_cmd(command) assert result async def test_command_mode_at_cmd_timeout(api): """Test AT in command mode with timeout.""" command = "+++" api._uart.command_mode_send = mock.MagicMock() result = await api.command_mode_at_cmd(command) assert result is None def test_handle_command_mode_rsp(api): """Test command mode response.""" api._cmd_mode_future = None data = "OK" api.handle_command_mode_rsp(data) api._cmd_mode_future = asyncio.Future() api.handle_command_mode_rsp(data) assert api._cmd_mode_future.done() assert api._cmd_mode_future.result() is True api._cmd_mode_future = asyncio.Future() api.handle_command_mode_rsp("ERROR") assert api._cmd_mode_future.done() assert api._cmd_mode_future.result() is False data = "Hello" api._cmd_mode_future = asyncio.Future() api.handle_command_mode_rsp(data) assert api._cmd_mode_future.done() assert api._cmd_mode_future.result() == data async def test_enter_at_command_mode(api): """Test switching to command mode.""" api.command_mode_at_cmd = mock.AsyncMock(return_value=mock.sentinel.at_response) res = await api.enter_at_command_mode() assert res == mock.sentinel.at_response async def test_api_mode_at_commands(api): """Test AT in API mode.""" api.command_mode_at_cmd = mock.AsyncMock(return_value=mock.sentinel.api_mode) res = await api.api_mode_at_commands(57600) assert res is True async def mock_at_cmd(cmd): if cmd == "ATWR\r": return False return True api.command_mode_at_cmd = mock_at_cmd res = await api.api_mode_at_commands(57600) assert res is None async def test_init_api_mode(api, monkeypatch): """Test init the API mode.""" monkeypatch.setattr(api._uart, "baudrate", 57600) api.enter_at_command_mode = mock.AsyncMock(return_value=True) res = await api.init_api_mode() assert res is None assert api.enter_at_command_mode.call_count == 1 api.enter_at_command_mode = mock.AsyncMock(return_value=False) res = await api.init_api_mode() assert res is False assert api.enter_at_command_mode.call_count == 10 async def enter_at_mode(): if api._uart.baudrate == 9600: return True return False api._uart.baudrate = 57600 api.enter_at_command_mode = mock.MagicMock(side_effect=enter_at_mode) api.api_mode_at_commands = mock.AsyncMock(return_value=True) res = await api.init_api_mode() assert res is True assert api.enter_at_command_mode.call_count == 5 def test_set_application(api): """Test setting the application.""" api.set_application(mock.sentinel.app) assert api._app == mock.sentinel.app def test_handle_route_record_indicator(api): """Test api._handle_route_record_indicator().""" s = mock.sentinel api._handle_route_record_indicator(s.ieee, s.src, s.rx_opts, s.hops) def test_handle_many_to_one_rri(api): """Test api._handle_many_to_one_rri().""" ieee = t.EUI64([t.uint8_t(a) for a in range(0, 8)]) nwk = 0x1234 api._handle_many_to_one_rri(ieee, nwk, 0) async def test_connection_lost(api): """Test `connection_lost` propagataion.""" api.set_application(mock.AsyncMock()) err = RuntimeError() api.connection_lost(err) api._app.connection_lost.assert_called_once_with(err) zigpy-xbee-0.21.0/tests/test_application.py000066400000000000000000000634741471001077200207500ustar00rootroot00000000000000"""Tests for ControllerApplication.""" import asyncio from unittest import mock import pytest import zigpy.config as config import zigpy.exceptions import zigpy.state import zigpy.types as t import zigpy.zdo import zigpy.zdo.types as zdo_t from zigpy_xbee.api import XBee from zigpy_xbee.exceptions import InvalidCommand import zigpy_xbee.types as xbee_t from zigpy_xbee.zigbee import application APP_CONFIG = { config.CONF_DEVICE: { config.CONF_DEVICE_PATH: "/dev/null", config.CONF_DEVICE_BAUDRATE: 115200, }, config.CONF_DATABASE: None, config.CONF_OTA: { config.CONF_OTA_ENABLED: False, }, } @pytest.fixture def node_info(): """Sample NodeInfo fixture.""" return zigpy.state.NodeInfo( nwk=t.NWK(0x0000), ieee=t.EUI64.convert("00:12:4b:00:1c:a1:b8:46"), logical_type=zdo_t.LogicalType.Coordinator, ) @pytest.fixture def network_info(node_info): """Sample NetworkInfo fixture.""" return zigpy.state.NetworkInfo( extended_pan_id=t.ExtendedPanId.convert("bd:27:0b:38:37:95:dc:87"), pan_id=t.PanId(0x9BB0), nwk_update_id=18, nwk_manager_id=t.NWK(0x0000), channel=t.uint8_t(15), channel_mask=t.Channels.ALL_CHANNELS, security_level=t.uint8_t(5), network_key=zigpy.state.Key( key=t.KeyData.convert("2ccade06b3090c310315b3d574d3c85a"), seq=108, tx_counter=118785, ), tc_link_key=zigpy.state.Key( key=t.KeyData(b"ZigBeeAlliance09"), partner_ieee=node_info.ieee, tx_counter=8712428, ), key_table=[], children=[], nwk_addresses={}, source="zigpy-xbee@0.0.0", ) @pytest.fixture def app(monkeypatch): """Sample ControllerApplication fixture.""" monkeypatch.setattr(application, "TIMEOUT_TX_STATUS", 0.1) monkeypatch.setattr(application, "TIMEOUT_REPLY", 0.1) monkeypatch.setattr(application, "TIMEOUT_REPLY_EXTENDED", 0.1) app = application.ControllerApplication(APP_CONFIG) api = XBee(APP_CONFIG[config.CONF_DEVICE]) monkeypatch.setattr(api, "_command", mock.AsyncMock()) app._api = api app.state.node_info.nwk = 0x0000 app.state.node_info.ieee = t.EUI64.convert("aa:bb:cc:dd:ee:ff:00:11") return app def test_modem_status(app): """Test handling ModemStatus updates.""" assert 0x00 in xbee_t.ModemStatus.__members__.values() app.handle_modem_status(xbee_t.ModemStatus(0x00)) assert 0xEE not in xbee_t.ModemStatus.__members__.values() app.handle_modem_status(xbee_t.ModemStatus(0xEE)) def _test_rx( app, device, nwk, dst_ep=mock.sentinel.dst_ep, cluster_id=mock.sentinel.cluster_id, data=mock.sentinel.data, ): """Call app.handle_rx().""" app.get_device = mock.MagicMock(return_value=device) app.handle_rx( b"\x01\x02\x03\x04\x05\x06\x07\x08", nwk, mock.sentinel.src_ep, dst_ep, cluster_id, mock.sentinel.profile_id, mock.sentinel.rxopts, data, ) def test_rx(app): """Test message receiving.""" device = mock.MagicMock() _test_rx(app, device, 0x1234, data=b"\x01\x02\x03\x04") assert device.packet_received.call_count == 1 packet = device.packet_received.call_args[0][0] assert packet.src == t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x1234) assert packet.src_ep == mock.sentinel.src_ep assert packet.dst == t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x0000) assert packet.dst_ep == mock.sentinel.dst_ep assert packet.profile_id == mock.sentinel.profile_id assert packet.cluster_id == mock.sentinel.cluster_id assert packet.data == t.SerializableBytes(b"\x01\x02\x03\x04") def test_rx_nwk_0000(app): """Test receiving self-addressed message.""" app._handle_reply = mock.MagicMock() app.get_device = mock.MagicMock() app.handle_rx( b"\x01\x02\x03\x04\x05\x06\x07\x08", 0x0000, mock.sentinel.src_ep, mock.sentinel.dst_ep, mock.sentinel.cluster_id, mock.sentinel.profile_id, mock.sentinel.rxopts, b"", ) assert app.get_device.call_count == 2 def test_rx_unknown_device(app, device): """Unknown NWK, but existing device.""" app.create_task = mock.MagicMock() app._discover_unknown_device = mock.MagicMock() dev = device(nwk=0x1234) app.devices[dev.ieee] = dev num_before_rx = len(app.devices) app.handle_rx( b"\x08\x07\x06\x05\x04\x03\x02\x01", 0x3334, mock.sentinel.src_ep, mock.sentinel.dst_ep, mock.sentinel.cluster_id, mock.sentinel.profile_id, mock.sentinel.rxopts, b"", ) assert app.create_task.call_count == 1 app._discover_unknown_device.assert_called_once_with(0x3334) assert len(app.devices) == num_before_rx def test_rx_unknown_device_ieee(app): """Unknown NWK, and unknown IEEE.""" app.create_task = mock.MagicMock() app._discover_unknown_device = mock.MagicMock() app.get_device = mock.MagicMock(side_effect=KeyError) app.handle_rx( b"\xff\xff\xff\xff\xff\xff\xff\xff", 0x3334, mock.sentinel.src_ep, mock.sentinel.dst_ep, mock.sentinel.cluster_id, mock.sentinel.profile_id, mock.sentinel.rxopts, b"", ) assert app.create_task.call_count == 1 app._discover_unknown_device.assert_called_once_with(0x3334) assert app.get_device.call_count == 2 @pytest.fixture def device(app): """Sample zigpy.device.Device fixture.""" def _device( new=False, zdo_init=False, nwk=0x1234, ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01" ): from zigpy.device import Device, Status as DeviceStatus nwk = t.uint16_t(nwk) ieee, _ = t.EUI64.deserialize(ieee) dev = Device(app, ieee, nwk) if new: dev.status = DeviceStatus.NEW elif zdo_init: dev.status = DeviceStatus.ZDO_INIT else: dev.status = DeviceStatus.ENDPOINTS_INIT return dev return _device def _device_join(app, dev, data): """Simulate device join notification.""" dev.packet_received = mock.MagicMock() dev.schedule_initialize = mock.MagicMock() app.handle_join = mock.MagicMock() app.create_task = mock.MagicMock() app._discover_unknown_device = mock.MagicMock() dst_ep = 0 cluster_id = 0x0013 _test_rx(app, dev, dev.nwk, dst_ep, cluster_id, data) assert app.handle_join.call_count == 1 assert dev.packet_received.call_count == 1 assert dev.schedule_initialize.call_count == 1 def test_device_join_new(app, device): """Test device join.""" dev = device() data = b"\xee" + dev.nwk.serialize() + dev.ieee.serialize() + b"\x40" _device_join(app, dev, data) def test_device_join_inconsistent_nwk(app, device): """Test device join inconsistent NWK.""" dev = device() data = b"\xee" + b"\x01\x02" + dev.ieee.serialize() + b"\x40" _device_join(app, dev, data) def test_device_join_inconsistent_ieee(app, device): """Test device join inconsistent IEEE.""" dev = device() data = b"\xee" + dev.nwk.serialize() + b"\x01\x02\x03\x04\x05\x06\x07\x08" + b"\x40" _device_join(app, dev, data) async def test_broadcast(app): """Test sending broadcast transmission.""" (profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data) = ( 0x260, 1, 2, 3, 0x0100, 0x06, 210, b"\x02\x01\x00", ) app._api._command.return_value = xbee_t.TXStatus.SUCCESS r = await app.broadcast(profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data) assert r[0] == xbee_t.TXStatus.SUCCESS assert app._api._command.call_count == 1 assert app._api._command.call_args[0][0] == "tx_explicit" assert app._api._command.call_args[0][3] == src_ep assert app._api._command.call_args[0][4] == dst_ep assert app._api._command.call_args[0][9] == data app._api._command.return_value = xbee_t.TXStatus.ADDRESS_NOT_FOUND with pytest.raises(zigpy.exceptions.DeliveryError): r = await app.broadcast( profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data ) app._api._command.side_effect = asyncio.TimeoutError with pytest.raises(zigpy.exceptions.DeliveryError): r = await app.broadcast( profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data ) async def test_get_association_state(app): """Test get association statevia API.""" ai_results = (0xFF, 0xFF, 0xFF, 0xFF, mock.sentinel.ai) app._api._at_command = mock.AsyncMock( spec=XBee._at_command, side_effect=ai_results, ) ai = await app._get_association_state() assert app._api._at_command.call_count == len(ai_results) assert ai is mock.sentinel.ai @pytest.mark.parametrize("legacy_module", (False, True)) async def test_write_network_info(app, node_info, network_info, legacy_module): """Test writing network info to the device.""" def _mock_queued_at(name, *args): if legacy_module and name == "CE": raise InvalidCommand("Legacy module") return "OK" app._api._queued_at = mock.AsyncMock( spec=XBee._queued_at, side_effect=_mock_queued_at ) app._api._at_command = mock.AsyncMock(spec=XBee._at_command) app._api._running = mock.AsyncMock(spec=app._api._running) app._get_association_state = mock.AsyncMock( spec=application.ControllerApplication._get_association_state, return_value=0x00, ) await app.write_network_info(network_info=network_info, node_info=node_info) app._api._queued_at.assert_any_call("SC", 1 << (network_info.channel - 11)) app._api._queued_at.assert_any_call("KY", b"ZigBeeAlliance09") app._api._queued_at.assert_any_call("NK", network_info.network_key.key.serialize()) app._api._queued_at.assert_any_call("ID", 0xBD270B383795DC87) async def _test_start_network( app, ai_status=0xFF, api_mode=True, api_config_succeeds=True, ee=1, eo=2, zs=2, legacy_module=False, ): """Call app.start_network().""" ai_tries = 5 app.state.node_info = zigpy.state.NodeInfo() def _at_command_mock(cmd, *args): nonlocal ai_tries if not api_mode: raise asyncio.TimeoutError if cmd == "CE" and legacy_module: raise InvalidCommand ai_tries -= 1 if cmd == "AI" else 0 return { "AI": ai_status if ai_tries < 0 else 0xFF, "CE": 1 if ai_status == 0 else 0, "EO": eo, "EE": ee, "ID": 0x25DCF87E03EA5906, "MY": 0xFFFE if ai_status else 0x0000, "NJ": mock.sentinel.at_nj, "OI": 0xDD94, "OP": mock.sentinel.at_op, "SH": 0x08070605, "SL": 0x04030201, "ZS": zs, "VR": 0x1234, }.get(cmd, None) def init_api_mode_mock(): nonlocal api_mode api_mode = api_config_succeeds return api_config_succeeds api_mock = mock.MagicMock() api_mock._at_command = mock.AsyncMock(side_effect=_at_command_mock) api_mock.init_api_mode = mock.AsyncMock(side_effect=init_api_mode_mock) api_mock.connect = mock.AsyncMock() with mock.patch("zigpy_xbee.api.XBee", return_value=api_mock): await app.connect() app.form_network = mock.AsyncMock() await app.start_network() return app async def test_start_network(app): """Test start network.""" await _test_start_network(app, ai_status=0x00) assert app.state.node_info.nwk == 0x0000 assert app.state.node_info.ieee == t.EUI64(range(1, 9)) assert app.state.network_info.pan_id == 0xDD94 assert app.state.network_info.extended_pan_id == t.ExtendedPanId.convert( "25:dc:f8:7e:03:ea:59:06" ) await _test_start_network(app, ai_status=0x00) assert app.state.node_info.nwk == 0x0000 assert app.state.node_info.ieee == t.EUI64(range(1, 9)) assert app.form_network.call_count == 0 with pytest.raises(zigpy.exceptions.NetworkNotFormed): await _test_start_network(app, ai_status=0x06) with pytest.raises(zigpy.exceptions.NetworkNotFormed): await _test_start_network(app, ai_status=0x00, zs=1) with pytest.raises(zigpy.exceptions.NetworkNotFormed): await _test_start_network(app, ai_status=0x06, legacy_module=True) with pytest.raises(zigpy.exceptions.NetworkNotFormed): await _test_start_network(app, ai_status=0x00, zs=1, legacy_module=True) async def test_start_network_no_api_mode(app): """Test start network when not in API mode.""" with pytest.raises(asyncio.TimeoutError): await _test_start_network(app, ai_status=0x00, api_mode=False) async def test_start_network_api_mode_config_fails(app): """Test start network when not when API config fails.""" with pytest.raises(asyncio.TimeoutError): await _test_start_network( app, ai_status=0x00, api_mode=False, api_config_succeeds=False ) async def test_permit(app): """Test permit joins.""" app._api._at_command = mock.AsyncMock() time_s = 30 await app.permit_ncp(time_s) assert app._api._at_command.call_count == 2 assert app._api._at_command.call_args_list[0][0][1] == time_s async def test_permit_with_link_key(app): """Test permit joins with link key.""" app._api._command = mock.AsyncMock(return_value=xbee_t.TXStatus.SUCCESS) app._api._at_command = mock.AsyncMock(return_value="OK") node = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08") link_key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" time_s = 500 await app.permit_with_link_key(node=node, link_key=link_key, time_s=time_s) app._api._at_command.assert_called_once_with("KT", time_s) app._api._command.assert_called_once_with( "register_joining_device", node, 0xFFFE, 0, link_key ) async def _test_request( app, expect_reply=True, send_success=True, send_timeout=False, **kwargs ): """Call app.request().""" seq = 123 nwk = 0x2345 ieee = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08") dev = app.add_device(ieee, nwk) def _mock_command( cmdname, ieee, nwk, src_ep, dst_ep, cluster, profile, radius, options, data ): send_fut = asyncio.Future() if not send_timeout: if send_success: send_fut.set_result(xbee_t.TXStatus.SUCCESS) else: send_fut.set_result(xbee_t.TXStatus.ADDRESS_NOT_FOUND) return send_fut app._api._command = mock.MagicMock(side_effect=_mock_command) return await app.request( dev, 0x0260, 1, 2, 3, seq, b"\xaa\x55\xbe\xef", expect_reply=expect_reply, **kwargs, ) async def test_request_with_ieee(app): """Test request with IEEE.""" r = await _test_request(app, use_ieee=True, send_success=True) assert r[0] == 0 async def test_request_with_reply(app): """Test request with expecting reply.""" r = await _test_request(app, expect_reply=True, send_success=True) assert r[0] == 0 async def test_request_send_timeout(app): """Test request with send timeout.""" with pytest.raises(zigpy.exceptions.DeliveryError): await _test_request(app, send_timeout=True) async def test_request_send_fail(app): """Test request with send failure.""" with pytest.raises(zigpy.exceptions.DeliveryError): await _test_request(app, send_success=False) async def test_request_unknown_device(app): """Test request with unknown device.""" dev = zigpy.device.Device( application=app, ieee=xbee_t.UNKNOWN_IEEE, nwk=xbee_t.UNKNOWN_NWK ) with pytest.raises( zigpy.exceptions.DeliveryError, match="Cannot send a packet to a device without a known IEEE address", ): await app.request( dev, 0x0260, 1, 2, 3, 123, b"\xaa\x55\xbe\xef", ) async def test_request_extended_timeout(app): """Test request with extended timeout.""" r = await _test_request(app, True, True, extended_timeout=False) assert r[0] == xbee_t.TXStatus.SUCCESS assert app._api._command.call_count == 1 assert app._api._command.call_args[0][8] & 0x40 == 0x00 app._api._command.reset_mock() r = await _test_request(app, True, True, extended_timeout=True) assert r[0] == xbee_t.TXStatus.SUCCESS assert app._api._command.call_count == 1 assert app._api._command.call_args[0][8] & 0x40 == 0x40 app._api._command.reset_mock() async def test_force_remove(app): """Test device force removal.""" await app.force_remove(mock.sentinel.device) async def test_shutdown(app): """Test application shutdown.""" mock_disconnect = mock.AsyncMock() app._api.disconnect = mock_disconnect await app.disconnect() assert app._api is None assert mock_disconnect.call_count == 1 async def test_remote_at_cmd(app, device): """Test remote AT command.""" dev = device() app.get_device = mock.MagicMock(return_value=dev) app._api = mock.MagicMock(spec=XBee) s = mock.sentinel await app.remote_at_command( s.nwk, s.cmd, s.data, apply_changes=True, encryption=True ) assert app._api._remote_at_command.call_count == 1 assert app._api._remote_at_command.call_args[0][0] is dev.ieee assert app._api._remote_at_command.call_args[0][1] == s.nwk assert app._api._remote_at_command.call_args[0][2] == 0x12 assert app._api._remote_at_command.call_args[0][3] == s.cmd assert app._api._remote_at_command.call_args[0][4] == s.data @pytest.fixture def ieee(): """Sample IEEE fixture.""" return t.EUI64.deserialize(b"\x00\x01\x02\x03\x04\x05\x06\x07")[0] @pytest.fixture def nwk(): """Sample NWK fixture.""" return t.uint16_t(0x0100) def test_rx_device_annce(app, ieee, nwk): """Test receiving device announce.""" dst_ep = 0 cluster_id = zdo_t.ZDOCmd.Device_annce device = mock.MagicMock() device.status = device.Status.NEW device.zdo = zigpy.zdo.ZDO(None) app.get_device = mock.MagicMock(return_value=device) app.handle_join = mock.MagicMock() device.packet_received = mock.MagicMock() data = t.uint8_t(0xAA).serialize() data += nwk.serialize() data += ieee.serialize() data += t.uint8_t(0x8E).serialize() app.handle_rx( ieee, nwk, mock.sentinel.src_ep, dst_ep, cluster_id, mock.sentinel.profile_id, mock.sentinel.rx_opt, data, ) assert device.packet_received.call_count == 1 app.handle_join.assert_called_once_with(nwk=nwk, ieee=ieee, parent_nwk=None) async def _test_mrequest(app, send_success=True, send_timeout=False, **kwargs): """Call app.mrequest().""" seq = 123 group_id = 0x2345 def _mock_command( cmdname, ieee, nwk, src_ep, dst_ep, cluster, profile, radius, options, data ): send_fut = asyncio.Future() if not send_timeout: if send_success: send_fut.set_result(xbee_t.TXStatus.SUCCESS) else: send_fut.set_result(xbee_t.TXStatus.ADDRESS_NOT_FOUND) return send_fut app._api._command = mock.MagicMock(side_effect=_mock_command) return await app.mrequest(group_id, 0x0260, 1, 2, seq, b"\xaa\x55\xbe\xef") async def test_mrequest_with_reply(app): """Test mrequest with reply.""" r = await _test_mrequest(app, send_success=True) assert r[0] == 0 async def test_mrequest_send_timeout(app): """Test mrequest with send timeout.""" with pytest.raises(zigpy.exceptions.DeliveryError): await _test_mrequest(app, send_timeout=True) async def test_mrequest_send_fail(app): """Test mrequest with send failure.""" with pytest.raises(zigpy.exceptions.DeliveryError): await _test_mrequest(app, send_success=False) async def test_reset_network_info(app): """Test resetting network.""" async def mock_at_command(cmd, *args): if cmd == "NR": return 0x00 return None app._api._at_command = mock.MagicMock( spec=XBee._at_command, side_effect=mock_at_command ) await app.reset_network_info() app._api._at_command.assert_called_once_with("NR", 0) async def test_move_network_to_channel(app): """Test moving network to another channel.""" app._api._queued_at = mock.AsyncMock(spec=XBee._at_command) await app._move_network_to_channel(26, new_nwk_update_id=1) assert len(app._api._queued_at.mock_calls) == 1 app._api._queued_at.assert_any_call("SC", 1 << (26 - 11)) async def test_energy_scan(app): """Test channel energy scan.""" rssi = b"\x0A\x0F\x14\x19\x1E\x23\x28\x2D\x32\x37\x3C\x41\x46\x4B\x50\x55" app._api._at_command = mock.AsyncMock(spec=XBee._at_command, return_value=rssi) time_s = 3 count = 3 energy = await app.energy_scan( channels=list(range(11, 27)), duration_exp=time_s, count=count ) assert app._api._at_command.mock_calls == [mock.call("ED", bytes([time_s]))] * count assert {k: round(v, 3) for k, v in energy.items()} == { 11: 254.032, 12: 253.153, 13: 251.486, 14: 248.352, 15: 242.562, 16: 232.193, 17: 214.619, 18: 187.443, 19: 150.853, 20: 109.797, 21: 72.172, 22: 43.571, 23: 24.769, 24: 13.56, 25: 7.264, 26: 3.844, } async def test_energy_scan_legacy_module(app): """Test channel energy scan.""" app._api._at_command = mock.AsyncMock( spec=XBee._at_command, side_effect=InvalidCommand ) time_s = 3 count = 3 energy = await app.energy_scan( channels=list(range(11, 27)), duration_exp=time_s, count=count ) app._api._at_command.assert_called_once_with("ED", bytes([time_s])) assert energy == {c: 0 for c in range(11, 27)} def test_neighbors_updated(app, device): """Test LQI from neighbour scan.""" router = device(ieee=b"\x01\x02\x03\x04\x05\x06\x07\x08") router.radio_details = mock.MagicMock() end_device = device(ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01") end_device.radio_details = mock.MagicMock() app.devices[router.ieee] = router app.devices[end_device.ieee] = end_device pan_id = t.ExtendedPanId(b"\x07\x07\x07\x07\x07\x07\x07\x07") # The router has two neighbors: the coordinator and the end device neighbors = [ zdo_t.Neighbor( extended_pan_id=pan_id, ieee=app.state.node_info.ieee, nwk=app.state.node_info.nwk, device_type=0x0, rx_on_when_idle=0x1, relationship=0x00, reserved1=0x0, permit_joining=0x0, reserved2=0x0, depth=0, lqi=128, ), zdo_t.Neighbor( extended_pan_id=pan_id, ieee=end_device.ieee, nwk=end_device.nwk, device_type=0x2, rx_on_when_idle=0x0, relationship=0x01, reserved1=0x0, permit_joining=0x0, reserved2=0x0, depth=2, lqi=100, ), # Let's also include an unknown device zdo_t.Neighbor( extended_pan_id=pan_id, ieee=t.EUI64(b"\x00\x0F\x0E\x0D\x0C\x0B\x0A\x09"), nwk=t.NWK(0x9999), device_type=0x2, rx_on_when_idle=0x0, relationship=0x01, reserved1=0x0, permit_joining=0x0, reserved2=0x0, depth=2, lqi=99, ), ] app.neighbors_updated(router.ieee, neighbors) router.radio_details.assert_called_once_with(lqi=128) end_device.radio_details.assert_called_once_with(lqi=100) def test_routes_updated_schedule(app): """Test scheduling the sync routes_updated function.""" app.create_task = mock.MagicMock() app._routes_updated = mock.MagicMock() ieee = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08") routes = [] app.routes_updated(ieee, routes) assert app.create_task.call_count == 1 app._routes_updated.assert_called_once_with(ieee, routes) async def test_routes_updated(app, device): """Test RSSI on routes scan update.""" rssi = 0x50 app._api._at_command = mock.AsyncMock(return_value=rssi) router1 = device(ieee=b"\x01\x02\x03\x04\x05\x06\x07\x08") router1.radio_details = mock.MagicMock() router2 = device(ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01") router2.radio_details = mock.MagicMock() app.devices[router1.ieee] = router1 app.devices[router2.ieee] = router2 # Let router1 be immediate child and route2 be child of the router1. # Then the routes of router1 would be: routes = [ zdo_t.Route( DstNWK=app.state.node_info.nwk, RouteStatus=0x00, MemoryConstrained=0x0, ManyToOne=0x1, RouteRecordRequired=0x0, Reserved=0x0, NextHop=app.state.node_info.nwk, ), zdo_t.Route( DstNWK=router2.nwk, RouteStatus=0x00, MemoryConstrained=0x0, ManyToOne=0x0, RouteRecordRequired=0x0, Reserved=0x0, NextHop=router2.nwk, ), ] await app._routes_updated(router1.ieee, routes) router1.radio_details.assert_called_once_with(rssi=-80) assert router2.radio_details.call_count == 0 router1.radio_details.reset_mock() routes = [ zdo_t.Route( DstNWK=router1.nwk, RouteStatus=0x00, MemoryConstrained=0x0, ManyToOne=0x0, RouteRecordRequired=0x0, Reserved=0x0, NextHop=router1.nwk, ) ] await app._routes_updated(router2.ieee, routes) assert router1.radio_details.call_count == 0 assert router2.radio_details.call_count == 0 app._api._at_command.assert_awaited_once_with("DB") zigpy-xbee-0.21.0/tests/test_types.py000066400000000000000000000036361471001077200176030ustar00rootroot00000000000000"""Tests for types module.""" import pytest import zigpy.types as t import zigpy_xbee.types as xbee_t def test_bytes_serialize(): """Test Bytes.serialize().""" data = 0x89AB.to_bytes(4, "big") result = xbee_t.Bytes(data).serialize() assert result == data def test_bytes_deserialize(): """Test Bytes.deserialize().""" data, rest = xbee_t.Bytes.deserialize(0x89AB.to_bytes(3, "big")) assert data == b"\x00\x89\xAB" assert rest == b"" def test_atcommand(): """Test ATCommand class.""" cmd = b"AI" data = 0x06.to_bytes(4, "big") r_cmd, r_data = xbee_t.ATCommand.deserialize(cmd + data) assert r_cmd == cmd assert r_data == data def test_undefined_enum_undefined_value(): """Test UndefinedEnum class.""" class undEnum(t.uint8_t, xbee_t.UndefinedEnum): OK = 0 ERROR = 2 UNDEFINED_VALUE = 0xFF _UNDEFINED = 0xFF i = undEnum(0) assert i == 0 assert i.name == "OK" i = undEnum(2) assert i == 2 assert i.name == "ERROR" i = undEnum(0xEE) assert i.name == "UNDEFINED_VALUE" i = undEnum() assert i is undEnum.OK def test_undefined_enum_undefinede(): """Test UndefinedEnum undefined member.""" class undEnum(t.uint8_t, xbee_t.UndefinedEnum): OK = 0 ERROR = 2 UNDEFINED_VALUE = 0xFF with pytest.raises(ValueError): undEnum(0xEE) def test_nwk(): """Test NWK class.""" nwk = xbee_t.NWK(0x1234) assert str(nwk) == "0x1234" assert repr(nwk) == "0x1234" def test_eui64(): """Test EUI64 class.""" extra = b"\xBE\xEF" data = b"01234567" result, rest = xbee_t.EUI64.deserialize(data + extra) assert rest == extra assert result == xbee_t.EUI64((0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30)) data = xbee_t.EUI64([t.uint8_t(i) for i in range(0x30, 0x38)]) result = data.serialize() assert result == b"76543210" zigpy-xbee-0.21.0/tests/test_uart.py000066400000000000000000000150011471001077200173770ustar00rootroot00000000000000"""Tests for uart module.""" import asyncio from unittest import mock import pytest import serial_asyncio import zigpy.config from zigpy_xbee import uart DEVICE_CONFIG = zigpy.config.SCHEMA_DEVICE( { zigpy.config.CONF_DEVICE_PATH: "/dev/null", zigpy.config.CONF_DEVICE_BAUDRATE: 57600, } ) @pytest.fixture def gw(): """Gateway fixture.""" gw = uart.Gateway(mock.MagicMock()) gw._transport = mock.MagicMock() gw._transport.serial.BAUDRATES = serial_asyncio.serial.Serial.BAUDRATES return gw def test_baudrate(gw): """Test setting baudrate.""" gw.baudrate gw.baudrate = 19200 assert gw._transport.serial.baudrate == 19200 def test_baudrate_fail(gw): """Test setting unexpected baudrate.""" with pytest.raises(ValueError): gw.baudrate = 3333 async def test_connect(monkeypatch): """Test connecting.""" api = mock.MagicMock() 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 uart.connect(DEVICE_CONFIG, api) def test_command_mode_rsp(gw): """Test command mode response.""" data = b"OK" gw.command_mode_rsp(data) assert gw._api.handle_command_mode_rsp.call_count == 1 assert gw._api.handle_command_mode_rsp.call_args[0][0] == "OK" def test_command_mode_send(gw): """Test command mode request.""" data = b"ATAP2\x0D" gw.command_mode_send(data) gw._transport.write.assert_called_once_with(data) async def test_disconnect(gw): """Test closing connection.""" transport = gw._transport asyncio.get_running_loop().call_soon(gw.connection_lost, None) await gw.disconnect() assert transport.close.call_count == 1 def test_data_received_chunk_frame(gw): """Test receiving frame in parts.""" data = b"~\x00\r\x88\rID\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd" gw.frame_received = mock.MagicMock() gw.data_received(data[:3]) assert gw.frame_received.call_count == 0 gw.data_received(data[3:]) assert gw.frame_received.call_count == 1 assert gw.frame_received.call_args[0][0] == data[3:-1] def test_data_received_full_frame(gw): """Test receiving full frame.""" data = b"~\x00\r\x88\rID\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd" gw.frame_received = mock.MagicMock() gw.data_received(data) assert gw.frame_received.call_count == 1 assert gw.frame_received.call_args[0][0] == data[3:-1] def test_data_received_incomplete_frame(gw): """Test receiving partial frame.""" data = b"~\x00\x07\x8b\x0e\xff\xfd" gw.frame_received = mock.MagicMock() gw.data_received(data) assert gw.frame_received.call_count == 0 def test_data_received_at_response_non_cmd_mode(gw): """Test command mode response while not in command mode.""" data = b"OK\x0D" gw.frame_received = mock.MagicMock() gw.command_mode_rsp = mock.MagicMock() gw.data_received(data) assert gw.command_mode_rsp.call_count == 0 def test_data_received_at_response_in_cmd_mode(gw): """Test command mode response in command mode.""" data = b"OK\x0D" gw.frame_received = mock.MagicMock() gw.command_mode_rsp = mock.MagicMock() gw.command_mode_send(b"") gw.data_received(data) assert gw.command_mode_rsp.call_count == 1 assert gw.command_mode_rsp.call_args[0][0] == b"OK" gw.reset_command_mode() gw.data_received(data) assert gw.command_mode_rsp.call_count == 1 def test_extract(gw): """Test handling extra chaining data.""" gw._buffer = b"\x7E\x00\x02\x23\x7D\x31\xCBextra" frame = gw._extract_frame() assert frame == b"\x23\x11" assert gw._buffer == b"extra" def test_extract_wrong_checksum(gw): """Test API frame with wrong checksum and extra data.""" gw._buffer = b"\x7E\x00\x02\x23\x7D\x31\xCEextra" frame = gw._extract_frame() assert frame is None assert gw._buffer == b"extra" def test_extract_checksum_none(gw): """Test API frame with no checksum.""" data = b"\x7E\x00\x02\x23\x7D\x31" gw._buffer = data gw._checksum = lambda x: None frame = gw._extract_frame() assert frame is None assert gw._buffer == data def test_extract_frame_len_none(gw): """Test API frame with no length.""" data = b"\x7E" gw._buffer = data frame = gw._extract_frame() assert frame is None assert gw._buffer == data def test_extract_frame_no_start(gw): """Test API frame without frame ID.""" data = b"\x00\x02\x23\x7D\x31" gw._buffer = data frame = gw._extract_frame() assert frame is None assert gw._buffer == data def test_frame_received(gw): """Test frame is passed to api.""" data = b"frame" gw.frame_received(data) assert gw._api.frame_received.call_count == 1 assert gw._api.frame_received.call_args[0][0] == data def test_send(gw): """Test data send.""" gw.send(b"\x23\x11") data = b"\x7E\x00\x02\x23\x7D\x31\xCB" gw._transport.write.assert_called_once_with(data) def test_escape(gw): """Test string escaping.""" data = b"".join( [ a.to_bytes(1, "big") + b.to_bytes(1, "big") for a, b in zip(gw.RESERVED, b"\x22\x33\x44\x55") ] ) escaped = gw._escape(data) assert len(data) < len(escaped) chk = [c for c in escaped if c in gw.RESERVED] assert len(chk) == len(gw.RESERVED) # 4 chars to escape, thus 4 escape chars assert escaped == b'}^"}]3}1D}3U' def test_unescape(gw): """Test string unescaping.""" extra = b"\xaa\xbb\xcc\xff" escaped = b'}^"}]3}1D}3U' chk = b"".join( [ a.to_bytes(1, "big") + b.to_bytes(1, "big") for a, b in zip(gw.RESERVED, b"\x22\x33\x44\x55") ] ) unescaped, rest = gw._get_unescaped(escaped + extra, 8) assert len(escaped) > len(unescaped) assert rest == extra assert unescaped == chk def test_unescape_underflow(gw): """Test unescape with not enough data.""" escaped = b'}^"}' unescaped, rest = gw._get_unescaped(escaped, 3) assert unescaped is None assert rest is None def test_connection_lost_exc(gw): """Test cannection lost callback is called.""" err = RuntimeError() gw.connection_lost(err) assert gw._api.connection_lost.mock_calls == [mock.call(err)] def test_connection_closed(gw): """Test connection closed.""" gw.connection_lost(None) assert gw._api.connection_lost.mock_calls == [mock.call(None)] zigpy-xbee-0.21.0/tox.ini000066400000000000000000000016231471001077200151710ustar00rootroot00000000000000# Tox (http://tox.testrun.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py38, py39, py310, py311, py312, lint, black skip_missing_interpreters = True [testenv] setenv = PYTHONPATH = {toxinidir} install_command = pip install {opts} {packages} commands = py.test --cov --cov-report= deps = asynctest pytest pytest-cov pytest-asyncio [testenv:lint] basepython = python3 deps = flake8==6.1.0 isort==5.12.0 Flake8-pyproject==1.2.3 commands = flake8 isort --check {toxinidir}/zigpy_xbee {toxinidir}/tests {toxinidir}/setup.py [testenv:black] deps=black setenv = LC_ALL=C.UTF-8 LANG=C.UTF-8 commands= black --check --fast {toxinidir}/zigpy_xbee {toxinidir}/tests {toxinidir}/setup.py zigpy-xbee-0.21.0/zigpy_xbee/000077500000000000000000000000001471001077200160215ustar00rootroot00000000000000zigpy-xbee-0.21.0/zigpy_xbee/__init__.py000066400000000000000000000003061471001077200201310ustar00rootroot00000000000000"""Init file for zigpy_xbee.""" MAJOR_VERSION = 0 MINOR_VERSION = 18 PATCH_VERSION = "3" __short_version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__ = f"{__short_version__}.{PATCH_VERSION}" zigpy-xbee-0.21.0/zigpy_xbee/api.py000066400000000000000000000430731471001077200171530ustar00rootroot00000000000000"""XBee API implementation.""" import asyncio import binascii import functools import logging from typing import Any, Dict, Optional from zigpy.exceptions import APIException, DeliveryError import zigpy.types as t from zigpy_xbee.exceptions import ( ATCommandError, ATCommandException, InvalidCommand, InvalidParameter, TransmissionFailure, ) from . import types as xbee_t, uart LOGGER = logging.getLogger(__name__) AT_COMMAND_TIMEOUT = 3 REMOTE_AT_COMMAND_TIMEOUT = 30 # https://www.digi.com/resources/documentation/digidocs/PDFs/90000976.pdf COMMAND_REQUESTS = { "at": (0x08, (xbee_t.FrameId, xbee_t.ATCommand, xbee_t.Bytes), 0x88), "queued_at": (0x09, (xbee_t.FrameId, xbee_t.ATCommand, xbee_t.Bytes), 0x88), "remote_at": ( 0x17, ( xbee_t.FrameId, xbee_t.EUI64, xbee_t.NWK, t.uint8_t, xbee_t.ATCommand, xbee_t.Bytes, ), 0x97, ), "tx": (0x10, (), None), "tx_explicit": ( 0x11, ( xbee_t.FrameId, xbee_t.EUI64, xbee_t.NWK, t.uint8_t, t.uint8_t, t.uint16_t_be, t.uint16_t_be, t.uint8_t, t.uint8_t, xbee_t.Bytes, ), 0x8B, ), "create_source_route": ( 0x21, (xbee_t.FrameId, xbee_t.EUI64, xbee_t.NWK, t.uint8_t, xbee_t.Relays), None, ), "register_joining_device": ( 0x24, (xbee_t.FrameId, xbee_t.EUI64, t.uint16_t_be, t.uint8_t, xbee_t.Bytes), 0xA4, ), } COMMAND_RESPONSES = { "at_response": ( 0x88, (xbee_t.FrameId, xbee_t.ATCommand, t.uint8_t, xbee_t.Bytes), None, ), "modem_status": (0x8A, (xbee_t.ModemStatus,), None), "tx_status": ( 0x8B, ( xbee_t.FrameId, xbee_t.NWK, t.uint8_t, xbee_t.TXStatus, xbee_t.DiscoveryStatus, ), None, ), "route_information": (0x8D, (), None), "rx": (0x90, (), None), "explicit_rx_indicator": ( 0x91, ( xbee_t.EUI64, xbee_t.NWK, t.uint8_t, t.uint8_t, t.uint16_t_be, t.uint16_t_be, t.uint8_t, xbee_t.Bytes, ), None, ), "rx_io_data_long_addr": (0x92, (), None), "remote_at_response": ( 0x97, ( xbee_t.FrameId, xbee_t.EUI64, xbee_t.NWK, xbee_t.ATCommand, t.uint8_t, xbee_t.Bytes, ), None, ), "extended_status": (0x98, (), None), "route_record_indicator": ( 0xA1, (xbee_t.EUI64, xbee_t.NWK, t.uint8_t, xbee_t.Relays), None, ), "many_to_one_rri": (0xA3, (xbee_t.EUI64, xbee_t.NWK, t.uint8_t), None), "registration_status": (0xA4, (xbee_t.FrameId, xbee_t.RegistrationStatus), None), "node_id_indicator": (0x95, (), None), } # https://www.digi.com/resources/documentation/digidocs/pdfs/90001539.pdf pg 175 AT_COMMANDS = { # Addressing commands "DH": t.uint32_t_be, "DL": t.uint32_t_be, "MY": t.uint16_t_be, "MP": t.uint16_t_be, "NC": t.uint32_t_be, # 0 - MAX_CHILDREN. "SH": t.uint32_t_be, "SL": t.uint32_t_be, "NI": t, # 20 byte printable ascii string "SE": t.uint8_t, "DE": t.uint8_t, "CI": t.uint16_t_be, "TO": t.uint8_t, "NP": t.uint16_t_be, "DD": t.uint32_t_be, "CR": t.uint8_t, # 0 - 0x3F # Networking commands "CH": t.uint8_t, # 0x0B - 0x1A "DA": t, # no param "ID": t.uint64_t_be, "OP": t.uint64_t_be, "NH": t.uint8_t, "BH": t.uint8_t, # 0 - 0x1E "OI": t.uint16_t_be, "NT": t.uint8_t, # 0x20 - 0xFF "NO": t.uint8_t, # bitfield, 0 - 3 "SC": t.uint16_t_be, # 1 - 0xFFFF "SD": t.uint8_t, # 0 - 7 "ZS": t.uint8_t, # 0 - 2 "NJ": t.uint8_t, "JV": t.Bool, "NW": t.uint16_t_be, # 0 - 0x64FF "JN": t.Bool, "AR": t.uint8_t, "DJ": t.Bool, # WTF, docs "II": t.uint16_t_be, # Security commands "EE": t.Bool, "EO": t.uint8_t, "NK": xbee_t.Bytes, # 128-bit value "KY": xbee_t.Bytes, # 128-bit value "KT": t.uint16_t_be, # 0x1E - 0xFFFF # RF interfacing commands "PL": t.uint8_t, # 0 - 4 (basically an Enum) "PM": t.Bool, "DB": t.uint8_t, "PP": t.uint8_t, # RO "AP": t.uint8_t, # 1-2 (an Enum) "AO": t.uint8_t, # 0 - 3 (an Enum) "BD": t.uint8_t, # 0 - 7 (an Enum) "NB": t.uint8_t, # 0 - 3 (an Enum) "SB": t.uint8_t, # 0 - 1 (an Enum) "RO": t.uint8_t, "D6": t.uint8_t, # 0 - 5 (an Enum) "D7": t.uint8_t, # 0 - 7 (an Enum) "P3": t.uint8_t, # 0 - 5 (an Enum) "P4": t.uint8_t, # 0 - 5 (an Enum) # MAC diagnostics commands "ED": xbee_t.Bytes, # 16-byte value # I/O commands "IR": t.uint16_t_be, "IC": t.uint16_t_be, "D0": t.uint8_t, # 0 - 5 (an Enum) "D1": t.uint8_t, # 0 - 5 (an Enum) "D2": t.uint8_t, # 0 - 5 (an Enum) "D3": t.uint8_t, # 0 - 5 (an Enum) "D4": t.uint8_t, # 0 - 5 (an Enum) "D5": t.uint8_t, # 0 - 5 (an Enum) "D8": t.uint8_t, # 0 - 5 (an Enum) "D9": t.uint8_t, # 0 - 5 (an Enum) "P0": t.uint8_t, # 0 - 5 (an Enum) "P1": t.uint8_t, # 0 - 5 (an Enum) "P2": t.uint8_t, # 0 - 5 (an Enum) "P5": t.uint8_t, # 0 - 5 (an Enum) "P6": t.uint8_t, # 0 - 5 (an Enum) "P7": t.uint8_t, # 0 - 5 (an Enum) "P8": t.uint8_t, # 0 - 5 (an Enum) "P9": t.uint8_t, # 0 - 5 (an Enum) "LT": t.uint8_t, "PR": t.uint16_t_be, "RP": t.uint8_t, "%V": t.uint16_t_be, # read only "V+": t.uint16_t_be, "TP": t.uint16_t_be, "M0": t.uint16_t_be, # 0 - 0x3FF "M1": t.uint16_t_be, # 0 - 0x3FF # Diagnostics commands "VR": t.uint16_t_be, "HV": t.uint16_t_be, "AI": t.uint8_t, # AT command options "CT": t.uint16_t_be, # 2 - 0x028F "CN": None, "GT": t.uint16_t_be, "CC": t.uint8_t, # Sleep commands "SM": t.uint8_t, "SN": t.uint16_t_be, "SP": t.uint16_t_be, "ST": t.uint16_t_be, "SO": t.uint8_t, "WH": t.uint16_t_be, "SI": None, "PO": t.uint16_t_be, # 0 - 0x3E8 # Execution commands "AC": None, "WR": None, "RE": None, "FR": None, "NR": t.Bool, "CB": t.uint8_t, "ND": t, # "optional 2-Byte NI value" "DN": xbee_t.Bytes, # "up to 20-Byte printable ASCII string" "IS": None, "1S": None, "AS": None, # Stuff I've guessed "CE": t.uint8_t, } BAUDRATE_TO_BD = { 1200: "ATBD0", 2400: "ATBD1", 4800: "ATBD2", 9600: "ATBD3", 19200: "ATBD4", 38400: "ATBD5", 57600: "ATBD6", 115200: "ATBD7", 230400: "ATBD8", } AT_COMMAND_RESULT = { 1: ATCommandError, 2: InvalidCommand, 3: InvalidParameter, 4: TransmissionFailure, } class XBee: """Class implementing XBee communication protocol.""" def __init__(self, device_config: Dict[str, Any]) -> None: """Initialize instance.""" self._config = device_config self._uart: Optional[uart.Gateway] = None self._seq: int = 1 self._commands_by_id = {v[0]: k for k, v in COMMAND_RESPONSES.items()} self._awaiting = {} self._app = None self._cmd_mode_future: Optional[asyncio.Future] = None self._reset: asyncio.Event = asyncio.Event() self._running: asyncio.Event = asyncio.Event() @property def reset_event(self): """Return reset event.""" return self._reset @property def coordinator_started_event(self): """Return coordinator started.""" return self._running @property def is_running(self): """Return true if coordinator is running.""" return self.coordinator_started_event.is_set() async def connect(self) -> None: """Connect to the device.""" assert self._uart is None self._uart = await uart.connect(self._config, self) try: try: # Ensure we have escaped commands await self._at_command("AP", 2) except asyncio.TimeoutError: if not await self.init_api_mode(): raise APIException("Failed to configure XBee for API mode") except Exception: await self.disconnect() raise def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" if self._app is not None: self._app.connection_lost(exc) async def disconnect(self): """Close the connection.""" if self._uart: await self._uart.disconnect() self._uart = None def _command(self, name, *args, mask_frame_id=False): """Send API frame to the device.""" LOGGER.debug("Command %s %s", name, args) if self._uart is None: raise APIException("API is not running") frame_id = 0 if mask_frame_id else self._seq data, needs_response = self._api_frame(name, frame_id, *args) self._uart.send(data) future = None if needs_response and frame_id: future = asyncio.Future() self._awaiting[frame_id] = (future,) self._seq = (self._seq % 255) + 1 return future async def _remote_at_command(self, ieee, nwk, options, name, *args): """Execute AT command on a different XBee module in the network.""" LOGGER.debug("Remote AT command: %s %s", name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command( "remote_at", ieee, nwk, options, name.encode("ascii"), data ), timeout=REMOTE_AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("No response to %s command", name) raise async def _at_partial(self, cmd_type, name, *args): LOGGER.debug("%s command: %s %s", cmd_type, name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command(cmd_type, name.encode("ascii"), data), timeout=AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("%s: No response to %s command", cmd_type, name) raise _at_command = functools.partialmethod(_at_partial, "at") _queued_at = functools.partialmethod(_at_partial, "queued_at") def _api_frame(self, name, *args): """Build API frame.""" c = COMMAND_REQUESTS[name] return (bytes([c[0]]) + t.serialize(args, c[1])), c[2] def frame_received(self, data): """Handle API frame from the device.""" command = self._commands_by_id[data[0]] LOGGER.debug("Frame received: %s", command) data, rest = t.deserialize(data[1:], COMMAND_RESPONSES[command][1]) try: getattr(self, f"_handle_{command}")(*data) except AttributeError: LOGGER.error("No '%s' handler. Data: %s", command, binascii.hexlify(data)) def _handle_at_response(self, frame_id, cmd, status, value): """Local AT command response.""" (fut,) = self._awaiting.pop(frame_id) if status: try: exception = AT_COMMAND_RESULT[status] except KeyError: exception = ATCommandException fut.set_exception(exception(f"AT Command response: {status}")) return response_type = AT_COMMANDS[cmd.decode("ascii")] if response_type is None or len(value) == 0: fut.set_result(None) return response, remains = response_type.deserialize(value) fut.set_result(response) def _handle_remote_at_response(self, frame_id, ieee, nwk, cmd, status, value): """Remote AT command response.""" LOGGER.debug( "Remote AT command response from: %s", (frame_id, ieee, nwk, cmd, status, value), ) return self._handle_at_response(frame_id, cmd, status, value) def _handle_many_to_one_rri(self, ieee, nwk, reserved): LOGGER.debug("_handle_many_to_one_rri: %s", (ieee, nwk, reserved)) def _handle_modem_status(self, status): LOGGER.debug("Handle modem status frame: %s", status) status = status if status == xbee_t.ModemStatus.COORDINATOR_STARTED: self.coordinator_started_event.set() elif status in ( xbee_t.ModemStatus.HARDWARE_RESET, xbee_t.ModemStatus.WATCHDOG_TIMER_RESET, ): self.reset_event.set() self.coordinator_started_event.clear() elif status == xbee_t.ModemStatus.DISASSOCIATED: self.coordinator_started_event.clear() if self._app: self._app.handle_modem_status(status) def _handle_explicit_rx_indicator( self, ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data ): LOGGER.debug( "_handle_explicit_rx: %s", (ieee, nwk, dst_ep, cluster, rx_opts, binascii.hexlify(data)), ) self._app.handle_rx(ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data) def _handle_route_record_indicator(self, ieee, src, rx_opts, hops): """Handle Route Record indicator from a device.""" LOGGER.debug("_handle_route_record_indicator: %s", (ieee, src, rx_opts, hops)) def _handle_tx_status(self, frame_id, nwk, tries, tx_status, dsc_status): LOGGER.debug( ( "tx_explicit to 0x%04x: %s after %i tries. Discovery Status: %s," " Frame #%i" ), nwk, tx_status, tries, dsc_status, frame_id, ) try: (fut,) = self._awaiting.pop(frame_id) except KeyError: LOGGER.debug("unexpected tx_status report received") return try: if tx_status in ( xbee_t.TXStatus.BROADCAST_APS_TX_ATTEMPT, xbee_t.TXStatus.SELF_ADDRESSED, xbee_t.TXStatus.SUCCESS, ): fut.set_result(tx_status) else: fut.set_exception(DeliveryError(f"{tx_status}")) except asyncio.InvalidStateError as ex: LOGGER.debug("duplicate tx_status for %s nwk? State: %s", nwk, ex) def _handle_registration_status(self, frame_id, status): (fut,) = self._awaiting.pop(frame_id) if status: fut.set_exception(RuntimeError(f"Registration Status: {status.name}")) return LOGGER.debug(f"Registration Status: {status.name}") fut.set_result(status) def set_application(self, app): """Set reference to ControllerApplication.""" self._app = app def handle_command_mode_rsp(self, data): """Handle AT command response in command mode.""" fut = self._cmd_mode_future if fut is None or fut.done(): return if "OK" in data: fut.set_result(True) elif "ERROR" in data: fut.set_result(False) else: fut.set_result(data) async def command_mode_at_cmd(self, command): """Send AT command in command mode.""" self._cmd_mode_future = asyncio.Future() self._uart.command_mode_send(command.encode("ascii")) try: res = await asyncio.wait_for(self._cmd_mode_future, timeout=2) return res except asyncio.TimeoutError: LOGGER.debug("Command mode no response to AT '%s' command", command) return None async def enter_at_command_mode(self): """Enter command mode.""" await asyncio.sleep(1.2) # keep UART quiet for 1s before escaping return await self.command_mode_at_cmd("+++") async def api_mode_at_commands(self, baudrate): """Configure API and exit AT command mode.""" cmds = ["ATAP2", "ATWR", "ATCN"] bd = BAUDRATE_TO_BD.get(baudrate) if bd: cmds.insert(0, bd) for cmd in cmds: if not await self.command_mode_at_cmd(cmd + "\r"): LOGGER.debug("No response to %s cmd", cmd) return None LOGGER.debug("Successfully sent %s cmd", cmd) self._uart.reset_command_mode() return True async def init_api_mode(self): """Configure API mode on XBee.""" current_baudrate = self._uart.baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) return await self.api_mode_at_commands(current_baudrate) for baudrate in sorted(BAUDRATE_TO_BD.keys()): LOGGER.debug( "Failed to enter AT command mode at %dbps, trying %d next", self._uart.baudrate, baudrate, ) self._uart.baudrate = baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) res = await self.api_mode_at_commands(current_baudrate) self._uart.baudrate = current_baudrate return res LOGGER.debug( "Couldn't enter AT command mode at any known baudrate." "Configure XBee manually for escaped API mode ATAP2" ) return False def __getattr__(self, item): """Handle supported command requests.""" if item in COMMAND_REQUESTS: return functools.partial(self._command, item) raise AttributeError(f"Unknown command {item}") zigpy-xbee-0.21.0/zigpy_xbee/config.py000066400000000000000000000005071471001077200176420ustar00rootroot00000000000000"""XBee module config.""" import voluptuous as vol import zigpy.config SCHEMA_DEVICE = zigpy.config.SCHEMA_DEVICE.extend( {vol.Optional(zigpy.config.CONF_DEVICE_BAUDRATE, default=57600): int} ) CONFIG_SCHEMA = zigpy.config.CONFIG_SCHEMA.extend( {vol.Required(zigpy.config.CONF_DEVICE): zigpy.config.SCHEMA_DEVICE} ) zigpy-xbee-0.21.0/zigpy_xbee/exceptions.py000066400000000000000000000010761471001077200205600ustar00rootroot00000000000000"""Additional exceptions for XBee.""" class ATCommandException(Exception): """Base exception class for AT Command exceptions.""" class ATCommandError(ATCommandException): """Exception for AT Command Status 1 (ERROR).""" class InvalidCommand(ATCommandException): """Exception for AT Command Status 2 (Invalid command).""" class InvalidParameter(ATCommandException): """Exception for AT Command Status 3 (Invalid parameter).""" class TransmissionFailure(ATCommandException): """Exception for Remote AT Command Status 4 (Transmission failure).""" zigpy-xbee-0.21.0/zigpy_xbee/types.py000066400000000000000000000161231471001077200175420ustar00rootroot00000000000000"""Additional types for data parsing.""" import enum import zigpy.types as t class Bytes(bytes): """Serializable and deserializable bytes.""" def serialize(self): """Serialize the class.""" return self @classmethod def deserialize(cls, data): """Deserialize the data into the class.""" return cls(data), b"" class ATCommand(Bytes): """XBee AT command name.""" @classmethod def deserialize(cls, data): """Deserialize the data into the class.""" return cls(data[:2]), data[2:] class EUI64(t.EUI64): """EUI64 without prefix.""" @classmethod def deserialize(cls, data): """Deserialize the data into the class.""" r, data = super().deserialize(data) return cls(r[::-1]), data def serialize(self): """Serialize the class.""" assert self._length == len(self) return super().serialize()[::-1] class UndefinedEnumMeta(enum.EnumMeta): """Meta class for Enum that always has a value.""" def __call__(cls, value=None, *args, **kwargs): """Return the member, default, or undefined value.""" if value is None: # the 1st enum member is default return next(iter(cls)) try: return super().__call__(value, *args, **kwargs) except ValueError as exc: try: return super().__call__(cls._UNDEFINED) except AttributeError: raise exc class UndefinedEnum(enum.Enum, metaclass=UndefinedEnumMeta): """Enum that always has a value.""" class FrameId(t.uint8_t): """API frame ID.""" class NWK(t.uint16_t_be): """zigpy.types.NWK but big endian.""" def __repr__(self): """Get printable representation.""" return f"0x{self:04x}" def __str__(self): """Get string representation.""" return f"0x{self:04x}" class Relays(t.LVList, item_type=NWK, length_type=t.uint8_t): """List of Relays.""" UNKNOWN_IEEE = EUI64([t.uint8_t(0xFF) for i in range(0, 8)]) UNKNOWN_NWK = NWK(0xFFFE) class TXStatus(t.uint8_t, UndefinedEnum): """TX Status frame.""" SUCCESS = 0x00 # Standard # all retries are expired and no ACK is received. # Not returned for Broadcasts NO_ACK_RECEIVED = 0x01 CCA_FAILURE = 0x02 # Transmission was purged because a coordinator tried to send to an end # device, but it timed out waiting for a poll from the end device that # never occurred, this haapens when Coordinator times out of an indirect # transmission. Timeouse is defines ad 2.5 * 'SP' (Cyclic Sleep Period) # parameter value INDIRECT_TX_TIMEOUT = 0x03 # invalid destination endpoint INVALID_DESTINATION_ENDPOINT = 0x15 # not returned for Broadcasts NETWORK_ACK_FAILURE = 0x21 # TX failed because end device was not joined to the network INDIRECT_TX_FAILURE = 0x22 # Self addressed SELF_ADDRESSED = 0x23 # Address not found ADDRESS_NOT_FOUND = 0x24 # Route not found ROUTE_NOT_FOUND = 0x25 # Broadcast source failed to hear a neighbor relay the message BROADCAST_RELAY_FAILURE = 0x26 # Invalid binding table index INVALID_BINDING_IDX = 0x2B # Resource error lack of free buffers, timers, and so forth. NO_RESOURCES = 0x2C # Attempted broadcast with APS transmission BROADCAST_APS_TX_ATTEMPT = 0x2D # Attempted unicast with APS transmission, but EE=0 UNICAST_APS_TX_ATTEMPT = 0x2E INTERNAL_ERROR = 0x31 # Transmission failed due to resource depletion (for example, out of # buffers, especially for indirect messages from coordinator) NO_RESOURCES_2 = 0x32 # The payload in the frame was larger than allowed PAYLOAD_TOO_LARGE = 0x74 _UNDEFINED = 0x2C class DiscoveryStatus(t.uint8_t, UndefinedEnum): """Discovery status of TX Status frame.""" SUCCESS = 0x00 ADDRESS_DISCOVERY = 0x01 ROUTE_DISCOVERY = 0x02 ADDRESS_AND_ROUTE = 0x03 EXTENDED_TIMEOUT = 0x40 _UNDEFINED = 0x00 class TXOptions(t.bitmap8): """TX Options for explicit transmit frame.""" NONE = 0x00 Disable_Retries_and_Route_Repair = 0x01 Enable_APS_Encryption = 0x20 Use_Extended_TX_Timeout = 0x40 class ModemStatus(t.uint8_t, UndefinedEnum): """Modem Status.""" HARDWARE_RESET = 0x00 WATCHDOG_TIMER_RESET = 0x01 JOINED_NETWORK = 0x02 DISASSOCIATED = 0x03 CONFIGURATION_ERROR_SYNCHRONIZATION_LOST = 0x04 COORDINATOR_REALIGNMENT = 0x05 COORDINATOR_STARTED = 0x06 NETWORK_SECURITY_KEY_UPDATED = 0x07 NETWORK_WOKE_UP = 0x0B NETWORK_WENT_TO_SLEEP = 0x0C VOLTAGE_SUPPLY_LIMIT_EXCEEDED = 0x0D DEVICE_CLOUD_CONNECTED = 0x0E DEVICE_CLOUD_DISCONNECTED = 0x0F MODEM_KEY_ESTABLISHED = 0x10 MODEM_CONFIGURATION_CHANGED_WHILE_JOIN_IN_PROGRESS = 0x11 ACCESS_FAULT = 0x12 FATAL_STACK_ERROR = 0x13 PLKE_TABLE_INITIATED = 0x14 PLKE_TABLE_SUCCESS = 0x15 PLKE_TABLE_IS_FULL = 0x16 PLKE_NOT_AUTHORIZED = 0x17 PLKE_INVALID_TRUST_CENTER_REQUEST = 0x18 PLKE_TRUST_CENTER_UPDATE_FAIL = 0x19 PLKE_BAD_EUI_ADDRESS = 0x1A PLKE_LINK_KEY_REJECTED = 0x1B PLKE_UPDATE_OCCURED = 0x1C PLKE_LINK_KEY_TABLE_CLEAR = 0x1D ZIGBEE_FREQUENCY_AGILITY_HAS_REQUESTED_CHANNEL_CHANGE = 0x1E ZIGBEE_EXECUTE_ATFR_NO_JOINABLE_BEACON_RESPONSES = 0x1F ZIGBEE_TOKENS_SPACE_RECOVERED = 0x20 ZIGBEE_TOKENS_SPACE_UNRECOVERABLE = 0x21 ZIGBEE_TOKENS_SPACE_CORRUPTED = 0x22 ZIGBEE_DUAL_MODE_METAFRAME_ERROR = 0x30 BLE_CONNECT = 0x32 BLE_DISCONNECT = 0x33 NO_SECURE_SESSION_CONNECTION = 0x34 CELL_COMPONENT_UPDATE_STARTED = 0x35 CELL_COMPONENT_UPDATE_FAILED = 0x36 CELL_COMPONENT_UPDATE_SUCCEDED = 0x37 XBEE_FIRMWARE_UPDATE_STARTED = 0x38 XBEE_FIRMWARE_UPDATE_FAILED = 0x39 XBEE_WILL_RESET_TO_APPLY_FIRMWARE_UPDATE = 0x3A SECURE_SESSION_SUCCESSFULLY_ESTABLISHED = 0x3B SECURE_SESSION_ENDED = 0x3C SECURE_SESSION_AUTHENTICATION_FAILED = 0x3D PAN_ID_CONFLICT_DETECTED = 0x3E PAN_ID_UPDATED_DUE_TO_CONFLICT = 0x3F ROUTER_PAN_ID_CHANGED_BY_COORDINATOR_DUE_TO_CONFLICT = 0x40 NETWORK_WATCHDOG_TIMEOUT_EXPIRED_THREE_TIMES = 0x42 JOIN_WINDOW_OPENED = 0x43 JOIN_WINDOW_CLOSED = 0x44 NETWORK_SECURITY_KEY_ROTATION_INITIATED = 0x45 STACK_RESET = 0x80 FIB_BOOTLOADER_RESET = 0x81 SEND_OR_JOIN_COMMAND_ISSUED_WITHOUT_CONNECTING_FROM_AP = 0x82 ACCESS_POINT_NOT_FOUND = 0x83 PSK_NOT_CONFIGURED = 0x84 SSID_NOT_FOUND = 0x87 FAILED_TO_JOIN_WITH_SECURITY_ENABLED = 0x88 COER_LOCKUP_OR_CRYSTAL_FAILURE_RESET = 0x89 INVALID_CHANNEL = 0x8A LOW_VOLTAGE_RESET = 0x8B FAILED_TO_JOIN_ACCESS_POINT = 0x8E UNKNOWN_MODEM_STATUS = 0xFF _UNDEFINED = 0xFF class RegistrationStatus(t.uint8_t, UndefinedEnum): """Key Registration Status.""" SUCCESS = 0x00 KEY_TOO_LONG = 0x01 TRANSIENT_KEY_TABLE_IS_FULL = 0x18 ADDRESS_NOT_FOUND_IN_THE_KEY_TABLE = 0xB1 KEY_IS_INVALID_OR_RESERVED = 0xB2 INVALID_ADDRESS = 0xB3 KEY_TABLE_IS_FULL = 0xB4 SECURITY_DATA_IS_INVALID_INSTALL_CODE_CRC_FAILS = 0xBD UNKNOWN_MODEM_STATUS = 0xFF _UNDEFINED = 0xFF zigpy-xbee-0.21.0/zigpy_xbee/uart.py000066400000000000000000000115051471001077200173500ustar00rootroot00000000000000"""Module for UART communication to the device.""" import asyncio import logging from typing import Any, Dict import zigpy.config import zigpy.serial LOGGER = logging.getLogger(__name__) class Gateway(zigpy.serial.SerialProtocol): """Class implementing the UART protocol.""" START = b"\x7E" ESCAPE = b"\x7D" XON = b"\x11" XOFF = b"\x13" RESERVED = START + ESCAPE + XON + XOFF THIS_ONE = True def __init__(self, api): """Initialize instance.""" super().__init__() self._api = api self._in_command_mode = False def send(self, data): """Send data, taking care of escaping and framing.""" LOGGER.debug("Sending: %s", data) checksum = bytes([self._checksum(data)]) frame = self.START + self._escape( len(data).to_bytes(2, "big") + data + checksum ) self._transport.write(frame) @property def baudrate(self): """Baudrate.""" return self._transport.serial.baudrate @baudrate.setter def baudrate(self, baudrate): """Set baudrate.""" if baudrate in self._transport.serial.BAUDRATES: self._transport.serial.baudrate = baudrate else: raise ValueError( f"baudrate must be one of {self._transport.serial.BAUDRATES}" ) def connection_lost(self, exc) -> None: """Port was closed expectedly or unexpectedly.""" super().connection_lost(exc) if self._api is not None: self._api.connection_lost(exc) def command_mode_rsp(self, data): """Handle AT command mode response.""" data = data.decode("ascii", "ignore") LOGGER.debug("Handling AT command mode response: %s", data) self._api.handle_command_mode_rsp(data) def command_mode_send(self, data): """Send data in command mode.""" LOGGER.debug("Command mode sending %s to uart", data) self._in_command_mode = True self._transport.write(data) def data_received(self, data): """Handle data received from the UART callback.""" super().data_received(data) while self._buffer: frame = self._extract_frame() if frame is None: break self.frame_received(frame) if self._in_command_mode and self._buffer[-1:] == b"\r": rsp = self._buffer[:-1] self._buffer.clear() self.command_mode_rsp(rsp) def frame_received(self, frame): """Frame receive handler.""" LOGGER.debug("Frame received: %s", frame) self._api.frame_received(frame) def reset_command_mode(self): r"""Reset command mode and ignore '\r' character as command mode response.""" self._in_command_mode = False def _extract_frame(self): first_start = self._buffer.find(self.START) if first_start < 0: return None data = self._buffer[first_start + 1 :] frame_len, data = self._get_unescaped(data, 2) if frame_len is None: return None frame_len = int.from_bytes(frame_len, "big") frame, data = self._get_unescaped(data, frame_len) if frame is None: return None checksum, data = self._get_unescaped(data, 1) if checksum is None: return None if self._checksum(frame) != checksum[0]: # TODO: Signal decode failure so that error frame can be sent self._buffer = data return None self._buffer = data return frame def _get_unescaped(self, data, n): ret = [] idx = 0 while len(ret) < n and idx < len(data): b = data[idx] if b == self.ESCAPE[0]: idx += 1 if idx >= len(data): return None, None b = data[idx] ^ 0x020 ret.append(b) idx += 1 if len(ret) >= n: return bytes(ret), data[idx:] return None, None def _escape(self, data): ret = [] for b in data: if b in self.RESERVED: ret.append(ord(self.ESCAPE)) ret.append(b ^ 0x20) else: ret.append(b) return bytes(ret) def _checksum(self, data): return 0xFF - (sum(data) % 0x100) async def connect(device_config: Dict[str, Any], api) -> Gateway: """Connect to the device.""" transport, protocol = await zigpy.serial.create_serial_connection( loop=asyncio.get_running_loop(), protocol_factory=lambda: Gateway(api), url=device_config[zigpy.config.CONF_DEVICE_PATH], baudrate=device_config[zigpy.config.CONF_DEVICE_BAUDRATE], xonxoff=device_config[zigpy.config.CONF_DEVICE_BAUDRATE], ) await protocol.wait_until_connected() return protocol zigpy-xbee-0.21.0/zigpy_xbee/zigbee/000077500000000000000000000000001471001077200172665ustar00rootroot00000000000000zigpy-xbee-0.21.0/zigpy_xbee/zigbee/__init__.py000066400000000000000000000000611471001077200213740ustar00rootroot00000000000000"""XBee ControllerApplication implementation.""" zigpy-xbee-0.21.0/zigpy_xbee/zigbee/application.py000066400000000000000000000421611471001077200221470ustar00rootroot00000000000000"""ControllerApplication for XBee adapters.""" from __future__ import annotations import asyncio import logging import math import statistics from typing import Any import zigpy.application import zigpy.config from zigpy.config import CONF_DEVICE import zigpy.device import zigpy.exceptions import zigpy.quirks import zigpy.state import zigpy.types import zigpy.util from zigpy.zcl import foundation from zigpy.zcl.clusters.general import Groups import zigpy.zdo.types as zdo_t import zigpy_xbee import zigpy_xbee.api import zigpy_xbee.config from zigpy_xbee.exceptions import InvalidCommand from zigpy_xbee.types import EUI64, UNKNOWN_IEEE, UNKNOWN_NWK, TXOptions, TXStatus # how long coordinator would hold message for an end device in 10ms units CONF_CYCLIC_SLEEP_PERIOD = 0x0300 # end device poll timeout = 3 * SN * SP * 10ms CONF_POLL_TIMEOUT = 0x029B TIMEOUT_TX_STATUS = 120 TIMEOUT_REPLY = 5 TIMEOUT_REPLY_EXTENDED = 28 LOGGER = logging.getLogger(__name__) XBEE_ENDPOINT_ID = 0xE6 class ControllerApplication(zigpy.application.ControllerApplication): """Implementation of Zigpy ControllerApplication for XBee devices.""" CONFIG_SCHEMA = zigpy_xbee.config.CONFIG_SCHEMA def __init__(self, config: dict[str, Any]): """Initialize instance.""" super().__init__(config=config) self._api: zigpy_xbee.api.XBee | None = None self.topology.add_listener(self) async def disconnect(self): """Shutdown application.""" if self._api: await self._api.disconnect() self._api = None async def connect(self): """Connect to the device.""" api = zigpy_xbee.api.XBee(self._config[CONF_DEVICE]) await api.connect() api.set_application(self) self._api = api async def start_network(self): """Configure the module to work with Zigpy.""" association_state = await asyncio.wait_for( self._get_association_state(), timeout=4 ) # Enable ZDO passthrough await self._api._at_command("AO", 0x03) if self.state.node_info == zigpy.state.NodeInfo(): await self.load_network_info() enc_enabled = await self._api._at_command("EE") enc_options = await self._api._at_command("EO") zb_profile = await self._api._at_command("ZS") if ( enc_enabled != 1 or enc_options & 0b0010 != 0b0010 or zb_profile != 2 or association_state != 0 or self.state.node_info.nwk != 0x0000 ): raise zigpy.exceptions.NetworkNotFormed("Network is not formed") # Disable joins await self._api._at_command("NJ", 0) await self._api._at_command("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._at_command("SN", CONF_POLL_TIMEOUT) dev = zigpy.device.Device( self, self.state.node_info.ieee, self.state.node_info.nwk ) dev.status = zigpy.device.Status.ENDPOINTS_INIT dev.add_endpoint(XBEE_ENDPOINT_ID) xbee_dev = XBeeCoordinator( self, self.state.node_info.ieee, self.state.node_info.nwk, dev ) self.listener_event("raw_device_initialized", xbee_dev) self.devices[dev.ieee] = xbee_dev await self.register_endpoints() async def load_network_info(self, *, load_devices=False): """Load supported parameters of network_info and node_info from the device.""" # Load node info node_info = self.state.node_info node_info.nwk = zigpy.types.NWK(await self._api._at_command("MY")) serial_high = await self._api._at_command("SH") serial_low = await self._api._at_command("SL") node_info.ieee = zigpy.types.EUI64( (serial_high.to_bytes(4, "big") + serial_low.to_bytes(4, "big"))[::-1] ) try: if await self._api._at_command("CE") == 0x01: node_info.logical_type = zdo_t.LogicalType.Coordinator else: node_info.logical_type = zdo_t.LogicalType.EndDevice except InvalidCommand: LOGGER.warning("CE command failed, assuming node is coordinator") node_info.logical_type = zdo_t.LogicalType.Coordinator # TODO: Feature detect the XBee's exact model node_info.model = "XBee" node_info.manufacturer = "Digi" version = await self._api._at_command("VR") node_info.version = f"{int(version):#06x}" # Load network info pan_id = await self._api._at_command("OI") extended_pan_id = await self._api._at_command("ID") network_info = self.state.network_info network_info.source = f"zigpy-xbee@{zigpy_xbee.__version__}" network_info.pan_id = zigpy.types.PanId(pan_id) network_info.extended_pan_id = zigpy.types.ExtendedPanId( zigpy.types.uint64_t(extended_pan_id).serialize() ) network_info.channel = await self._api._at_command("CH") async def reset_network_info(self) -> None: """Reset Zigbee network.""" await self._api._at_command("NR", 0) async def write_network_info(self, *, network_info, node_info): """Write supported network_info and node_info parameters to the device.""" epid, _ = zigpy.types.uint64_t.deserialize( network_info.extended_pan_id.serialize() ) await self._api._queued_at("ID", epid) await self._api._queued_at("ZS", 2) scan_bitmask = 1 << (network_info.channel - 11) await self._api._queued_at("SC", scan_bitmask) await self._api._queued_at("EE", 1) await self._api._queued_at("EO", 0b0010) await self._api._queued_at("NK", network_info.network_key.key.serialize()) await self._api._queued_at("KY", network_info.tc_link_key.key.serialize()) await self._api._queued_at("NJ", 0) await self._api._queued_at("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._queued_at("SN", CONF_POLL_TIMEOUT) try: await self._api._queued_at("CE", 1) except InvalidCommand: pass await self._api._at_command("WR") await asyncio.wait_for(self._api.coordinator_started_event.wait(), timeout=10) association_state = await asyncio.wait_for( self._get_association_state(), timeout=10 ) LOGGER.debug("Association state: %s", association_state) async def _move_network_to_channel( self, new_channel: int, new_nwk_update_id: int ) -> None: """Move the coordinator to a new channel.""" scan_bitmask = 1 << (new_channel - 11) await self._api._queued_at("SC", scan_bitmask) async def energy_scan( self, channels: zigpy.types.Channels, duration_exp: int, count: int ) -> dict[int, float]: """Run an energy detection scan and returns the per-channel scan results.""" all_results = {} for _ in range(count): try: results = await self._api._at_command("ED", bytes([duration_exp])) except InvalidCommand: LOGGER.warning("Coordinator does not support energy scanning") return {c: 0 for c in channels} results = { channel: -int(rssi) for channel, rssi in zip(range(11, 27), results) } for channel, rssi in results.items(): all_results.setdefault(channel, []).append(rssi) def logistic(x: float, *, L: float = 1, x_0: float = 0, k: float = 1) -> float: """Logistic function.""" return L / (1 + math.exp(-k * (x - x_0))) def map_rssi_to_energy(rssi: int) -> float: """Remaps RSSI (in dBm) to Energy (0-255).""" RSSI_MAX = -5 RSSI_MIN = -92 return logistic( x=rssi, L=255, x_0=RSSI_MIN + 0.45 * (RSSI_MAX - RSSI_MIN), k=0.13, ) energy = { channel: map_rssi_to_energy(statistics.mean(all_rssi)) for channel, all_rssi in all_results.items() } return {channel: energy.get(channel, 0) for channel in channels} async def force_remove(self, dev): """Forcibly remove device from NCP.""" async def add_endpoint(self, descriptor: zdo_t.SimpleDescriptor) -> None: """Register a new endpoint on the device.""" self._device.replacement["endpoints"][descriptor.endpoint] = { "device_type": descriptor.device_type, "profile_id": descriptor.profile, "input_clusters": descriptor.input_clusters, "output_clusters": descriptor.output_clusters, } self._device.add_endpoint(descriptor.endpoint) async def _get_association_state(self): """Wait for Zigbee to start.""" state = await self._api._at_command("AI") while state == 0xFF: LOGGER.debug("Waiting for radio startup...") await asyncio.sleep(0.2) state = await self._api._at_command("AI") return state async def send_packet(self, packet: zigpy.types.ZigbeePacket) -> None: """Send ZigbeePacket via the device.""" LOGGER.debug("Sending packet %r", packet) try: device = self.get_device_with_address(packet.dst) except (KeyError, ValueError): device = None tx_opts = TXOptions.NONE if packet.extended_timeout: tx_opts |= TXOptions.Use_Extended_TX_Timeout if packet.dst.addr_mode == zigpy.types.AddrMode.Group: tx_opts |= 0x08 # where did this come from? long_addr = UNKNOWN_IEEE short_addr = UNKNOWN_NWK if packet.dst.addr_mode == zigpy.types.AddrMode.Broadcast: long_addr = EUI64( [ zigpy.types.uint8_t(b) for b in packet.dst.address.to_bytes(8, "little") ] ) short_addr = packet.dst.address elif packet.dst.addr_mode == zigpy.types.AddrMode.Group: short_addr = packet.dst.address elif packet.dst.addr_mode == zigpy.types.AddrMode.IEEE: long_addr = EUI64(packet.dst.address) elif device is not None: long_addr = EUI64(device.ieee) short_addr = device.nwk else: raise zigpy.exceptions.DeliveryError( "Cannot send a packet to a device without a known IEEE address" ) send_req = self._api.tx_explicit( long_addr, short_addr, packet.src_ep or 0, packet.dst_ep or 0, packet.cluster_id, packet.profile_id, packet.radius, tx_opts, packet.data.serialize(), ) try: v = await asyncio.wait_for(send_req, timeout=TIMEOUT_TX_STATUS) except asyncio.TimeoutError: raise zigpy.exceptions.DeliveryError( "Timeout waiting for ACK", status=TXStatus.NETWORK_ACK_FAILURE ) if v != TXStatus.SUCCESS: raise zigpy.exceptions.DeliveryError( f"Failed to deliver packet: {v!r}", status=v ) @zigpy.util.retryable_request() def remote_at_command( self, nwk, cmd_name, *args, apply_changes=True, encryption=True ): """Execute AT command on another XBee module in the network.""" LOGGER.debug("Remote AT%s command: %s", cmd_name, args) options = zigpy.types.uint8_t(0) if apply_changes: options |= 0x02 if encryption: options |= 0x10 dev = self.get_device(nwk=nwk) return self._api._remote_at_command(dev.ieee, nwk, options, cmd_name, *args) async def permit_ncp(self, time_s=60): """Permit join.""" assert 0 <= time_s <= 254 await self._api._at_command("NJ", time_s) await self._api._at_command("AC") async def permit_with_link_key( self, node: EUI64, link_key: zigpy.types.KeyData, time_s: int = 500, key_type=0 ): """Permits a new device to join with the given IEEE and link key.""" assert 0x1E <= time_s <= 0xFFFF await self._api._at_command("KT", time_s) reserved = 0xFFFE # Key type: # 0 = Pre-configured Link Key (KY command of the joining device) # 1 = Install Code With CRC (I? command of the joining device) await self._api.register_joining_device(node, reserved, key_type, link_key) def handle_modem_status(self, status): """Handle changed Modem Status of the device.""" LOGGER.info("Modem status update: %s (%s)", status.name, status.value) def handle_rx( self, src_ieee, src_nwk, src_ep, dst_ep, cluster_id, profile_id, rxopts, data ): """Handle receipt of Zigbee data from the device.""" src = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=src_nwk ) dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=self.state.node_info.nwk ) if src == dst: LOGGER.info("handle_rx self addressed") try: self._device.update_last_seen() except KeyError: pass self.packet_received( zigpy.types.ZigbeePacket( src=src, src_ep=src_ep, dst=dst, dst_ep=dst_ep, tsn=None, profile_id=profile_id, cluster_id=cluster_id, data=zigpy.types.SerializableBytes(data), ) ) def neighbors_updated( self, ieee: zigpy.types.EUI64, neighbors: list[zdo_t.Neighbor] ) -> None: """Neighbor update from Mgmt_Lqi_req.""" for neighbor in neighbors: if neighbor.relationship == zdo_t.Neighbor.Relationship.Parent: device = self.get_device(ieee=ieee) device.radio_details(lqi=neighbor.lqi) elif neighbor.relationship == zdo_t.Neighbor.Relationship.Child: try: child_device = self.get_device(ieee=neighbor.ieee) child_device.radio_details(lqi=neighbor.lqi) except KeyError: LOGGER.warning("Unknown device %r", neighbor.ieee) def routes_updated( self, ieee: zigpy.types.EUI64, routes: list[zdo_t.Route] ) -> None: """Route update from Mgmt_Rtg_req.""" self.create_task( self._routes_updated(ieee, routes), f"routes_updated-ieee={ieee}" ) async def _routes_updated( self, ieee: zigpy.types.EUI64, routes: list[zdo_t.Route] ) -> None: """Get RSSI for adjacent routers on Route update from Mgmt_Rtg_req.""" for route in routes: if ( route.DstNWK == self.state.node_info.nwk and route.NextHop == self.state.node_info.nwk and route.RouteStatus == zdo_t.RouteStatus.Active ): device = self.get_device(ieee=ieee) rssi = await self._api._at_command("DB") device.radio_details(rssi=-rssi) break class XBeeCoordinator(zigpy.quirks.CustomDevice): """Zigpy Device representing Coordinator.""" class XBeeGroup(zigpy.quirks.CustomCluster, Groups): """XBeeGroup custom cluster.""" cluster_id = 0x0006 class XBeeGroupResponse(zigpy.quirks.CustomCluster, Groups): """XBeeGroupResponse custom cluster.""" cluster_id = 0x8006 ep_attribute = "xbee_groups_response" client_commands = { **Groups.client_commands, 0x04: foundation.ZCLCommandDef( "remove_all_response", {"status": foundation.Status}, direction=foundation.Direction.Client_to_Server, ), } def __init__(self, *args, **kwargs): """Initialize instance.""" super().__init__(*args, **kwargs) self.node_desc = zdo_t.NodeDescriptor( logical_type=zdo_t.LogicalType.Coordinator, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=zdo_t.NodeDescriptor.FrequencyBand.Freq2400MHz, mac_capability_flags=( zdo_t.NodeDescriptor.MACCapabilityFlags.AllocateAddress | zdo_t.NodeDescriptor.MACCapabilityFlags.RxOnWhenIdle | zdo_t.NodeDescriptor.MACCapabilityFlags.MainsPowered | zdo_t.NodeDescriptor.MACCapabilityFlags.FullFunctionDevice ), manufacturer_code=4126, maximum_buffer_size=82, maximum_incoming_transfer_size=255, server_mask=11264, maximum_outgoing_transfer_size=255, descriptor_capability_field=zdo_t.NodeDescriptor.DescriptorCapability.NONE, ) replacement = { "manufacturer": "Digi", "model": "XBee", "endpoints": { XBEE_ENDPOINT_ID: { "device_type": 0x0050, "profile_id": 0xC105, "input_clusters": [XBeeGroup, XBeeGroupResponse], "output_clusters": [], } }, }