├── .coveragerc
├── .github
└── workflows
│ ├── ci.yml
│ ├── matchers
│ ├── codespell.json
│ ├── flake8.json
│ └── python.json
│ └── publish-to-pypi.yml
├── .gitignore
├── .pre-commit-config.yaml
├── COPYING
├── Contributors.md
├── LICENSE
├── README.md
├── pyproject.toml
├── requirements_test.txt
├── setup.py
├── tests
├── __init__.py
├── test_api.py
├── test_application.py
├── test_types.py
└── test_uart.py
├── tox.ini
└── zigpy_xbee
├── __init__.py
├── api.py
├── config.py
├── exceptions.py
├── types.py
├── uart.py
└── zigbee
├── __init__.py
└── application.py
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | source = zigpy_xbee
3 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | # yamllint disable-line rule:truthy
4 | on:
5 | push:
6 | pull_request: ~
7 |
8 | jobs:
9 | shared-ci:
10 | uses: zigpy/workflows/.github/workflows/ci.yml@main
11 | with:
12 | CODE_FOLDER: zigpy_xbee
13 | CACHE_VERSION: 2
14 | PYTHON_VERSION_DEFAULT: 3.9.15
15 | PRE_COMMIT_CACHE_PATH: ~/.cache/pre-commit
16 | MINIMUM_COVERAGE_PERCENTAGE: 100
17 | secrets:
18 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
19 |
--------------------------------------------------------------------------------
/.github/workflows/matchers/codespell.json:
--------------------------------------------------------------------------------
1 | {
2 | "problemMatcher": [
3 | {
4 | "owner": "codespell",
5 | "severity": "warning",
6 | "pattern": [
7 | {
8 | "regexp": "^(.+):(\\d+):\\s(.+)$",
9 | "file": 1,
10 | "line": 2,
11 | "message": 3
12 | }
13 | ]
14 | }
15 | ]
16 | }
17 |
--------------------------------------------------------------------------------
/.github/workflows/matchers/flake8.json:
--------------------------------------------------------------------------------
1 | {
2 | "problemMatcher": [
3 | {
4 | "owner": "flake8-error",
5 | "severity": "error",
6 | "pattern": [
7 | {
8 | "regexp": "^(.*):(\\d+):(\\d+):\\s([EF]\\d{3}\\s.*)$",
9 | "file": 1,
10 | "line": 2,
11 | "column": 3,
12 | "message": 4
13 | }
14 | ]
15 | },
16 | {
17 | "owner": "flake8-warning",
18 | "severity": "warning",
19 | "pattern": [
20 | {
21 | "regexp": "^(.*):(\\d+):(\\d+):\\s([CDNW]\\d{3}\\s.*)$",
22 | "file": 1,
23 | "line": 2,
24 | "column": 3,
25 | "message": 4
26 | }
27 | ]
28 | }
29 | ]
30 | }
31 |
--------------------------------------------------------------------------------
/.github/workflows/matchers/python.json:
--------------------------------------------------------------------------------
1 | {
2 | "problemMatcher": [
3 | {
4 | "owner": "python",
5 | "pattern": [
6 | {
7 | "regexp": "^\\s*File\\s\\\"(.*)\\\",\\sline\\s(\\d+),\\sin\\s(.*)$",
8 | "file": 1,
9 | "line": 2
10 | },
11 | {
12 | "regexp": "^\\s*raise\\s(.*)\\(\\'(.*)\\'\\)$",
13 | "message": 2
14 | }
15 | ]
16 | }
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/.github/workflows/publish-to-pypi.yml:
--------------------------------------------------------------------------------
1 | name: Publish distributions to PyPI
2 | on:
3 | release:
4 | types:
5 | - published
6 |
7 | jobs:
8 | shared-build-and-publish:
9 | uses: zigpy/workflows/.github/workflows/publish-to-pypi.yml@main
10 | secrets:
11 | PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
12 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | coverage.xml
45 | *,cover
46 | .pytest_cache/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Sphinx documentation
53 | docs/_build/
54 |
55 | # PyBuilder
56 | target/
57 |
58 | # pyenv
59 | .python-version
60 |
61 | # dotenv
62 | .env
63 |
64 | # virtualenv
65 | .venv/
66 | venv/
67 | ENV/
68 |
69 | # Editor temp files
70 | .*.swp
71 | tags
72 |
73 | # Visual Studio Code
74 | .vscode
75 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/asottile/pyupgrade
3 | rev: v3.15.0
4 | hooks:
5 | - id: pyupgrade
6 | args: [--py38-plus]
7 |
8 | - repo: https://github.com/PyCQA/autoflake
9 | rev: v2.2.1
10 | hooks:
11 | - id: autoflake
12 |
13 | - repo: https://github.com/psf/black
14 | rev: 23.9.1
15 | hooks:
16 | - id: black
17 | args:
18 | - --quiet
19 | - --safe
20 |
21 | - repo: https://github.com/PyCQA/flake8
22 | rev: 6.1.0
23 | hooks:
24 | - id: flake8
25 | additional_dependencies:
26 | - flake8-docstrings==1.7.0
27 | - pydocstyle==6.3.0
28 | - Flake8-pyproject==1.2.3
29 | - flake8-bugbear==23.9.16
30 | - flake8-comprehensions==3.14.0
31 | - flake8_2020==1.8.1
32 | - mccabe==0.7.0
33 | - pycodestyle==2.11.0
34 | - pyflakes==3.1.0
35 | - flake8-async==22.11.14
36 |
37 | - repo: https://github.com/PyCQA/isort
38 | rev: 5.12.0
39 | hooks:
40 | - id: isort
41 |
42 | - repo: https://github.com/codespell-project/codespell
43 | rev: v2.2.6
44 | hooks:
45 | - id: codespell
46 | args:
47 | - --ignore-words-list=ser,nd,hass
48 | - --skip="./.*"
49 | - --quiet-level=2
50 |
51 | - repo: https://github.com/pre-commit/mirrors-mypy
52 | rev: v1.6.0
53 | hooks:
54 | - id: mypy
55 | additional_dependencies:
56 | - zigpy
57 |
58 | - repo: https://github.com/charliermarsh/ruff-pre-commit
59 | rev: v0.0.291
60 | hooks:
61 | - id: ruff
62 | args:
63 | - --fix
64 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | zigpy-xbee
2 | Copyright (C) 2018 Russell Cloran
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 |
--------------------------------------------------------------------------------
/Contributors.md:
--------------------------------------------------------------------------------
1 | # Contributors
2 | - [Alexei Chetroi] (https://github.com/Adminiuga)
3 | - [Russell Cloran] (https://github.com/rcloran)
4 | - [damarco] (https://github.com/damarco)
5 | - [Hedda] (https://github.com/Hedda)
6 | - [Shulyaka] (https://github.com/Shulyaka)
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # zigpy-xbee
2 |
3 | [](https://github.com/zigpy/zigpy-xbee/actions)
4 | [](https://codecov.io/gh/zigpy/zigpy-xbee)
5 |
6 | [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.
7 |
8 | - https://github.com/zigpy/zigpy-xbee
9 |
10 | Digi XBee is the brand name of a family of form factor compatible radio modules from Digi International.
11 |
12 | 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.
13 |
14 | - https://en.wikipedia.org/wiki/XBee
15 |
16 | 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.
17 |
18 | [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/)**
19 |
20 | ## Compatible hardware
21 |
22 | 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.
23 |
24 | ### Known working XBee based Zigbee radio modules for Zigpy
25 |
26 | These are XBee Zigbee based radios that have been tested with the [zigpy-xbee](https://github.com/zigpy/zigpy-xbee) library for zigpy
27 |
28 | - [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
29 | - 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)
30 | - [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))
31 |
32 | # Port configuration
33 |
34 | - To configure __usb__ port path for your XBee serial device, just specify the TTY (serial com) port, example : `/dev/ttyACM0`
35 |
36 | Note! Users can change UART baud rate of your Digi XBee using the Digi's XCTU configuration tool. Using XCTU tool
37 | enable the API communication mode -- `ATAP2`, set baudrate to 57600 -- `ATBD6`, save parameters.
38 |
39 | # Testing new releases
40 |
41 | Testing a new release of the zigpy-xbee library before it is released in Home Assistant.
42 |
43 | If you are using Supervised Home Assistant (formerly known as the Hassio/Hass.io distro):
44 | - Add https://github.com/home-assistant/hassio-addons-development as "add-on" repository
45 | - Install "Custom deps deployment" addon
46 | - Update config like:
47 | ```
48 | pypi:
49 | - zigpy-xbee==0.12.0
50 | apk: []
51 | ```
52 | where 0.12.0 is the new version
53 | - Start the addon
54 |
55 | If you are instead using some custom python installation of Home Assistant then do this:
56 | - Activate your python virtual env
57 | - Update package with ``pip``
58 | ```
59 | pip install zigpy-xbee==0.12.0
60 |
61 | # Releases of zigpy-xbee via PyPI
62 |
63 | New packages of tagged versions are also released via the "zigpy-xbee" project on PyPI
64 | - https://pypi.org/project/zigpy-xbee/
65 | - https://pypi.org/project/zigpy-xbee/#history
66 | - https://pypi.org/project/zigpy-xbee/#files
67 |
68 | Older packages of tagged versions are still available on the "zigpy-xbee-homeassistant" project on PyPI
69 | - https://pypi.org/project/zigpy-xbee-homeassistant/
70 |
71 | # How to contribute
72 |
73 | If you are looking to make a contribution to this project we suggest that you follow the steps in these guides:
74 | - https://github.com/firstcontributions/first-contributions/blob/master/README.md
75 | - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md
76 |
77 | 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.
78 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=61.0.0", "wheel", "setuptools-git-versioning<2"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "zigpy-xbee"
7 | dynamic = ["version"]
8 | description = "A library which communicates with XBee radios for zigpy"
9 | urls = {repository = "https://github.com/zigpy/zigpy-xbee"}
10 | authors = [
11 | {name = "Russell Cloran", email = "rcloran@gmail.com"}
12 | ]
13 | readme = "README.md"
14 | license = {text = "GPL-3.0"}
15 | requires-python = ">=3.8"
16 | dependencies = [
17 | "zigpy>=0.70.0",
18 | ]
19 |
20 | [tool.setuptools.packages.find]
21 | exclude = ["tests", "tests.*"]
22 |
23 | [project.optional-dependencies]
24 | testing = [
25 | "pytest>=7.1.2",
26 | "asynctest>=0.13.0",
27 | "pytest-asyncio>=0.19.0",
28 | ]
29 |
30 | [tool.setuptools-git-versioning]
31 | enabled = true
32 |
33 | [tool.isort]
34 | profile = "black"
35 | # will group `import x` and `from x import` of the same module.
36 | force_sort_within_sections = true
37 | known_first_party = ["zigpy_xbee", "tests"]
38 | forced_separate = "tests"
39 | combine_as_imports = true
40 |
41 | [tool.mypy]
42 | ignore_errors = true
43 |
44 | [tool.pytest.ini_options]
45 | asyncio_mode = "auto"
46 | asyncio_default_fixture_loop_scope = "function"
47 |
48 | [tool.flake8]
49 | exclude = [".venv", ".git", ".tox", "docs", "venv", "bin", "lib", "deps", "build"]
50 | # To work with Black
51 | max-line-length = 88
52 | # W503: Line break occurred before a binary operator
53 | # E203: Whitespace before ':'
54 | # D202 No blank lines allowed after function docstring
55 | ignore = ["W503", "E203", "D202"]
56 |
--------------------------------------------------------------------------------
/requirements_test.txt:
--------------------------------------------------------------------------------
1 | # Test dependencies.
2 |
3 | asynctest
4 | isort
5 | black
6 | flake8
7 | codecov
8 | colorlog
9 | codespell
10 | mypy==1.6.0
11 | pre-commit
12 | pylint
13 | pytest-cov
14 | pytest-sugar
15 | pytest-timeout
16 | pytest-asyncio>=0.17
17 | pytest>=7.1.3
18 | zigpy>=0.56.0
19 | ruff>=0.0.291
20 | Flake8-pyproject
21 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """Setup stub for legacy builds."""
2 |
3 | import setuptools
4 |
5 | if __name__ == "__main__":
6 | setuptools.setup()
7 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | """Tests for zigpy_xbee."""
2 |
--------------------------------------------------------------------------------
/tests/test_api.py:
--------------------------------------------------------------------------------
1 | """Tests for API."""
2 |
3 | import asyncio
4 | from unittest import mock
5 |
6 | import pytest
7 | import zigpy.config
8 | import zigpy.exceptions
9 | import zigpy.types as t
10 |
11 | from zigpy_xbee import api as xbee_api, types as xbee_t
12 | from zigpy_xbee.exceptions import ATCommandError, ATCommandException, InvalidCommand
13 | from zigpy_xbee.zigbee.application import ControllerApplication
14 |
15 | DEVICE_CONFIG = zigpy.config.SCHEMA_DEVICE(
16 | {
17 | zigpy.config.CONF_DEVICE_PATH: "/dev/null",
18 | zigpy.config.CONF_DEVICE_BAUDRATE: 57600,
19 | }
20 | )
21 |
22 |
23 | @pytest.fixture
24 | def api():
25 | """Sample XBee API fixture."""
26 | api = xbee_api.XBee(DEVICE_CONFIG)
27 | api._uart = mock.AsyncMock()
28 | return api
29 |
30 |
31 | async def test_connect():
32 | """Test connect."""
33 | api = xbee_api.XBee(DEVICE_CONFIG)
34 | api._command = mock.AsyncMock(spec=api._command)
35 |
36 | with mock.patch("zigpy_xbee.uart.connect"):
37 | await api.connect()
38 |
39 |
40 | async def test_connect_initial_timeout_success():
41 | """Test connect, initial command times out."""
42 | api = xbee_api.XBee(DEVICE_CONFIG)
43 | api._at_command = mock.AsyncMock(side_effect=asyncio.TimeoutError)
44 | api.init_api_mode = mock.AsyncMock(return_value=True)
45 |
46 | with mock.patch("zigpy_xbee.uart.connect"):
47 | await api.connect()
48 |
49 |
50 | async def test_connect_initial_timeout_failure():
51 | """Test connect, initial command times out."""
52 | api = xbee_api.XBee(DEVICE_CONFIG)
53 | api._at_command = mock.AsyncMock(side_effect=asyncio.TimeoutError)
54 | api.init_api_mode = mock.AsyncMock(return_value=False)
55 |
56 | with mock.patch("zigpy_xbee.uart.connect") as mock_connect:
57 | with pytest.raises(zigpy.exceptions.APIException):
58 | await api.connect()
59 |
60 | assert mock_connect.return_value.disconnect.mock_calls == [mock.call()]
61 |
62 |
63 | async def test_disconnect(api):
64 | """Test connection close."""
65 | uart = api._uart
66 | await api.disconnect()
67 |
68 | assert api._uart is None
69 | assert uart.disconnect.call_count == 1
70 |
71 |
72 | def test_commands():
73 | """Test command requests and command responses description."""
74 | import string
75 |
76 | anum = string.ascii_letters + string.digits + "_"
77 | commands = {**xbee_api.COMMAND_REQUESTS, **xbee_api.COMMAND_RESPONSES}
78 |
79 | for cmd_name, cmd_opts in commands.items():
80 | assert isinstance(cmd_name, str) is True
81 | assert all(c in anum for c in cmd_name), cmd_name
82 | assert len(cmd_opts) == 3
83 | cmd_id, schema, reply = cmd_opts
84 | assert isinstance(cmd_id, int) is True
85 | assert isinstance(schema, tuple) is True
86 | assert reply is None or isinstance(reply, int)
87 |
88 |
89 | async def test_command(api):
90 | """Test AT commands."""
91 |
92 | def mock_api_frame(name, *args):
93 | c = xbee_api.COMMAND_REQUESTS[name]
94 | return mock.sentinel.api_frame_data, c[2]
95 |
96 | api._api_frame = mock.MagicMock(side_effect=mock_api_frame)
97 | api._uart.send = mock.MagicMock()
98 |
99 | for cmd_name, cmd_opts in xbee_api.COMMAND_REQUESTS.items():
100 | cmd_id, schema, expect_reply = cmd_opts
101 | ret = api._command(cmd_name, mock.sentinel.cmd_data)
102 | if expect_reply:
103 | assert asyncio.isfuture(ret) is True
104 | ret.cancel()
105 | else:
106 | assert ret is None
107 | assert api._api_frame.call_count == 1
108 | assert api._api_frame.call_args[0][0] == cmd_name
109 | assert api._api_frame.call_args[0][1] == api._seq - 1
110 | assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data
111 | assert api._uart.send.call_count == 1
112 | assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
113 | api._api_frame.reset_mock()
114 | api._uart.send.reset_mock()
115 |
116 | ret = api._command(cmd_name, mock.sentinel.cmd_data, mask_frame_id=True)
117 | assert ret is None
118 | assert api._api_frame.call_count == 1
119 | assert api._api_frame.call_args[0][0] == cmd_name
120 | assert api._api_frame.call_args[0][1] == 0
121 | assert api._api_frame.call_args[0][2] == mock.sentinel.cmd_data
122 | assert api._uart.send.call_count == 1
123 | assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
124 | api._api_frame.reset_mock()
125 | api._uart.send.reset_mock()
126 |
127 |
128 | async def test_command_not_connected(api):
129 | """Test AT command while disconnected to the device."""
130 | api._uart = None
131 |
132 | def mock_api_frame(name, *args):
133 | return mock.sentinel.api_frame_data, api._seq
134 |
135 | api._api_frame = mock.MagicMock(side_effect=mock_api_frame)
136 |
137 | for cmd, _cmd_opts in xbee_api.COMMAND_REQUESTS.items():
138 | with pytest.raises(zigpy.exceptions.APIException):
139 | await api._command(cmd, mock.sentinel.cmd_data)
140 | assert api._api_frame.call_count == 0
141 | api._api_frame.reset_mock()
142 |
143 |
144 | async def _test_at_or_queued_at_command(api, cmd, monkeypatch, do_reply=True):
145 | monkeypatch.setattr(
146 | t, "serialize", mock.MagicMock(return_value=mock.sentinel.serialize)
147 | )
148 | """Call api._at_command() or api._queued_at() with every possible command."""
149 |
150 | def mock_command(name, *args):
151 | rsp = xbee_api.COMMAND_REQUESTS[name][2]
152 | ret = None
153 | if rsp:
154 | ret = asyncio.Future()
155 | if do_reply:
156 | ret.set_result(mock.sentinel.at_result)
157 | return ret
158 |
159 | api._command = mock.MagicMock(side_effect=mock_command)
160 | api._seq = mock.sentinel.seq
161 |
162 | for at_cmd in xbee_api.AT_COMMANDS:
163 | res = await cmd(at_cmd, mock.sentinel.args)
164 | assert t.serialize.call_count == 1
165 | assert api._command.call_count == 1
166 | assert api._command.call_args[0][0] in ("at", "queued_at")
167 | assert api._command.call_args[0][1] == at_cmd.encode("ascii")
168 | assert api._command.call_args[0][2] == mock.sentinel.serialize
169 | assert res == mock.sentinel.at_result
170 | t.serialize.reset_mock()
171 | api._command.reset_mock()
172 |
173 |
174 | async def test_at_command(api, monkeypatch):
175 | """Test api._at_command."""
176 | await _test_at_or_queued_at_command(api, api._at_command, monkeypatch)
177 |
178 |
179 | async def test_at_command_no_response(api, monkeypatch):
180 | """Test api._at_command with no response."""
181 | with pytest.raises(asyncio.TimeoutError):
182 | await _test_at_or_queued_at_command(
183 | api, api._at_command, monkeypatch, do_reply=False
184 | )
185 |
186 |
187 | async def test_queued_at_command(api, monkeypatch):
188 | """Test api._queued_at."""
189 | await _test_at_or_queued_at_command(api, api._queued_at, monkeypatch)
190 |
191 |
192 | async def _test_remote_at_command(api, monkeypatch, do_reply=True):
193 | monkeypatch.setattr(
194 | t, "serialize", mock.MagicMock(return_value=mock.sentinel.serialize)
195 | )
196 | """Call api._remote_at_command()."""
197 |
198 | def mock_command(name, *args):
199 | rsp = xbee_api.COMMAND_REQUESTS[name][2]
200 | ret = None
201 | if rsp:
202 | ret = asyncio.Future()
203 | if do_reply:
204 | ret.set_result(mock.sentinel.at_result)
205 | return ret
206 |
207 | api._command = mock.MagicMock(side_effect=mock_command)
208 | api._seq = mock.sentinel.seq
209 |
210 | for at_cmd in xbee_api.AT_COMMANDS:
211 | res = await api._remote_at_command(
212 | mock.sentinel.ieee,
213 | mock.sentinel.nwk,
214 | mock.sentinel.opts,
215 | at_cmd,
216 | mock.sentinel.args,
217 | )
218 | assert t.serialize.call_count == 1
219 | assert api._command.call_count == 1
220 | assert api._command.call_args[0][0] == "remote_at"
221 | assert api._command.call_args[0][1] == mock.sentinel.ieee
222 | assert api._command.call_args[0][2] == mock.sentinel.nwk
223 | assert api._command.call_args[0][3] == mock.sentinel.opts
224 | assert api._command.call_args[0][4] == at_cmd.encode("ascii")
225 | assert api._command.call_args[0][5] == mock.sentinel.serialize
226 | assert res == mock.sentinel.at_result
227 | t.serialize.reset_mock()
228 | api._command.reset_mock()
229 |
230 |
231 | async def test_remote_at_cmd(api, monkeypatch):
232 | """Test remote AT command."""
233 | await _test_remote_at_command(api, monkeypatch)
234 |
235 |
236 | async def test_remote_at_cmd_no_rsp(api, monkeypatch):
237 | """Test remote AT command with no response."""
238 | monkeypatch.setattr(xbee_api, "REMOTE_AT_COMMAND_TIMEOUT", 0.1)
239 | with pytest.raises(asyncio.TimeoutError):
240 | await _test_remote_at_command(api, monkeypatch, do_reply=False)
241 |
242 |
243 | def test_api_frame(api):
244 | """Test api._api_frame."""
245 | ieee = t.EUI64([t.uint8_t(a) for a in range(0, 8)])
246 | for cmd_name, cmd_opts in xbee_api.COMMAND_REQUESTS.items():
247 | cmd_id, schema, repl = cmd_opts
248 | if schema:
249 | args = [ieee if issubclass(a, t.EUI64) else a() for a in schema]
250 | frame, repl = api._api_frame(cmd_name, *args)
251 | else:
252 | frame, repl = api._api_frame(cmd_name)
253 |
254 |
255 | def test_frame_received(api, monkeypatch):
256 | """Test api.frame_received()."""
257 | monkeypatch.setattr(
258 | t,
259 | "deserialize",
260 | mock.MagicMock(
261 | return_value=(
262 | [
263 | mock.sentinel.arg_0,
264 | mock.sentinel.arg_1,
265 | mock.sentinel.arg_2,
266 | mock.sentinel.arg_3,
267 | mock.sentinel.arg_4,
268 | mock.sentinel.arg_5,
269 | mock.sentinel.arg_6,
270 | mock.sentinel.arg_7,
271 | mock.sentinel.arg_8,
272 | ],
273 | b"",
274 | )
275 | ),
276 | )
277 | my_handler = mock.MagicMock()
278 |
279 | for cmd, cmd_opts in xbee_api.COMMAND_RESPONSES.items():
280 | cmd_id = cmd_opts[0]
281 | payload = b"\x01\x02\x03\x04"
282 | data = cmd_id.to_bytes(1, "big") + payload
283 | setattr(api, f"_handle_{cmd}", my_handler)
284 | api.frame_received(data)
285 | assert t.deserialize.call_count == 1
286 | assert t.deserialize.call_args[0][0] == payload
287 | assert my_handler.call_count == 1
288 | assert my_handler.call_args[0][0] == mock.sentinel.arg_0
289 | assert my_handler.call_args[0][1] == mock.sentinel.arg_1
290 | assert my_handler.call_args[0][2] == mock.sentinel.arg_2
291 | assert my_handler.call_args[0][3] == mock.sentinel.arg_3
292 | t.deserialize.reset_mock()
293 | my_handler.reset_mock()
294 |
295 |
296 | def test_frame_received_no_handler(api, monkeypatch):
297 | """Test frame received with no handler defined."""
298 | monkeypatch.setattr(
299 | t, "deserialize", mock.MagicMock(return_value=(b"deserialized data", b""))
300 | )
301 | my_handler = mock.MagicMock()
302 | cmd = "no_handler"
303 | cmd_id = 0x00
304 | xbee_api.COMMAND_RESPONSES[cmd] = (cmd_id, (), None)
305 | api._commands_by_id[cmd_id] = cmd
306 |
307 | cmd_opts = xbee_api.COMMAND_RESPONSES[cmd]
308 | cmd_id = cmd_opts[0]
309 | payload = b"\x01\x02\x03\x04"
310 | data = cmd_id.to_bytes(1, "big") + payload
311 | api.frame_received(data)
312 | assert t.deserialize.call_count == 1
313 | assert t.deserialize.call_args[0][0] == payload
314 | assert my_handler.call_count == 0
315 |
316 |
317 | def _handle_at_response(api, tsn, status, at_response=b""):
318 | """Call api._handle_at_response."""
319 | data = (tsn, b"AI", status, at_response)
320 | response = asyncio.Future()
321 | api._awaiting[tsn] = (response,)
322 | api._handle_at_response(*data)
323 | return response
324 |
325 |
326 | def test_handle_at_response_none(api):
327 | """Test AT successful response with no value."""
328 | tsn = 123
329 | fut = _handle_at_response(api, tsn, 0)
330 | assert fut.done() is True
331 | assert fut.result() is None
332 | assert fut.exception() is None
333 |
334 |
335 | def test_handle_at_response_data(api):
336 | """Test AT successful response with data."""
337 | tsn = 123
338 | status, response = 0, 0x23
339 | fut = _handle_at_response(api, tsn, status, [response])
340 | assert fut.done() is True
341 | assert fut.result() == response
342 | assert fut.exception() is None
343 |
344 |
345 | def test_handle_at_response_error(api):
346 | """Test AT unsuccessful response."""
347 | tsn = 123
348 | status, response = 1, 0x23
349 | fut = _handle_at_response(api, tsn, status, [response])
350 | assert fut.done() is True
351 | assert isinstance(fut.exception(), ATCommandError)
352 |
353 |
354 | def test_handle_at_response_invalid_command(api):
355 | """Test invalid AT command response."""
356 | tsn = 123
357 | status, response = 2, 0x23
358 | fut = _handle_at_response(api, tsn, status, [response])
359 | assert fut.done() is True
360 | assert isinstance(fut.exception(), InvalidCommand)
361 |
362 |
363 | def test_handle_at_response_undef_error(api):
364 | """Test AT unsuccessful response with undefined error."""
365 | tsn = 123
366 | status, response = 0xEE, 0x23
367 | fut = _handle_at_response(api, tsn, status, [response])
368 | assert fut.done() is True
369 | assert isinstance(fut.exception(), ATCommandException)
370 |
371 |
372 | def test_handle_remote_at_rsp(api):
373 | """Test handling the response."""
374 | api._handle_at_response = mock.MagicMock()
375 | s = mock.sentinel
376 | api._handle_remote_at_response(s.frame_id, s.ieee, s.nwk, s.cmd, s.status, s.data)
377 | assert api._handle_at_response.call_count == 1
378 | assert api._handle_at_response.call_args[0][0] == s.frame_id
379 | assert api._handle_at_response.call_args[0][1] == s.cmd
380 | assert api._handle_at_response.call_args[0][2] == s.status
381 | assert api._handle_at_response.call_args[0][3] == s.data
382 |
383 |
384 | def _send_modem_event(api, event):
385 | """Call api._handle_modem_status()."""
386 | api._app = mock.MagicMock(spec=ControllerApplication)
387 | api._handle_modem_status(event)
388 | assert api._app.handle_modem_status.call_count == 1
389 | assert api._app.handle_modem_status.call_args[0][0] == event
390 |
391 |
392 | def test_handle_modem_status(api):
393 | """Test api._handle_modem_status()."""
394 | api._running.clear()
395 | api._reset.set()
396 | _send_modem_event(api, xbee_t.ModemStatus.COORDINATOR_STARTED)
397 | assert api.is_running is True
398 | assert api.reset_event.is_set() is True
399 |
400 | api._running.set()
401 | api._reset.set()
402 | _send_modem_event(api, xbee_t.ModemStatus.DISASSOCIATED)
403 | assert api.is_running is False
404 | assert api.reset_event.is_set() is True
405 |
406 | api._running.set()
407 | api._reset.clear()
408 | _send_modem_event(api, xbee_t.ModemStatus.HARDWARE_RESET)
409 | assert api.is_running is False
410 | assert api.reset_event.is_set() is True
411 |
412 |
413 | def test_handle_explicit_rx_indicator(api):
414 | """Test receiving explicit_rx_indicator frame."""
415 | s = mock.sentinel
416 | data = [
417 | s.src_ieee,
418 | s.src_nwk,
419 | s.src_ep,
420 | s.dst_ep,
421 | s.cluster_id,
422 | s.profile,
423 | s.opts,
424 | b"abcdef",
425 | ]
426 | api._app = mock.MagicMock()
427 | api._app.handle_rx = mock.MagicMock()
428 | api._handle_explicit_rx_indicator(*data)
429 | assert api._app.handle_rx.call_count == 1
430 |
431 |
432 | def _handle_tx_status(api, status, wrong_frame_id=False):
433 | """Call api._handle_tx_status."""
434 | status = xbee_t.TXStatus(status)
435 | frame_id = 0x12
436 | send_fut = mock.MagicMock(spec=asyncio.Future)
437 | api._awaiting[frame_id] = (send_fut,)
438 | s = mock.sentinel
439 | if wrong_frame_id:
440 | frame_id += 1
441 | api._handle_tx_status(
442 | frame_id, s.dst_nwk, s.retries, status, xbee_t.DiscoveryStatus()
443 | )
444 | return send_fut
445 |
446 |
447 | def test_handle_tx_status_success(api):
448 | """Test handling successful TX Status."""
449 | fut = _handle_tx_status(api, xbee_t.TXStatus.SUCCESS)
450 | assert len(api._awaiting) == 0
451 | assert fut.set_result.call_count == 1
452 | assert fut.set_exception.call_count == 0
453 |
454 |
455 | def test_handle_tx_status_except(api):
456 | """Test exceptional TXStatus."""
457 | fut = _handle_tx_status(api, xbee_t.TXStatus.ADDRESS_NOT_FOUND)
458 | assert len(api._awaiting) == 0
459 | assert fut.set_result.call_count == 0
460 | assert fut.set_exception.call_count == 1
461 |
462 |
463 | def test_handle_tx_status_unexpected(api):
464 | """Test TX status reply on unexpected frame."""
465 | fut = _handle_tx_status(api, 1, wrong_frame_id=True)
466 | assert len(api._awaiting) == 1
467 | assert fut.set_result.call_count == 0
468 | assert fut.set_exception.call_count == 0
469 |
470 |
471 | def test_handle_tx_status_duplicate(api):
472 | """Test TX status duplicate reply."""
473 | status = xbee_t.TXStatus.SUCCESS
474 | frame_id = 0x12
475 | send_fut = mock.MagicMock(spec=asyncio.Future)
476 | send_fut.set_result.side_effect = asyncio.InvalidStateError
477 | api._awaiting[frame_id] = (send_fut,)
478 | s = mock.sentinel
479 | api._handle_tx_status(frame_id, s.dst_nwk, s.retries, status, s.disc)
480 | assert len(api._awaiting) == 0
481 | assert send_fut.set_result.call_count == 1
482 | assert send_fut.set_exception.call_count == 0
483 |
484 |
485 | def test_handle_registration_status(api):
486 | """Test device registration status."""
487 | frame_id = 0x12
488 | status = xbee_t.RegistrationStatus.SUCCESS
489 | fut = asyncio.Future()
490 | api._awaiting[frame_id] = (fut,)
491 | api._handle_registration_status(frame_id, status)
492 | assert fut.done() is True
493 | assert fut.result() == xbee_t.RegistrationStatus.SUCCESS
494 | assert fut.exception() is None
495 |
496 | frame_id = 0x13
497 | status = xbee_t.RegistrationStatus.KEY_TABLE_IS_FULL
498 | fut = asyncio.Future()
499 | api._awaiting[frame_id] = (fut,)
500 | api._handle_registration_status(frame_id, status)
501 | assert fut.done() is True
502 | with pytest.raises(RuntimeError, match="Registration Status: KEY_TABLE_IS_FULL"):
503 | fut.result()
504 |
505 |
506 | async def test_command_mode_at_cmd(api):
507 | """Test AT in command mode."""
508 | command = "+++"
509 |
510 | def cmd_mode_send(cmd):
511 | api._cmd_mode_future.set_result(True)
512 |
513 | api._uart.command_mode_send = cmd_mode_send
514 |
515 | result = await api.command_mode_at_cmd(command)
516 | assert result
517 |
518 |
519 | async def test_command_mode_at_cmd_timeout(api):
520 | """Test AT in command mode with timeout."""
521 | command = "+++"
522 |
523 | api._uart.command_mode_send = mock.MagicMock()
524 |
525 | result = await api.command_mode_at_cmd(command)
526 | assert result is None
527 |
528 |
529 | def test_handle_command_mode_rsp(api):
530 | """Test command mode response."""
531 | api._cmd_mode_future = None
532 | data = "OK"
533 | api.handle_command_mode_rsp(data)
534 |
535 | api._cmd_mode_future = asyncio.Future()
536 | api.handle_command_mode_rsp(data)
537 | assert api._cmd_mode_future.done()
538 | assert api._cmd_mode_future.result() is True
539 |
540 | api._cmd_mode_future = asyncio.Future()
541 | api.handle_command_mode_rsp("ERROR")
542 | assert api._cmd_mode_future.done()
543 | assert api._cmd_mode_future.result() is False
544 |
545 | data = "Hello"
546 | api._cmd_mode_future = asyncio.Future()
547 | api.handle_command_mode_rsp(data)
548 | assert api._cmd_mode_future.done()
549 | assert api._cmd_mode_future.result() == data
550 |
551 |
552 | async def test_enter_at_command_mode(api):
553 | """Test switching to command mode."""
554 | api.command_mode_at_cmd = mock.AsyncMock(return_value=mock.sentinel.at_response)
555 |
556 | res = await api.enter_at_command_mode()
557 | assert res == mock.sentinel.at_response
558 |
559 |
560 | async def test_api_mode_at_commands(api):
561 | """Test AT in API mode."""
562 | api.command_mode_at_cmd = mock.AsyncMock(return_value=mock.sentinel.api_mode)
563 |
564 | res = await api.api_mode_at_commands(57600)
565 | assert res is True
566 |
567 | async def mock_at_cmd(cmd):
568 | if cmd == "ATWR\r":
569 | return False
570 | return True
571 |
572 | api.command_mode_at_cmd = mock_at_cmd
573 | res = await api.api_mode_at_commands(57600)
574 | assert res is None
575 |
576 |
577 | async def test_init_api_mode(api, monkeypatch):
578 | """Test init the API mode."""
579 | monkeypatch.setattr(api._uart, "baudrate", 57600)
580 | api.enter_at_command_mode = mock.AsyncMock(return_value=True)
581 |
582 | res = await api.init_api_mode()
583 | assert res is None
584 | assert api.enter_at_command_mode.call_count == 1
585 |
586 | api.enter_at_command_mode = mock.AsyncMock(return_value=False)
587 |
588 | res = await api.init_api_mode()
589 | assert res is False
590 | assert api.enter_at_command_mode.call_count == 10
591 |
592 | async def enter_at_mode():
593 | if api._uart.baudrate == 9600:
594 | return True
595 | return False
596 |
597 | api._uart.baudrate = 57600
598 | api.enter_at_command_mode = mock.MagicMock(side_effect=enter_at_mode)
599 | api.api_mode_at_commands = mock.AsyncMock(return_value=True)
600 |
601 | res = await api.init_api_mode()
602 | assert res is True
603 | assert api.enter_at_command_mode.call_count == 5
604 |
605 |
606 | def test_set_application(api):
607 | """Test setting the application."""
608 | api.set_application(mock.sentinel.app)
609 | assert api._app == mock.sentinel.app
610 |
611 |
612 | def test_handle_route_record_indicator(api):
613 | """Test api._handle_route_record_indicator()."""
614 | s = mock.sentinel
615 | api._handle_route_record_indicator(s.ieee, s.src, s.rx_opts, s.hops)
616 |
617 |
618 | def test_handle_many_to_one_rri(api):
619 | """Test api._handle_many_to_one_rri()."""
620 | ieee = t.EUI64([t.uint8_t(a) for a in range(0, 8)])
621 | nwk = 0x1234
622 | api._handle_many_to_one_rri(ieee, nwk, 0)
623 |
624 |
625 | async def test_connection_lost(api):
626 | """Test `connection_lost` propagataion."""
627 | api.set_application(mock.AsyncMock())
628 |
629 | err = RuntimeError()
630 | api.connection_lost(err)
631 | api._app.connection_lost.assert_called_once_with(err)
632 |
--------------------------------------------------------------------------------
/tests/test_application.py:
--------------------------------------------------------------------------------
1 | """Tests for ControllerApplication."""
2 |
3 | import asyncio
4 | from unittest import mock
5 |
6 | import pytest
7 | import zigpy.config as config
8 | import zigpy.exceptions
9 | import zigpy.state
10 | import zigpy.types as t
11 | import zigpy.zdo
12 | import zigpy.zdo.types as zdo_t
13 |
14 | from zigpy_xbee.api import XBee
15 | from zigpy_xbee.exceptions import InvalidCommand
16 | import zigpy_xbee.types as xbee_t
17 | from zigpy_xbee.zigbee import application
18 |
19 | APP_CONFIG = {
20 | config.CONF_DEVICE: {
21 | config.CONF_DEVICE_PATH: "/dev/null",
22 | config.CONF_DEVICE_BAUDRATE: 115200,
23 | },
24 | config.CONF_DATABASE: None,
25 | config.CONF_OTA: {
26 | config.CONF_OTA_ENABLED: False,
27 | },
28 | }
29 |
30 |
31 | @pytest.fixture
32 | def node_info():
33 | """Sample NodeInfo fixture."""
34 | return zigpy.state.NodeInfo(
35 | nwk=t.NWK(0x0000),
36 | ieee=t.EUI64.convert("00:12:4b:00:1c:a1:b8:46"),
37 | logical_type=zdo_t.LogicalType.Coordinator,
38 | )
39 |
40 |
41 | @pytest.fixture
42 | def network_info(node_info):
43 | """Sample NetworkInfo fixture."""
44 | return zigpy.state.NetworkInfo(
45 | extended_pan_id=t.ExtendedPanId.convert("bd:27:0b:38:37:95:dc:87"),
46 | pan_id=t.PanId(0x9BB0),
47 | nwk_update_id=18,
48 | nwk_manager_id=t.NWK(0x0000),
49 | channel=t.uint8_t(15),
50 | channel_mask=t.Channels.ALL_CHANNELS,
51 | security_level=t.uint8_t(5),
52 | network_key=zigpy.state.Key(
53 | key=t.KeyData.convert("2ccade06b3090c310315b3d574d3c85a"),
54 | seq=108,
55 | tx_counter=118785,
56 | ),
57 | tc_link_key=zigpy.state.Key(
58 | key=t.KeyData(b"ZigBeeAlliance09"),
59 | partner_ieee=node_info.ieee,
60 | tx_counter=8712428,
61 | ),
62 | key_table=[],
63 | children=[],
64 | nwk_addresses={},
65 | source="zigpy-xbee@0.0.0",
66 | )
67 |
68 |
69 | @pytest.fixture
70 | def app(monkeypatch):
71 | """Sample ControllerApplication fixture."""
72 | monkeypatch.setattr(application, "TIMEOUT_TX_STATUS", 0.1)
73 | monkeypatch.setattr(application, "TIMEOUT_REPLY", 0.1)
74 | monkeypatch.setattr(application, "TIMEOUT_REPLY_EXTENDED", 0.1)
75 | app = application.ControllerApplication(APP_CONFIG)
76 | api = XBee(APP_CONFIG[config.CONF_DEVICE])
77 | monkeypatch.setattr(api, "_command", mock.AsyncMock())
78 | app._api = api
79 |
80 | app.state.node_info.nwk = 0x0000
81 | app.state.node_info.ieee = t.EUI64.convert("aa:bb:cc:dd:ee:ff:00:11")
82 | return app
83 |
84 |
85 | def test_modem_status(app):
86 | """Test handling ModemStatus updates."""
87 | assert 0x00 in xbee_t.ModemStatus.__members__.values()
88 | app.handle_modem_status(xbee_t.ModemStatus(0x00))
89 | assert 0xEE not in xbee_t.ModemStatus.__members__.values()
90 | app.handle_modem_status(xbee_t.ModemStatus(0xEE))
91 |
92 |
93 | def _test_rx(
94 | app,
95 | device,
96 | nwk,
97 | dst_ep=mock.sentinel.dst_ep,
98 | cluster_id=mock.sentinel.cluster_id,
99 | data=mock.sentinel.data,
100 | ):
101 | """Call app.handle_rx()."""
102 | app.get_device = mock.MagicMock(return_value=device)
103 |
104 | app.handle_rx(
105 | b"\x01\x02\x03\x04\x05\x06\x07\x08",
106 | nwk,
107 | mock.sentinel.src_ep,
108 | dst_ep,
109 | cluster_id,
110 | mock.sentinel.profile_id,
111 | mock.sentinel.rxopts,
112 | data,
113 | )
114 |
115 |
116 | def test_rx(app):
117 | """Test message receiving."""
118 | device = mock.MagicMock()
119 | _test_rx(app, device, 0x1234, data=b"\x01\x02\x03\x04")
120 | assert device.packet_received.call_count == 1
121 | packet = device.packet_received.call_args[0][0]
122 | assert packet.src == t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x1234)
123 | assert packet.src_ep == mock.sentinel.src_ep
124 | assert packet.dst == t.AddrModeAddress(addr_mode=t.AddrMode.NWK, address=0x0000)
125 | assert packet.dst_ep == mock.sentinel.dst_ep
126 | assert packet.profile_id == mock.sentinel.profile_id
127 | assert packet.cluster_id == mock.sentinel.cluster_id
128 | assert packet.data == t.SerializableBytes(b"\x01\x02\x03\x04")
129 |
130 |
131 | def test_rx_nwk_0000(app):
132 | """Test receiving self-addressed message."""
133 | app._handle_reply = mock.MagicMock()
134 | app.get_device = mock.MagicMock()
135 | app.handle_rx(
136 | b"\x01\x02\x03\x04\x05\x06\x07\x08",
137 | 0x0000,
138 | mock.sentinel.src_ep,
139 | mock.sentinel.dst_ep,
140 | mock.sentinel.cluster_id,
141 | mock.sentinel.profile_id,
142 | mock.sentinel.rxopts,
143 | b"",
144 | )
145 | assert app.get_device.call_count == 2
146 |
147 |
148 | def test_rx_unknown_device(app, device):
149 | """Unknown NWK, but existing device."""
150 | app.create_task = mock.MagicMock()
151 | app._discover_unknown_device = mock.MagicMock()
152 | dev = device(nwk=0x1234)
153 | app.devices[dev.ieee] = dev
154 |
155 | num_before_rx = len(app.devices)
156 | app.handle_rx(
157 | b"\x08\x07\x06\x05\x04\x03\x02\x01",
158 | 0x3334,
159 | mock.sentinel.src_ep,
160 | mock.sentinel.dst_ep,
161 | mock.sentinel.cluster_id,
162 | mock.sentinel.profile_id,
163 | mock.sentinel.rxopts,
164 | b"",
165 | )
166 | assert app.create_task.call_count == 1
167 | app._discover_unknown_device.assert_called_once_with(0x3334)
168 | assert len(app.devices) == num_before_rx
169 |
170 |
171 | def test_rx_unknown_device_ieee(app):
172 | """Unknown NWK, and unknown IEEE."""
173 | app.create_task = mock.MagicMock()
174 | app._discover_unknown_device = mock.MagicMock()
175 | app.get_device = mock.MagicMock(side_effect=KeyError)
176 | app.handle_rx(
177 | b"\xff\xff\xff\xff\xff\xff\xff\xff",
178 | 0x3334,
179 | mock.sentinel.src_ep,
180 | mock.sentinel.dst_ep,
181 | mock.sentinel.cluster_id,
182 | mock.sentinel.profile_id,
183 | mock.sentinel.rxopts,
184 | b"",
185 | )
186 | assert app.create_task.call_count == 1
187 | app._discover_unknown_device.assert_called_once_with(0x3334)
188 | assert app.get_device.call_count == 2
189 |
190 |
191 | @pytest.fixture
192 | def device(app):
193 | """Sample zigpy.device.Device fixture."""
194 |
195 | def _device(
196 | new=False, zdo_init=False, nwk=0x1234, ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01"
197 | ):
198 | from zigpy.device import Device, Status as DeviceStatus
199 |
200 | nwk = t.uint16_t(nwk)
201 | ieee, _ = t.EUI64.deserialize(ieee)
202 | dev = Device(app, ieee, nwk)
203 | if new:
204 | dev.status = DeviceStatus.NEW
205 | elif zdo_init:
206 | dev.status = DeviceStatus.ZDO_INIT
207 | else:
208 | dev.status = DeviceStatus.ENDPOINTS_INIT
209 | return dev
210 |
211 | return _device
212 |
213 |
214 | def _device_join(app, dev, data):
215 | """Simulate device join notification."""
216 | dev.packet_received = mock.MagicMock()
217 | dev.schedule_initialize = mock.MagicMock()
218 | app.handle_join = mock.MagicMock()
219 | app.create_task = mock.MagicMock()
220 | app._discover_unknown_device = mock.MagicMock()
221 |
222 | dst_ep = 0
223 | cluster_id = 0x0013
224 |
225 | _test_rx(app, dev, dev.nwk, dst_ep, cluster_id, data)
226 | assert app.handle_join.call_count == 1
227 | assert dev.packet_received.call_count == 1
228 | assert dev.schedule_initialize.call_count == 1
229 |
230 |
231 | def test_device_join_new(app, device):
232 | """Test device join."""
233 | dev = device()
234 | data = b"\xee" + dev.nwk.serialize() + dev.ieee.serialize() + b"\x40"
235 |
236 | _device_join(app, dev, data)
237 |
238 |
239 | def test_device_join_inconsistent_nwk(app, device):
240 | """Test device join inconsistent NWK."""
241 | dev = device()
242 | data = b"\xee" + b"\x01\x02" + dev.ieee.serialize() + b"\x40"
243 |
244 | _device_join(app, dev, data)
245 |
246 |
247 | def test_device_join_inconsistent_ieee(app, device):
248 | """Test device join inconsistent IEEE."""
249 | dev = device()
250 | data = b"\xee" + dev.nwk.serialize() + b"\x01\x02\x03\x04\x05\x06\x07\x08" + b"\x40"
251 |
252 | _device_join(app, dev, data)
253 |
254 |
255 | async def test_broadcast(app):
256 | """Test sending broadcast transmission."""
257 | (profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data) = (
258 | 0x260,
259 | 1,
260 | 2,
261 | 3,
262 | 0x0100,
263 | 0x06,
264 | 210,
265 | b"\x02\x01\x00",
266 | )
267 |
268 | app._api._command.return_value = xbee_t.TXStatus.SUCCESS
269 |
270 | r = await app.broadcast(profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data)
271 | assert r[0] == xbee_t.TXStatus.SUCCESS
272 | assert app._api._command.call_count == 1
273 | assert app._api._command.call_args[0][0] == "tx_explicit"
274 | assert app._api._command.call_args[0][3] == src_ep
275 | assert app._api._command.call_args[0][4] == dst_ep
276 | assert app._api._command.call_args[0][9] == data
277 |
278 | app._api._command.return_value = xbee_t.TXStatus.ADDRESS_NOT_FOUND
279 |
280 | with pytest.raises(zigpy.exceptions.DeliveryError):
281 | r = await app.broadcast(
282 | profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data
283 | )
284 |
285 | app._api._command.side_effect = asyncio.TimeoutError
286 |
287 | with pytest.raises(zigpy.exceptions.DeliveryError):
288 | r = await app.broadcast(
289 | profile, cluster, src_ep, dst_ep, grpid, radius, tsn, data
290 | )
291 |
292 |
293 | async def test_get_association_state(app):
294 | """Test get association statevia API."""
295 | ai_results = (0xFF, 0xFF, 0xFF, 0xFF, mock.sentinel.ai)
296 | app._api._at_command = mock.AsyncMock(
297 | spec=XBee._at_command,
298 | side_effect=ai_results,
299 | )
300 | ai = await app._get_association_state()
301 | assert app._api._at_command.call_count == len(ai_results)
302 | assert ai is mock.sentinel.ai
303 |
304 |
305 | @pytest.mark.parametrize("legacy_module", (False, True))
306 | async def test_write_network_info(app, node_info, network_info, legacy_module):
307 | """Test writing network info to the device."""
308 |
309 | def _mock_queued_at(name, *args):
310 | if legacy_module and name == "CE":
311 | raise InvalidCommand("Legacy module")
312 | return "OK"
313 |
314 | app._api._queued_at = mock.AsyncMock(
315 | spec=XBee._queued_at, side_effect=_mock_queued_at
316 | )
317 | app._api._at_command = mock.AsyncMock(spec=XBee._at_command)
318 | app._api._running = mock.AsyncMock(spec=app._api._running)
319 |
320 | app._get_association_state = mock.AsyncMock(
321 | spec=application.ControllerApplication._get_association_state,
322 | return_value=0x00,
323 | )
324 |
325 | await app.write_network_info(network_info=network_info, node_info=node_info)
326 |
327 | app._api._queued_at.assert_any_call("SC", 1 << (network_info.channel - 11))
328 | app._api._queued_at.assert_any_call("KY", b"ZigBeeAlliance09")
329 | app._api._queued_at.assert_any_call("NK", network_info.network_key.key.serialize())
330 | app._api._queued_at.assert_any_call("ID", 0xBD270B383795DC87)
331 |
332 |
333 | async def _test_start_network(
334 | app,
335 | ai_status=0xFF,
336 | api_mode=True,
337 | api_config_succeeds=True,
338 | ee=1,
339 | eo=2,
340 | zs=2,
341 | legacy_module=False,
342 | ):
343 | """Call app.start_network()."""
344 | ai_tries = 5
345 | app.state.node_info = zigpy.state.NodeInfo()
346 |
347 | def _at_command_mock(cmd, *args):
348 | nonlocal ai_tries
349 | if not api_mode:
350 | raise asyncio.TimeoutError
351 | if cmd == "CE" and legacy_module:
352 | raise InvalidCommand
353 |
354 | ai_tries -= 1 if cmd == "AI" else 0
355 | return {
356 | "AI": ai_status if ai_tries < 0 else 0xFF,
357 | "CE": 1 if ai_status == 0 else 0,
358 | "EO": eo,
359 | "EE": ee,
360 | "ID": 0x25DCF87E03EA5906,
361 | "MY": 0xFFFE if ai_status else 0x0000,
362 | "NJ": mock.sentinel.at_nj,
363 | "OI": 0xDD94,
364 | "OP": mock.sentinel.at_op,
365 | "SH": 0x08070605,
366 | "SL": 0x04030201,
367 | "ZS": zs,
368 | "VR": 0x1234,
369 | }.get(cmd, None)
370 |
371 | def init_api_mode_mock():
372 | nonlocal api_mode
373 | api_mode = api_config_succeeds
374 | return api_config_succeeds
375 |
376 | api_mock = mock.MagicMock()
377 | api_mock._at_command = mock.AsyncMock(side_effect=_at_command_mock)
378 | api_mock.init_api_mode = mock.AsyncMock(side_effect=init_api_mode_mock)
379 | api_mock.connect = mock.AsyncMock()
380 |
381 | with mock.patch("zigpy_xbee.api.XBee", return_value=api_mock):
382 | await app.connect()
383 |
384 | app.form_network = mock.AsyncMock()
385 | await app.start_network()
386 | return app
387 |
388 |
389 | async def test_start_network(app):
390 | """Test start network."""
391 | await _test_start_network(app, ai_status=0x00)
392 | assert app.state.node_info.nwk == 0x0000
393 | assert app.state.node_info.ieee == t.EUI64(range(1, 9))
394 | assert app.state.network_info.pan_id == 0xDD94
395 | assert app.state.network_info.extended_pan_id == t.ExtendedPanId.convert(
396 | "25:dc:f8:7e:03:ea:59:06"
397 | )
398 |
399 | await _test_start_network(app, ai_status=0x00)
400 | assert app.state.node_info.nwk == 0x0000
401 | assert app.state.node_info.ieee == t.EUI64(range(1, 9))
402 | assert app.form_network.call_count == 0
403 |
404 | with pytest.raises(zigpy.exceptions.NetworkNotFormed):
405 | await _test_start_network(app, ai_status=0x06)
406 |
407 | with pytest.raises(zigpy.exceptions.NetworkNotFormed):
408 | await _test_start_network(app, ai_status=0x00, zs=1)
409 |
410 | with pytest.raises(zigpy.exceptions.NetworkNotFormed):
411 | await _test_start_network(app, ai_status=0x06, legacy_module=True)
412 |
413 | with pytest.raises(zigpy.exceptions.NetworkNotFormed):
414 | await _test_start_network(app, ai_status=0x00, zs=1, legacy_module=True)
415 |
416 |
417 | async def test_start_network_no_api_mode(app):
418 | """Test start network when not in API mode."""
419 | with pytest.raises(asyncio.TimeoutError):
420 | await _test_start_network(app, ai_status=0x00, api_mode=False)
421 |
422 |
423 | async def test_start_network_api_mode_config_fails(app):
424 | """Test start network when not when API config fails."""
425 | with pytest.raises(asyncio.TimeoutError):
426 | await _test_start_network(
427 | app, ai_status=0x00, api_mode=False, api_config_succeeds=False
428 | )
429 |
430 |
431 | async def test_permit(app):
432 | """Test permit joins."""
433 | app._api._at_command = mock.AsyncMock()
434 | time_s = 30
435 | await app.permit_ncp(time_s)
436 | assert app._api._at_command.call_count == 2
437 | assert app._api._at_command.call_args_list[0][0][1] == time_s
438 |
439 |
440 | async def test_permit_with_link_key(app):
441 | """Test permit joins with link key."""
442 | app._api._command = mock.AsyncMock(return_value=xbee_t.TXStatus.SUCCESS)
443 | app._api._at_command = mock.AsyncMock(return_value="OK")
444 | node = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08")
445 | link_key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
446 | time_s = 500
447 | await app.permit_with_link_key(node=node, link_key=link_key, time_s=time_s)
448 | app._api._at_command.assert_called_once_with("KT", time_s)
449 | app._api._command.assert_called_once_with(
450 | "register_joining_device", node, 0xFFFE, 0, link_key
451 | )
452 |
453 |
454 | async def _test_request(
455 | app, expect_reply=True, send_success=True, send_timeout=False, **kwargs
456 | ):
457 | """Call app.request()."""
458 | seq = 123
459 | nwk = 0x2345
460 | ieee = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08")
461 | dev = app.add_device(ieee, nwk)
462 |
463 | def _mock_command(
464 | cmdname, ieee, nwk, src_ep, dst_ep, cluster, profile, radius, options, data
465 | ):
466 | send_fut = asyncio.Future()
467 | if not send_timeout:
468 | if send_success:
469 | send_fut.set_result(xbee_t.TXStatus.SUCCESS)
470 | else:
471 | send_fut.set_result(xbee_t.TXStatus.ADDRESS_NOT_FOUND)
472 | return send_fut
473 |
474 | app._api._command = mock.MagicMock(side_effect=_mock_command)
475 | return await app.request(
476 | dev,
477 | 0x0260,
478 | 1,
479 | 2,
480 | 3,
481 | seq,
482 | b"\xaa\x55\xbe\xef",
483 | expect_reply=expect_reply,
484 | **kwargs,
485 | )
486 |
487 |
488 | async def test_request_with_ieee(app):
489 | """Test request with IEEE."""
490 | r = await _test_request(app, use_ieee=True, send_success=True)
491 | assert r[0] == 0
492 |
493 |
494 | async def test_request_with_reply(app):
495 | """Test request with expecting reply."""
496 | r = await _test_request(app, expect_reply=True, send_success=True)
497 | assert r[0] == 0
498 |
499 |
500 | async def test_request_send_timeout(app):
501 | """Test request with send timeout."""
502 | with pytest.raises(zigpy.exceptions.DeliveryError):
503 | await _test_request(app, send_timeout=True)
504 |
505 |
506 | async def test_request_send_fail(app):
507 | """Test request with send failure."""
508 | with pytest.raises(zigpy.exceptions.DeliveryError):
509 | await _test_request(app, send_success=False)
510 |
511 |
512 | async def test_request_unknown_device(app):
513 | """Test request with unknown device."""
514 | dev = zigpy.device.Device(
515 | application=app, ieee=xbee_t.UNKNOWN_IEEE, nwk=xbee_t.UNKNOWN_NWK
516 | )
517 | with pytest.raises(
518 | zigpy.exceptions.DeliveryError,
519 | match="Cannot send a packet to a device without a known IEEE address",
520 | ):
521 | await app.request(
522 | dev,
523 | 0x0260,
524 | 1,
525 | 2,
526 | 3,
527 | 123,
528 | b"\xaa\x55\xbe\xef",
529 | )
530 |
531 |
532 | async def test_request_extended_timeout(app):
533 | """Test request with extended timeout."""
534 | r = await _test_request(app, True, True, extended_timeout=False)
535 | assert r[0] == xbee_t.TXStatus.SUCCESS
536 | assert app._api._command.call_count == 1
537 | assert app._api._command.call_args[0][8] & 0x40 == 0x00
538 | app._api._command.reset_mock()
539 |
540 | r = await _test_request(app, True, True, extended_timeout=True)
541 | assert r[0] == xbee_t.TXStatus.SUCCESS
542 | assert app._api._command.call_count == 1
543 | assert app._api._command.call_args[0][8] & 0x40 == 0x40
544 | app._api._command.reset_mock()
545 |
546 |
547 | async def test_force_remove(app):
548 | """Test device force removal."""
549 | await app.force_remove(mock.sentinel.device)
550 |
551 |
552 | async def test_shutdown(app):
553 | """Test application shutdown."""
554 | mock_disconnect = mock.AsyncMock()
555 | app._api.disconnect = mock_disconnect
556 | await app.disconnect()
557 | assert app._api is None
558 | assert mock_disconnect.call_count == 1
559 |
560 |
561 | async def test_remote_at_cmd(app, device):
562 | """Test remote AT command."""
563 | dev = device()
564 | app.get_device = mock.MagicMock(return_value=dev)
565 | app._api = mock.MagicMock(spec=XBee)
566 | s = mock.sentinel
567 | await app.remote_at_command(
568 | s.nwk, s.cmd, s.data, apply_changes=True, encryption=True
569 | )
570 | assert app._api._remote_at_command.call_count == 1
571 | assert app._api._remote_at_command.call_args[0][0] is dev.ieee
572 | assert app._api._remote_at_command.call_args[0][1] == s.nwk
573 | assert app._api._remote_at_command.call_args[0][2] == 0x12
574 | assert app._api._remote_at_command.call_args[0][3] == s.cmd
575 | assert app._api._remote_at_command.call_args[0][4] == s.data
576 |
577 |
578 | @pytest.fixture
579 | def ieee():
580 | """Sample IEEE fixture."""
581 | return t.EUI64.deserialize(b"\x00\x01\x02\x03\x04\x05\x06\x07")[0]
582 |
583 |
584 | @pytest.fixture
585 | def nwk():
586 | """Sample NWK fixture."""
587 | return t.uint16_t(0x0100)
588 |
589 |
590 | def test_rx_device_annce(app, ieee, nwk):
591 | """Test receiving device announce."""
592 | dst_ep = 0
593 | cluster_id = zdo_t.ZDOCmd.Device_annce
594 | device = mock.MagicMock()
595 | device.status = device.Status.NEW
596 | device.zdo = zigpy.zdo.ZDO(None)
597 | app.get_device = mock.MagicMock(return_value=device)
598 | app.handle_join = mock.MagicMock()
599 | device.packet_received = mock.MagicMock()
600 |
601 | data = t.uint8_t(0xAA).serialize()
602 | data += nwk.serialize()
603 | data += ieee.serialize()
604 | data += t.uint8_t(0x8E).serialize()
605 |
606 | app.handle_rx(
607 | ieee,
608 | nwk,
609 | mock.sentinel.src_ep,
610 | dst_ep,
611 | cluster_id,
612 | mock.sentinel.profile_id,
613 | mock.sentinel.rx_opt,
614 | data,
615 | )
616 |
617 | assert device.packet_received.call_count == 1
618 | app.handle_join.assert_called_once_with(nwk=nwk, ieee=ieee, parent_nwk=None)
619 |
620 |
621 | async def _test_mrequest(app, send_success=True, send_timeout=False, **kwargs):
622 | """Call app.mrequest()."""
623 | seq = 123
624 | group_id = 0x2345
625 |
626 | def _mock_command(
627 | cmdname, ieee, nwk, src_ep, dst_ep, cluster, profile, radius, options, data
628 | ):
629 | send_fut = asyncio.Future()
630 | if not send_timeout:
631 | if send_success:
632 | send_fut.set_result(xbee_t.TXStatus.SUCCESS)
633 | else:
634 | send_fut.set_result(xbee_t.TXStatus.ADDRESS_NOT_FOUND)
635 | return send_fut
636 |
637 | app._api._command = mock.MagicMock(side_effect=_mock_command)
638 | return await app.mrequest(group_id, 0x0260, 1, 2, seq, b"\xaa\x55\xbe\xef")
639 |
640 |
641 | async def test_mrequest_with_reply(app):
642 | """Test mrequest with reply."""
643 | r = await _test_mrequest(app, send_success=True)
644 | assert r[0] == 0
645 |
646 |
647 | async def test_mrequest_send_timeout(app):
648 | """Test mrequest with send timeout."""
649 | with pytest.raises(zigpy.exceptions.DeliveryError):
650 | await _test_mrequest(app, send_timeout=True)
651 |
652 |
653 | async def test_mrequest_send_fail(app):
654 | """Test mrequest with send failure."""
655 | with pytest.raises(zigpy.exceptions.DeliveryError):
656 | await _test_mrequest(app, send_success=False)
657 |
658 |
659 | async def test_reset_network_info(app):
660 | """Test resetting network."""
661 |
662 | async def mock_at_command(cmd, *args):
663 | if cmd == "NR":
664 | return 0x00
665 |
666 | return None
667 |
668 | app._api._at_command = mock.MagicMock(
669 | spec=XBee._at_command, side_effect=mock_at_command
670 | )
671 |
672 | await app.reset_network_info()
673 |
674 | app._api._at_command.assert_called_once_with("NR", 0)
675 |
676 |
677 | async def test_move_network_to_channel(app):
678 | """Test moving network to another channel."""
679 | app._api._queued_at = mock.AsyncMock(spec=XBee._at_command)
680 | await app._move_network_to_channel(26, new_nwk_update_id=1)
681 |
682 | assert len(app._api._queued_at.mock_calls) == 1
683 | app._api._queued_at.assert_any_call("SC", 1 << (26 - 11))
684 |
685 |
686 | async def test_energy_scan(app):
687 | """Test channel energy scan."""
688 | rssi = b"\x0A\x0F\x14\x19\x1E\x23\x28\x2D\x32\x37\x3C\x41\x46\x4B\x50\x55"
689 | app._api._at_command = mock.AsyncMock(spec=XBee._at_command, return_value=rssi)
690 | time_s = 3
691 | count = 3
692 | energy = await app.energy_scan(
693 | channels=list(range(11, 27)), duration_exp=time_s, count=count
694 | )
695 | assert app._api._at_command.mock_calls == [mock.call("ED", bytes([time_s]))] * count
696 | assert {k: round(v, 3) for k, v in energy.items()} == {
697 | 11: 254.032,
698 | 12: 253.153,
699 | 13: 251.486,
700 | 14: 248.352,
701 | 15: 242.562,
702 | 16: 232.193,
703 | 17: 214.619,
704 | 18: 187.443,
705 | 19: 150.853,
706 | 20: 109.797,
707 | 21: 72.172,
708 | 22: 43.571,
709 | 23: 24.769,
710 | 24: 13.56,
711 | 25: 7.264,
712 | 26: 3.844,
713 | }
714 |
715 |
716 | async def test_energy_scan_legacy_module(app):
717 | """Test channel energy scan."""
718 | app._api._at_command = mock.AsyncMock(
719 | spec=XBee._at_command, side_effect=InvalidCommand
720 | )
721 | time_s = 3
722 | count = 3
723 | energy = await app.energy_scan(
724 | channels=list(range(11, 27)), duration_exp=time_s, count=count
725 | )
726 | app._api._at_command.assert_called_once_with("ED", bytes([time_s]))
727 | assert energy == {c: 0 for c in range(11, 27)}
728 |
729 |
730 | def test_neighbors_updated(app, device):
731 | """Test LQI from neighbour scan."""
732 | router = device(ieee=b"\x01\x02\x03\x04\x05\x06\x07\x08")
733 | router.radio_details = mock.MagicMock()
734 | end_device = device(ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01")
735 | end_device.radio_details = mock.MagicMock()
736 |
737 | app.devices[router.ieee] = router
738 | app.devices[end_device.ieee] = end_device
739 |
740 | pan_id = t.ExtendedPanId(b"\x07\x07\x07\x07\x07\x07\x07\x07")
741 | # The router has two neighbors: the coordinator and the end device
742 | neighbors = [
743 | zdo_t.Neighbor(
744 | extended_pan_id=pan_id,
745 | ieee=app.state.node_info.ieee,
746 | nwk=app.state.node_info.nwk,
747 | device_type=0x0,
748 | rx_on_when_idle=0x1,
749 | relationship=0x00,
750 | reserved1=0x0,
751 | permit_joining=0x0,
752 | reserved2=0x0,
753 | depth=0,
754 | lqi=128,
755 | ),
756 | zdo_t.Neighbor(
757 | extended_pan_id=pan_id,
758 | ieee=end_device.ieee,
759 | nwk=end_device.nwk,
760 | device_type=0x2,
761 | rx_on_when_idle=0x0,
762 | relationship=0x01,
763 | reserved1=0x0,
764 | permit_joining=0x0,
765 | reserved2=0x0,
766 | depth=2,
767 | lqi=100,
768 | ),
769 | # Let's also include an unknown device
770 | zdo_t.Neighbor(
771 | extended_pan_id=pan_id,
772 | ieee=t.EUI64(b"\x00\x0F\x0E\x0D\x0C\x0B\x0A\x09"),
773 | nwk=t.NWK(0x9999),
774 | device_type=0x2,
775 | rx_on_when_idle=0x0,
776 | relationship=0x01,
777 | reserved1=0x0,
778 | permit_joining=0x0,
779 | reserved2=0x0,
780 | depth=2,
781 | lqi=99,
782 | ),
783 | ]
784 |
785 | app.neighbors_updated(router.ieee, neighbors)
786 |
787 | router.radio_details.assert_called_once_with(lqi=128)
788 | end_device.radio_details.assert_called_once_with(lqi=100)
789 |
790 |
791 | def test_routes_updated_schedule(app):
792 | """Test scheduling the sync routes_updated function."""
793 | app.create_task = mock.MagicMock()
794 | app._routes_updated = mock.MagicMock()
795 |
796 | ieee = t.EUI64(b"\x01\x02\x03\x04\x05\x06\x07\x08")
797 | routes = []
798 | app.routes_updated(ieee, routes)
799 |
800 | assert app.create_task.call_count == 1
801 | app._routes_updated.assert_called_once_with(ieee, routes)
802 |
803 |
804 | async def test_routes_updated(app, device):
805 | """Test RSSI on routes scan update."""
806 | rssi = 0x50
807 | app._api._at_command = mock.AsyncMock(return_value=rssi)
808 |
809 | router1 = device(ieee=b"\x01\x02\x03\x04\x05\x06\x07\x08")
810 | router1.radio_details = mock.MagicMock()
811 | router2 = device(ieee=b"\x08\x07\x06\x05\x04\x03\x02\x01")
812 | router2.radio_details = mock.MagicMock()
813 |
814 | app.devices[router1.ieee] = router1
815 | app.devices[router2.ieee] = router2
816 |
817 | # Let router1 be immediate child and route2 be child of the router1.
818 | # Then the routes of router1 would be:
819 | routes = [
820 | zdo_t.Route(
821 | DstNWK=app.state.node_info.nwk,
822 | RouteStatus=0x00,
823 | MemoryConstrained=0x0,
824 | ManyToOne=0x1,
825 | RouteRecordRequired=0x0,
826 | Reserved=0x0,
827 | NextHop=app.state.node_info.nwk,
828 | ),
829 | zdo_t.Route(
830 | DstNWK=router2.nwk,
831 | RouteStatus=0x00,
832 | MemoryConstrained=0x0,
833 | ManyToOne=0x0,
834 | RouteRecordRequired=0x0,
835 | Reserved=0x0,
836 | NextHop=router2.nwk,
837 | ),
838 | ]
839 |
840 | await app._routes_updated(router1.ieee, routes)
841 |
842 | router1.radio_details.assert_called_once_with(rssi=-80)
843 | assert router2.radio_details.call_count == 0
844 |
845 | router1.radio_details.reset_mock()
846 |
847 | routes = [
848 | zdo_t.Route(
849 | DstNWK=router1.nwk,
850 | RouteStatus=0x00,
851 | MemoryConstrained=0x0,
852 | ManyToOne=0x0,
853 | RouteRecordRequired=0x0,
854 | Reserved=0x0,
855 | NextHop=router1.nwk,
856 | )
857 | ]
858 | await app._routes_updated(router2.ieee, routes)
859 |
860 | assert router1.radio_details.call_count == 0
861 | assert router2.radio_details.call_count == 0
862 |
863 | app._api._at_command.assert_awaited_once_with("DB")
864 |
--------------------------------------------------------------------------------
/tests/test_types.py:
--------------------------------------------------------------------------------
1 | """Tests for types module."""
2 |
3 | import pytest
4 | import zigpy.types as t
5 |
6 | import zigpy_xbee.types as xbee_t
7 |
8 |
9 | def test_bytes_serialize():
10 | """Test Bytes.serialize()."""
11 | data = 0x89AB.to_bytes(4, "big")
12 | result = xbee_t.Bytes(data).serialize()
13 | assert result == data
14 |
15 |
16 | def test_bytes_deserialize():
17 | """Test Bytes.deserialize()."""
18 | data, rest = xbee_t.Bytes.deserialize(0x89AB.to_bytes(3, "big"))
19 | assert data == b"\x00\x89\xAB"
20 | assert rest == b""
21 |
22 |
23 | def test_atcommand():
24 | """Test ATCommand class."""
25 | cmd = b"AI"
26 | data = 0x06.to_bytes(4, "big")
27 | r_cmd, r_data = xbee_t.ATCommand.deserialize(cmd + data)
28 |
29 | assert r_cmd == cmd
30 | assert r_data == data
31 |
32 |
33 | def test_undefined_enum_undefined_value():
34 | """Test UndefinedEnum class."""
35 |
36 | class undEnum(t.uint8_t, xbee_t.UndefinedEnum):
37 | OK = 0
38 | ERROR = 2
39 | UNDEFINED_VALUE = 0xFF
40 | _UNDEFINED = 0xFF
41 |
42 | i = undEnum(0)
43 | assert i == 0
44 | assert i.name == "OK"
45 |
46 | i = undEnum(2)
47 | assert i == 2
48 | assert i.name == "ERROR"
49 |
50 | i = undEnum(0xEE)
51 | assert i.name == "UNDEFINED_VALUE"
52 |
53 | i = undEnum()
54 | assert i is undEnum.OK
55 |
56 |
57 | def test_undefined_enum_undefinede():
58 | """Test UndefinedEnum undefined member."""
59 |
60 | class undEnum(t.uint8_t, xbee_t.UndefinedEnum):
61 | OK = 0
62 | ERROR = 2
63 | UNDEFINED_VALUE = 0xFF
64 |
65 | with pytest.raises(ValueError):
66 | undEnum(0xEE)
67 |
68 |
69 | def test_nwk():
70 | """Test NWK class."""
71 | nwk = xbee_t.NWK(0x1234)
72 |
73 | assert str(nwk) == "0x1234"
74 | assert repr(nwk) == "0x1234"
75 |
76 |
77 | def test_eui64():
78 | """Test EUI64 class."""
79 | extra = b"\xBE\xEF"
80 | data = b"01234567"
81 |
82 | result, rest = xbee_t.EUI64.deserialize(data + extra)
83 |
84 | assert rest == extra
85 | assert result == xbee_t.EUI64((0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30))
86 |
87 | data = xbee_t.EUI64([t.uint8_t(i) for i in range(0x30, 0x38)])
88 | result = data.serialize()
89 |
90 | assert result == b"76543210"
91 |
--------------------------------------------------------------------------------
/tests/test_uart.py:
--------------------------------------------------------------------------------
1 | """Tests for uart module."""
2 |
3 | import asyncio
4 | from unittest import mock
5 |
6 | import pytest
7 | import serial_asyncio
8 | import zigpy.config
9 |
10 | from zigpy_xbee import uart
11 |
12 | DEVICE_CONFIG = zigpy.config.SCHEMA_DEVICE(
13 | {
14 | zigpy.config.CONF_DEVICE_PATH: "/dev/null",
15 | zigpy.config.CONF_DEVICE_BAUDRATE: 57600,
16 | }
17 | )
18 |
19 |
20 | @pytest.fixture
21 | def gw():
22 | """Gateway fixture."""
23 | gw = uart.Gateway(mock.MagicMock())
24 | gw._transport = mock.MagicMock()
25 | gw._transport.serial.BAUDRATES = serial_asyncio.serial.Serial.BAUDRATES
26 | return gw
27 |
28 |
29 | def test_baudrate(gw):
30 | """Test setting baudrate."""
31 | gw.baudrate
32 | gw.baudrate = 19200
33 | assert gw._transport.serial.baudrate == 19200
34 |
35 |
36 | def test_baudrate_fail(gw):
37 | """Test setting unexpected baudrate."""
38 | with pytest.raises(ValueError):
39 | gw.baudrate = 3333
40 |
41 |
42 | async def test_connect(monkeypatch):
43 | """Test connecting."""
44 | api = mock.MagicMock()
45 |
46 | async def mock_conn(loop, protocol_factory, **kwargs):
47 | protocol = protocol_factory()
48 | loop.call_soon(protocol.connection_made, None)
49 | return None, protocol
50 |
51 | monkeypatch.setattr(serial_asyncio, "create_serial_connection", mock_conn)
52 |
53 | await uart.connect(DEVICE_CONFIG, api)
54 |
55 |
56 | def test_command_mode_rsp(gw):
57 | """Test command mode response."""
58 | data = b"OK"
59 | gw.command_mode_rsp(data)
60 | assert gw._api.handle_command_mode_rsp.call_count == 1
61 | assert gw._api.handle_command_mode_rsp.call_args[0][0] == "OK"
62 |
63 |
64 | def test_command_mode_send(gw):
65 | """Test command mode request."""
66 | data = b"ATAP2\x0D"
67 | gw.command_mode_send(data)
68 | gw._transport.write.assert_called_once_with(data)
69 |
70 |
71 | async def test_disconnect(gw):
72 | """Test closing connection."""
73 | transport = gw._transport
74 | asyncio.get_running_loop().call_soon(gw.connection_lost, None)
75 | await gw.disconnect()
76 | assert transport.close.call_count == 1
77 |
78 |
79 | def test_data_received_chunk_frame(gw):
80 | """Test receiving frame in parts."""
81 | data = b"~\x00\r\x88\rID\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd"
82 | gw.frame_received = mock.MagicMock()
83 | gw.data_received(data[:3])
84 | assert gw.frame_received.call_count == 0
85 | gw.data_received(data[3:])
86 | assert gw.frame_received.call_count == 1
87 | assert gw.frame_received.call_args[0][0] == data[3:-1]
88 |
89 |
90 | def test_data_received_full_frame(gw):
91 | """Test receiving full frame."""
92 | data = b"~\x00\r\x88\rID\x00\x00\x00\x00\x00\x00\x00\x00\x00\xdd"
93 | gw.frame_received = mock.MagicMock()
94 | gw.data_received(data)
95 | assert gw.frame_received.call_count == 1
96 | assert gw.frame_received.call_args[0][0] == data[3:-1]
97 |
98 |
99 | def test_data_received_incomplete_frame(gw):
100 | """Test receiving partial frame."""
101 | data = b"~\x00\x07\x8b\x0e\xff\xfd"
102 | gw.frame_received = mock.MagicMock()
103 | gw.data_received(data)
104 | assert gw.frame_received.call_count == 0
105 |
106 |
107 | def test_data_received_at_response_non_cmd_mode(gw):
108 | """Test command mode response while not in command mode."""
109 | data = b"OK\x0D"
110 | gw.frame_received = mock.MagicMock()
111 | gw.command_mode_rsp = mock.MagicMock()
112 |
113 | gw.data_received(data)
114 | assert gw.command_mode_rsp.call_count == 0
115 |
116 |
117 | def test_data_received_at_response_in_cmd_mode(gw):
118 | """Test command mode response in command mode."""
119 | data = b"OK\x0D"
120 | gw.frame_received = mock.MagicMock()
121 | gw.command_mode_rsp = mock.MagicMock()
122 |
123 | gw.command_mode_send(b"")
124 | gw.data_received(data)
125 | assert gw.command_mode_rsp.call_count == 1
126 | assert gw.command_mode_rsp.call_args[0][0] == b"OK"
127 |
128 | gw.reset_command_mode()
129 | gw.data_received(data)
130 | assert gw.command_mode_rsp.call_count == 1
131 |
132 |
133 | def test_extract(gw):
134 | """Test handling extra chaining data."""
135 | gw._buffer = b"\x7E\x00\x02\x23\x7D\x31\xCBextra"
136 | frame = gw._extract_frame()
137 | assert frame == b"\x23\x11"
138 | assert gw._buffer == b"extra"
139 |
140 |
141 | def test_extract_wrong_checksum(gw):
142 | """Test API frame with wrong checksum and extra data."""
143 | gw._buffer = b"\x7E\x00\x02\x23\x7D\x31\xCEextra"
144 | frame = gw._extract_frame()
145 | assert frame is None
146 | assert gw._buffer == b"extra"
147 |
148 |
149 | def test_extract_checksum_none(gw):
150 | """Test API frame with no checksum."""
151 | data = b"\x7E\x00\x02\x23\x7D\x31"
152 | gw._buffer = data
153 | gw._checksum = lambda x: None
154 | frame = gw._extract_frame()
155 | assert frame is None
156 | assert gw._buffer == data
157 |
158 |
159 | def test_extract_frame_len_none(gw):
160 | """Test API frame with no length."""
161 | data = b"\x7E"
162 | gw._buffer = data
163 | frame = gw._extract_frame()
164 | assert frame is None
165 | assert gw._buffer == data
166 |
167 |
168 | def test_extract_frame_no_start(gw):
169 | """Test API frame without frame ID."""
170 | data = b"\x00\x02\x23\x7D\x31"
171 | gw._buffer = data
172 | frame = gw._extract_frame()
173 | assert frame is None
174 | assert gw._buffer == data
175 |
176 |
177 | def test_frame_received(gw):
178 | """Test frame is passed to api."""
179 | data = b"frame"
180 | gw.frame_received(data)
181 | assert gw._api.frame_received.call_count == 1
182 | assert gw._api.frame_received.call_args[0][0] == data
183 |
184 |
185 | def test_send(gw):
186 | """Test data send."""
187 | gw.send(b"\x23\x11")
188 | data = b"\x7E\x00\x02\x23\x7D\x31\xCB"
189 | gw._transport.write.assert_called_once_with(data)
190 |
191 |
192 | def test_escape(gw):
193 | """Test string escaping."""
194 | data = b"".join(
195 | [
196 | a.to_bytes(1, "big") + b.to_bytes(1, "big")
197 | for a, b in zip(gw.RESERVED, b"\x22\x33\x44\x55")
198 | ]
199 | )
200 | escaped = gw._escape(data)
201 | assert len(data) < len(escaped)
202 | chk = [c for c in escaped if c in gw.RESERVED]
203 | assert len(chk) == len(gw.RESERVED) # 4 chars to escape, thus 4 escape chars
204 | assert escaped == b'}^"}]3}1D}3U'
205 |
206 |
207 | def test_unescape(gw):
208 | """Test string unescaping."""
209 | extra = b"\xaa\xbb\xcc\xff"
210 | escaped = b'}^"}]3}1D}3U'
211 | chk = b"".join(
212 | [
213 | a.to_bytes(1, "big") + b.to_bytes(1, "big")
214 | for a, b in zip(gw.RESERVED, b"\x22\x33\x44\x55")
215 | ]
216 | )
217 | unescaped, rest = gw._get_unescaped(escaped + extra, 8)
218 | assert len(escaped) > len(unescaped)
219 | assert rest == extra
220 | assert unescaped == chk
221 |
222 |
223 | def test_unescape_underflow(gw):
224 | """Test unescape with not enough data."""
225 | escaped = b'}^"}'
226 | unescaped, rest = gw._get_unescaped(escaped, 3)
227 | assert unescaped is None
228 | assert rest is None
229 |
230 |
231 | def test_connection_lost_exc(gw):
232 | """Test cannection lost callback is called."""
233 | err = RuntimeError()
234 | gw.connection_lost(err)
235 | assert gw._api.connection_lost.mock_calls == [mock.call(err)]
236 |
237 |
238 | def test_connection_closed(gw):
239 | """Test connection closed."""
240 | gw.connection_lost(None)
241 | assert gw._api.connection_lost.mock_calls == [mock.call(None)]
242 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | # Tox (http://tox.testrun.org/) is a tool for running tests
2 | # in multiple virtualenvs. This configuration file will run the
3 | # test suite on all supported python versions. To use it, "pip install tox"
4 | # and then run "tox" from this directory.
5 |
6 | [tox]
7 | envlist = py38, py39, py310, py311, py312, lint, black
8 | skip_missing_interpreters = True
9 |
10 | [testenv]
11 | setenv = PYTHONPATH = {toxinidir}
12 | install_command = pip install {opts} {packages}
13 | commands = py.test --cov --cov-report=
14 | deps =
15 | asynctest
16 | pytest
17 | pytest-cov
18 | pytest-asyncio
19 |
20 | [testenv:lint]
21 | basepython = python3
22 | deps =
23 | flake8==6.1.0
24 | isort==5.12.0
25 | Flake8-pyproject==1.2.3
26 | commands =
27 | flake8
28 | isort --check {toxinidir}/zigpy_xbee {toxinidir}/tests {toxinidir}/setup.py
29 |
30 | [testenv:black]
31 | deps=black
32 | setenv =
33 | LC_ALL=C.UTF-8
34 | LANG=C.UTF-8
35 | commands=
36 | black --check --fast {toxinidir}/zigpy_xbee {toxinidir}/tests {toxinidir}/setup.py
37 |
--------------------------------------------------------------------------------
/zigpy_xbee/__init__.py:
--------------------------------------------------------------------------------
1 | """Init file for zigpy_xbee."""
2 |
3 | MAJOR_VERSION = 0
4 | MINOR_VERSION = 18
5 | PATCH_VERSION = "3"
6 | __short_version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}"
7 | __version__ = f"{__short_version__}.{PATCH_VERSION}"
8 |
--------------------------------------------------------------------------------
/zigpy_xbee/api.py:
--------------------------------------------------------------------------------
1 | """XBee API implementation."""
2 |
3 | import asyncio
4 | import binascii
5 | import functools
6 | import logging
7 | from typing import Any, Dict, Optional
8 |
9 | from zigpy.exceptions import APIException, DeliveryError
10 | import zigpy.types as t
11 |
12 | from zigpy_xbee.exceptions import (
13 | ATCommandError,
14 | ATCommandException,
15 | InvalidCommand,
16 | InvalidParameter,
17 | TransmissionFailure,
18 | )
19 |
20 | from . import types as xbee_t, uart
21 |
22 | LOGGER = logging.getLogger(__name__)
23 |
24 | AT_COMMAND_TIMEOUT = 3
25 | REMOTE_AT_COMMAND_TIMEOUT = 30
26 |
27 |
28 | # https://www.digi.com/resources/documentation/digidocs/PDFs/90000976.pdf
29 | COMMAND_REQUESTS = {
30 | "at": (0x08, (xbee_t.FrameId, xbee_t.ATCommand, xbee_t.Bytes), 0x88),
31 | "queued_at": (0x09, (xbee_t.FrameId, xbee_t.ATCommand, xbee_t.Bytes), 0x88),
32 | "remote_at": (
33 | 0x17,
34 | (
35 | xbee_t.FrameId,
36 | xbee_t.EUI64,
37 | xbee_t.NWK,
38 | t.uint8_t,
39 | xbee_t.ATCommand,
40 | xbee_t.Bytes,
41 | ),
42 | 0x97,
43 | ),
44 | "tx": (0x10, (), None),
45 | "tx_explicit": (
46 | 0x11,
47 | (
48 | xbee_t.FrameId,
49 | xbee_t.EUI64,
50 | xbee_t.NWK,
51 | t.uint8_t,
52 | t.uint8_t,
53 | t.uint16_t_be,
54 | t.uint16_t_be,
55 | t.uint8_t,
56 | t.uint8_t,
57 | xbee_t.Bytes,
58 | ),
59 | 0x8B,
60 | ),
61 | "create_source_route": (
62 | 0x21,
63 | (xbee_t.FrameId, xbee_t.EUI64, xbee_t.NWK, t.uint8_t, xbee_t.Relays),
64 | None,
65 | ),
66 | "register_joining_device": (
67 | 0x24,
68 | (xbee_t.FrameId, xbee_t.EUI64, t.uint16_t_be, t.uint8_t, xbee_t.Bytes),
69 | 0xA4,
70 | ),
71 | }
72 | COMMAND_RESPONSES = {
73 | "at_response": (
74 | 0x88,
75 | (xbee_t.FrameId, xbee_t.ATCommand, t.uint8_t, xbee_t.Bytes),
76 | None,
77 | ),
78 | "modem_status": (0x8A, (xbee_t.ModemStatus,), None),
79 | "tx_status": (
80 | 0x8B,
81 | (
82 | xbee_t.FrameId,
83 | xbee_t.NWK,
84 | t.uint8_t,
85 | xbee_t.TXStatus,
86 | xbee_t.DiscoveryStatus,
87 | ),
88 | None,
89 | ),
90 | "route_information": (0x8D, (), None),
91 | "rx": (0x90, (), None),
92 | "explicit_rx_indicator": (
93 | 0x91,
94 | (
95 | xbee_t.EUI64,
96 | xbee_t.NWK,
97 | t.uint8_t,
98 | t.uint8_t,
99 | t.uint16_t_be,
100 | t.uint16_t_be,
101 | t.uint8_t,
102 | xbee_t.Bytes,
103 | ),
104 | None,
105 | ),
106 | "rx_io_data_long_addr": (0x92, (), None),
107 | "remote_at_response": (
108 | 0x97,
109 | (
110 | xbee_t.FrameId,
111 | xbee_t.EUI64,
112 | xbee_t.NWK,
113 | xbee_t.ATCommand,
114 | t.uint8_t,
115 | xbee_t.Bytes,
116 | ),
117 | None,
118 | ),
119 | "extended_status": (0x98, (), None),
120 | "route_record_indicator": (
121 | 0xA1,
122 | (xbee_t.EUI64, xbee_t.NWK, t.uint8_t, xbee_t.Relays),
123 | None,
124 | ),
125 | "many_to_one_rri": (0xA3, (xbee_t.EUI64, xbee_t.NWK, t.uint8_t), None),
126 | "registration_status": (0xA4, (xbee_t.FrameId, xbee_t.RegistrationStatus), None),
127 | "node_id_indicator": (0x95, (), None),
128 | }
129 |
130 | # https://www.digi.com/resources/documentation/digidocs/pdfs/90001539.pdf pg 175
131 | AT_COMMANDS = {
132 | # Addressing commands
133 | "DH": t.uint32_t_be,
134 | "DL": t.uint32_t_be,
135 | "MY": t.uint16_t_be,
136 | "MP": t.uint16_t_be,
137 | "NC": t.uint32_t_be, # 0 - MAX_CHILDREN.
138 | "SH": t.uint32_t_be,
139 | "SL": t.uint32_t_be,
140 | "NI": t, # 20 byte printable ascii string
141 | "SE": t.uint8_t,
142 | "DE": t.uint8_t,
143 | "CI": t.uint16_t_be,
144 | "TO": t.uint8_t,
145 | "NP": t.uint16_t_be,
146 | "DD": t.uint32_t_be,
147 | "CR": t.uint8_t, # 0 - 0x3F
148 | # Networking commands
149 | "CH": t.uint8_t, # 0x0B - 0x1A
150 | "DA": t, # no param
151 | "ID": t.uint64_t_be,
152 | "OP": t.uint64_t_be,
153 | "NH": t.uint8_t,
154 | "BH": t.uint8_t, # 0 - 0x1E
155 | "OI": t.uint16_t_be,
156 | "NT": t.uint8_t, # 0x20 - 0xFF
157 | "NO": t.uint8_t, # bitfield, 0 - 3
158 | "SC": t.uint16_t_be, # 1 - 0xFFFF
159 | "SD": t.uint8_t, # 0 - 7
160 | "ZS": t.uint8_t, # 0 - 2
161 | "NJ": t.uint8_t,
162 | "JV": t.Bool,
163 | "NW": t.uint16_t_be, # 0 - 0x64FF
164 | "JN": t.Bool,
165 | "AR": t.uint8_t,
166 | "DJ": t.Bool, # WTF, docs
167 | "II": t.uint16_t_be,
168 | # Security commands
169 | "EE": t.Bool,
170 | "EO": t.uint8_t,
171 | "NK": xbee_t.Bytes, # 128-bit value
172 | "KY": xbee_t.Bytes, # 128-bit value
173 | "KT": t.uint16_t_be, # 0x1E - 0xFFFF
174 | # RF interfacing commands
175 | "PL": t.uint8_t, # 0 - 4 (basically an Enum)
176 | "PM": t.Bool,
177 | "DB": t.uint8_t,
178 | "PP": t.uint8_t, # RO
179 | "AP": t.uint8_t, # 1-2 (an Enum)
180 | "AO": t.uint8_t, # 0 - 3 (an Enum)
181 | "BD": t.uint8_t, # 0 - 7 (an Enum)
182 | "NB": t.uint8_t, # 0 - 3 (an Enum)
183 | "SB": t.uint8_t, # 0 - 1 (an Enum)
184 | "RO": t.uint8_t,
185 | "D6": t.uint8_t, # 0 - 5 (an Enum)
186 | "D7": t.uint8_t, # 0 - 7 (an Enum)
187 | "P3": t.uint8_t, # 0 - 5 (an Enum)
188 | "P4": t.uint8_t, # 0 - 5 (an Enum)
189 | # MAC diagnostics commands
190 | "ED": xbee_t.Bytes, # 16-byte value
191 | # I/O commands
192 | "IR": t.uint16_t_be,
193 | "IC": t.uint16_t_be,
194 | "D0": t.uint8_t, # 0 - 5 (an Enum)
195 | "D1": t.uint8_t, # 0 - 5 (an Enum)
196 | "D2": t.uint8_t, # 0 - 5 (an Enum)
197 | "D3": t.uint8_t, # 0 - 5 (an Enum)
198 | "D4": t.uint8_t, # 0 - 5 (an Enum)
199 | "D5": t.uint8_t, # 0 - 5 (an Enum)
200 | "D8": t.uint8_t, # 0 - 5 (an Enum)
201 | "D9": t.uint8_t, # 0 - 5 (an Enum)
202 | "P0": t.uint8_t, # 0 - 5 (an Enum)
203 | "P1": t.uint8_t, # 0 - 5 (an Enum)
204 | "P2": t.uint8_t, # 0 - 5 (an Enum)
205 | "P5": t.uint8_t, # 0 - 5 (an Enum)
206 | "P6": t.uint8_t, # 0 - 5 (an Enum)
207 | "P7": t.uint8_t, # 0 - 5 (an Enum)
208 | "P8": t.uint8_t, # 0 - 5 (an Enum)
209 | "P9": t.uint8_t, # 0 - 5 (an Enum)
210 | "LT": t.uint8_t,
211 | "PR": t.uint16_t_be,
212 | "RP": t.uint8_t,
213 | "%V": t.uint16_t_be, # read only
214 | "V+": t.uint16_t_be,
215 | "TP": t.uint16_t_be,
216 | "M0": t.uint16_t_be, # 0 - 0x3FF
217 | "M1": t.uint16_t_be, # 0 - 0x3FF
218 | # Diagnostics commands
219 | "VR": t.uint16_t_be,
220 | "HV": t.uint16_t_be,
221 | "AI": t.uint8_t,
222 | # AT command options
223 | "CT": t.uint16_t_be, # 2 - 0x028F
224 | "CN": None,
225 | "GT": t.uint16_t_be,
226 | "CC": t.uint8_t,
227 | # Sleep commands
228 | "SM": t.uint8_t,
229 | "SN": t.uint16_t_be,
230 | "SP": t.uint16_t_be,
231 | "ST": t.uint16_t_be,
232 | "SO": t.uint8_t,
233 | "WH": t.uint16_t_be,
234 | "SI": None,
235 | "PO": t.uint16_t_be, # 0 - 0x3E8
236 | # Execution commands
237 | "AC": None,
238 | "WR": None,
239 | "RE": None,
240 | "FR": None,
241 | "NR": t.Bool,
242 | "CB": t.uint8_t,
243 | "ND": t, # "optional 2-Byte NI value"
244 | "DN": xbee_t.Bytes, # "up to 20-Byte printable ASCII string"
245 | "IS": None,
246 | "1S": None,
247 | "AS": None,
248 | # Stuff I've guessed
249 | "CE": t.uint8_t,
250 | }
251 |
252 |
253 | BAUDRATE_TO_BD = {
254 | 1200: "ATBD0",
255 | 2400: "ATBD1",
256 | 4800: "ATBD2",
257 | 9600: "ATBD3",
258 | 19200: "ATBD4",
259 | 38400: "ATBD5",
260 | 57600: "ATBD6",
261 | 115200: "ATBD7",
262 | 230400: "ATBD8",
263 | }
264 |
265 |
266 | AT_COMMAND_RESULT = {
267 | 1: ATCommandError,
268 | 2: InvalidCommand,
269 | 3: InvalidParameter,
270 | 4: TransmissionFailure,
271 | }
272 |
273 |
274 | class XBee:
275 | """Class implementing XBee communication protocol."""
276 |
277 | def __init__(self, device_config: Dict[str, Any]) -> None:
278 | """Initialize instance."""
279 | self._config = device_config
280 | self._uart: Optional[uart.Gateway] = None
281 | self._seq: int = 1
282 | self._commands_by_id = {v[0]: k for k, v in COMMAND_RESPONSES.items()}
283 | self._awaiting = {}
284 | self._app = None
285 | self._cmd_mode_future: Optional[asyncio.Future] = None
286 | self._reset: asyncio.Event = asyncio.Event()
287 | self._running: asyncio.Event = asyncio.Event()
288 |
289 | @property
290 | def reset_event(self):
291 | """Return reset event."""
292 | return self._reset
293 |
294 | @property
295 | def coordinator_started_event(self):
296 | """Return coordinator started."""
297 | return self._running
298 |
299 | @property
300 | def is_running(self):
301 | """Return true if coordinator is running."""
302 | return self.coordinator_started_event.is_set()
303 |
304 | async def connect(self) -> None:
305 | """Connect to the device."""
306 | assert self._uart is None
307 | self._uart = await uart.connect(self._config, self)
308 |
309 | try:
310 | try:
311 | # Ensure we have escaped commands
312 | await self._at_command("AP", 2)
313 | except asyncio.TimeoutError:
314 | if not await self.init_api_mode():
315 | raise APIException("Failed to configure XBee for API mode")
316 | except Exception:
317 | await self.disconnect()
318 | raise
319 |
320 | def connection_lost(self, exc: Exception) -> None:
321 | """Lost serial connection."""
322 | if self._app is not None:
323 | self._app.connection_lost(exc)
324 |
325 | async def disconnect(self):
326 | """Close the connection."""
327 | if self._uart:
328 | await self._uart.disconnect()
329 | self._uart = None
330 |
331 | def _command(self, name, *args, mask_frame_id=False):
332 | """Send API frame to the device."""
333 | LOGGER.debug("Command %s %s", name, args)
334 | if self._uart is None:
335 | raise APIException("API is not running")
336 | frame_id = 0 if mask_frame_id else self._seq
337 | data, needs_response = self._api_frame(name, frame_id, *args)
338 | self._uart.send(data)
339 | future = None
340 | if needs_response and frame_id:
341 | future = asyncio.Future()
342 | self._awaiting[frame_id] = (future,)
343 | self._seq = (self._seq % 255) + 1
344 | return future
345 |
346 | async def _remote_at_command(self, ieee, nwk, options, name, *args):
347 | """Execute AT command on a different XBee module in the network."""
348 | LOGGER.debug("Remote AT command: %s %s", name, args)
349 | data = t.serialize(args, (AT_COMMANDS[name],))
350 | try:
351 | return await asyncio.wait_for(
352 | self._command(
353 | "remote_at", ieee, nwk, options, name.encode("ascii"), data
354 | ),
355 | timeout=REMOTE_AT_COMMAND_TIMEOUT,
356 | )
357 | except asyncio.TimeoutError:
358 | LOGGER.warning("No response to %s command", name)
359 | raise
360 |
361 | async def _at_partial(self, cmd_type, name, *args):
362 | LOGGER.debug("%s command: %s %s", cmd_type, name, args)
363 | data = t.serialize(args, (AT_COMMANDS[name],))
364 | try:
365 | return await asyncio.wait_for(
366 | self._command(cmd_type, name.encode("ascii"), data),
367 | timeout=AT_COMMAND_TIMEOUT,
368 | )
369 | except asyncio.TimeoutError:
370 | LOGGER.warning("%s: No response to %s command", cmd_type, name)
371 | raise
372 |
373 | _at_command = functools.partialmethod(_at_partial, "at")
374 | _queued_at = functools.partialmethod(_at_partial, "queued_at")
375 |
376 | def _api_frame(self, name, *args):
377 | """Build API frame."""
378 | c = COMMAND_REQUESTS[name]
379 | return (bytes([c[0]]) + t.serialize(args, c[1])), c[2]
380 |
381 | def frame_received(self, data):
382 | """Handle API frame from the device."""
383 | command = self._commands_by_id[data[0]]
384 | LOGGER.debug("Frame received: %s", command)
385 | data, rest = t.deserialize(data[1:], COMMAND_RESPONSES[command][1])
386 | try:
387 | getattr(self, f"_handle_{command}")(*data)
388 | except AttributeError:
389 | LOGGER.error("No '%s' handler. Data: %s", command, binascii.hexlify(data))
390 |
391 | def _handle_at_response(self, frame_id, cmd, status, value):
392 | """Local AT command response."""
393 | (fut,) = self._awaiting.pop(frame_id)
394 |
395 | if status:
396 | try:
397 | exception = AT_COMMAND_RESULT[status]
398 | except KeyError:
399 | exception = ATCommandException
400 | fut.set_exception(exception(f"AT Command response: {status}"))
401 | return
402 |
403 | response_type = AT_COMMANDS[cmd.decode("ascii")]
404 | if response_type is None or len(value) == 0:
405 | fut.set_result(None)
406 | return
407 |
408 | response, remains = response_type.deserialize(value)
409 | fut.set_result(response)
410 |
411 | def _handle_remote_at_response(self, frame_id, ieee, nwk, cmd, status, value):
412 | """Remote AT command response."""
413 | LOGGER.debug(
414 | "Remote AT command response from: %s",
415 | (frame_id, ieee, nwk, cmd, status, value),
416 | )
417 | return self._handle_at_response(frame_id, cmd, status, value)
418 |
419 | def _handle_many_to_one_rri(self, ieee, nwk, reserved):
420 | LOGGER.debug("_handle_many_to_one_rri: %s", (ieee, nwk, reserved))
421 |
422 | def _handle_modem_status(self, status):
423 | LOGGER.debug("Handle modem status frame: %s", status)
424 | status = status
425 | if status == xbee_t.ModemStatus.COORDINATOR_STARTED:
426 | self.coordinator_started_event.set()
427 | elif status in (
428 | xbee_t.ModemStatus.HARDWARE_RESET,
429 | xbee_t.ModemStatus.WATCHDOG_TIMER_RESET,
430 | ):
431 | self.reset_event.set()
432 | self.coordinator_started_event.clear()
433 | elif status == xbee_t.ModemStatus.DISASSOCIATED:
434 | self.coordinator_started_event.clear()
435 |
436 | if self._app:
437 | self._app.handle_modem_status(status)
438 |
439 | def _handle_explicit_rx_indicator(
440 | self, ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data
441 | ):
442 | LOGGER.debug(
443 | "_handle_explicit_rx: %s",
444 | (ieee, nwk, dst_ep, cluster, rx_opts, binascii.hexlify(data)),
445 | )
446 | self._app.handle_rx(ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data)
447 |
448 | def _handle_route_record_indicator(self, ieee, src, rx_opts, hops):
449 | """Handle Route Record indicator from a device."""
450 | LOGGER.debug("_handle_route_record_indicator: %s", (ieee, src, rx_opts, hops))
451 |
452 | def _handle_tx_status(self, frame_id, nwk, tries, tx_status, dsc_status):
453 | LOGGER.debug(
454 | (
455 | "tx_explicit to 0x%04x: %s after %i tries. Discovery Status: %s,"
456 | " Frame #%i"
457 | ),
458 | nwk,
459 | tx_status,
460 | tries,
461 | dsc_status,
462 | frame_id,
463 | )
464 | try:
465 | (fut,) = self._awaiting.pop(frame_id)
466 | except KeyError:
467 | LOGGER.debug("unexpected tx_status report received")
468 | return
469 |
470 | try:
471 | if tx_status in (
472 | xbee_t.TXStatus.BROADCAST_APS_TX_ATTEMPT,
473 | xbee_t.TXStatus.SELF_ADDRESSED,
474 | xbee_t.TXStatus.SUCCESS,
475 | ):
476 | fut.set_result(tx_status)
477 | else:
478 | fut.set_exception(DeliveryError(f"{tx_status}"))
479 | except asyncio.InvalidStateError as ex:
480 | LOGGER.debug("duplicate tx_status for %s nwk? State: %s", nwk, ex)
481 |
482 | def _handle_registration_status(self, frame_id, status):
483 | (fut,) = self._awaiting.pop(frame_id)
484 | if status:
485 | fut.set_exception(RuntimeError(f"Registration Status: {status.name}"))
486 | return
487 | LOGGER.debug(f"Registration Status: {status.name}")
488 |
489 | fut.set_result(status)
490 |
491 | def set_application(self, app):
492 | """Set reference to ControllerApplication."""
493 | self._app = app
494 |
495 | def handle_command_mode_rsp(self, data):
496 | """Handle AT command response in command mode."""
497 | fut = self._cmd_mode_future
498 | if fut is None or fut.done():
499 | return
500 | if "OK" in data:
501 | fut.set_result(True)
502 | elif "ERROR" in data:
503 | fut.set_result(False)
504 | else:
505 | fut.set_result(data)
506 |
507 | async def command_mode_at_cmd(self, command):
508 | """Send AT command in command mode."""
509 | self._cmd_mode_future = asyncio.Future()
510 | self._uart.command_mode_send(command.encode("ascii"))
511 |
512 | try:
513 | res = await asyncio.wait_for(self._cmd_mode_future, timeout=2)
514 | return res
515 | except asyncio.TimeoutError:
516 | LOGGER.debug("Command mode no response to AT '%s' command", command)
517 | return None
518 |
519 | async def enter_at_command_mode(self):
520 | """Enter command mode."""
521 | await asyncio.sleep(1.2) # keep UART quiet for 1s before escaping
522 | return await self.command_mode_at_cmd("+++")
523 |
524 | async def api_mode_at_commands(self, baudrate):
525 | """Configure API and exit AT command mode."""
526 | cmds = ["ATAP2", "ATWR", "ATCN"]
527 |
528 | bd = BAUDRATE_TO_BD.get(baudrate)
529 | if bd:
530 | cmds.insert(0, bd)
531 |
532 | for cmd in cmds:
533 | if not await self.command_mode_at_cmd(cmd + "\r"):
534 | LOGGER.debug("No response to %s cmd", cmd)
535 | return None
536 | LOGGER.debug("Successfully sent %s cmd", cmd)
537 | self._uart.reset_command_mode()
538 | return True
539 |
540 | async def init_api_mode(self):
541 | """Configure API mode on XBee."""
542 | current_baudrate = self._uart.baudrate
543 | if await self.enter_at_command_mode():
544 | LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate)
545 | return await self.api_mode_at_commands(current_baudrate)
546 |
547 | for baudrate in sorted(BAUDRATE_TO_BD.keys()):
548 | LOGGER.debug(
549 | "Failed to enter AT command mode at %dbps, trying %d next",
550 | self._uart.baudrate,
551 | baudrate,
552 | )
553 | self._uart.baudrate = baudrate
554 | if await self.enter_at_command_mode():
555 | LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate)
556 | res = await self.api_mode_at_commands(current_baudrate)
557 | self._uart.baudrate = current_baudrate
558 | return res
559 |
560 | LOGGER.debug(
561 | "Couldn't enter AT command mode at any known baudrate."
562 | "Configure XBee manually for escaped API mode ATAP2"
563 | )
564 | return False
565 |
566 | def __getattr__(self, item):
567 | """Handle supported command requests."""
568 | if item in COMMAND_REQUESTS:
569 | return functools.partial(self._command, item)
570 | raise AttributeError(f"Unknown command {item}")
571 |
--------------------------------------------------------------------------------
/zigpy_xbee/config.py:
--------------------------------------------------------------------------------
1 | """XBee module config."""
2 |
3 | import voluptuous as vol
4 | import zigpy.config
5 |
6 | SCHEMA_DEVICE = zigpy.config.SCHEMA_DEVICE.extend(
7 | {vol.Optional(zigpy.config.CONF_DEVICE_BAUDRATE, default=57600): int}
8 | )
9 |
10 | CONFIG_SCHEMA = zigpy.config.CONFIG_SCHEMA.extend(
11 | {vol.Required(zigpy.config.CONF_DEVICE): zigpy.config.SCHEMA_DEVICE}
12 | )
13 |
--------------------------------------------------------------------------------
/zigpy_xbee/exceptions.py:
--------------------------------------------------------------------------------
1 | """Additional exceptions for XBee."""
2 |
3 |
4 | class ATCommandException(Exception):
5 | """Base exception class for AT Command exceptions."""
6 |
7 |
8 | class ATCommandError(ATCommandException):
9 | """Exception for AT Command Status 1 (ERROR)."""
10 |
11 |
12 | class InvalidCommand(ATCommandException):
13 | """Exception for AT Command Status 2 (Invalid command)."""
14 |
15 |
16 | class InvalidParameter(ATCommandException):
17 | """Exception for AT Command Status 3 (Invalid parameter)."""
18 |
19 |
20 | class TransmissionFailure(ATCommandException):
21 | """Exception for Remote AT Command Status 4 (Transmission failure)."""
22 |
--------------------------------------------------------------------------------
/zigpy_xbee/types.py:
--------------------------------------------------------------------------------
1 | """Additional types for data parsing."""
2 |
3 | import enum
4 |
5 | import zigpy.types as t
6 |
7 |
8 | class Bytes(bytes):
9 | """Serializable and deserializable bytes."""
10 |
11 | def serialize(self):
12 | """Serialize the class."""
13 | return self
14 |
15 | @classmethod
16 | def deserialize(cls, data):
17 | """Deserialize the data into the class."""
18 | return cls(data), b""
19 |
20 |
21 | class ATCommand(Bytes):
22 | """XBee AT command name."""
23 |
24 | @classmethod
25 | def deserialize(cls, data):
26 | """Deserialize the data into the class."""
27 | return cls(data[:2]), data[2:]
28 |
29 |
30 | class EUI64(t.EUI64):
31 | """EUI64 without prefix."""
32 |
33 | @classmethod
34 | def deserialize(cls, data):
35 | """Deserialize the data into the class."""
36 | r, data = super().deserialize(data)
37 | return cls(r[::-1]), data
38 |
39 | def serialize(self):
40 | """Serialize the class."""
41 | assert self._length == len(self)
42 | return super().serialize()[::-1]
43 |
44 |
45 | class UndefinedEnumMeta(enum.EnumMeta):
46 | """Meta class for Enum that always has a value."""
47 |
48 | def __call__(cls, value=None, *args, **kwargs):
49 | """Return the member, default, or undefined value."""
50 | if value is None:
51 | # the 1st enum member is default
52 | return next(iter(cls))
53 |
54 | try:
55 | return super().__call__(value, *args, **kwargs)
56 | except ValueError as exc:
57 | try:
58 | return super().__call__(cls._UNDEFINED)
59 | except AttributeError:
60 | raise exc
61 |
62 |
63 | class UndefinedEnum(enum.Enum, metaclass=UndefinedEnumMeta):
64 | """Enum that always has a value."""
65 |
66 |
67 | class FrameId(t.uint8_t):
68 | """API frame ID."""
69 |
70 |
71 | class NWK(t.uint16_t_be):
72 | """zigpy.types.NWK but big endian."""
73 |
74 | def __repr__(self):
75 | """Get printable representation."""
76 | return f"0x{self:04x}"
77 |
78 | def __str__(self):
79 | """Get string representation."""
80 | return f"0x{self:04x}"
81 |
82 |
83 | class Relays(t.LVList, item_type=NWK, length_type=t.uint8_t):
84 | """List of Relays."""
85 |
86 |
87 | UNKNOWN_IEEE = EUI64([t.uint8_t(0xFF) for i in range(0, 8)])
88 | UNKNOWN_NWK = NWK(0xFFFE)
89 |
90 |
91 | class TXStatus(t.uint8_t, UndefinedEnum):
92 | """TX Status frame."""
93 |
94 | SUCCESS = 0x00 # Standard
95 |
96 | # all retries are expired and no ACK is received.
97 | # Not returned for Broadcasts
98 | NO_ACK_RECEIVED = 0x01
99 | CCA_FAILURE = 0x02
100 |
101 | # Transmission was purged because a coordinator tried to send to an end
102 | # device, but it timed out waiting for a poll from the end device that
103 | # never occurred, this haapens when Coordinator times out of an indirect
104 | # transmission. Timeouse is defines ad 2.5 * 'SP' (Cyclic Sleep Period)
105 | # parameter value
106 | INDIRECT_TX_TIMEOUT = 0x03
107 |
108 | # invalid destination endpoint
109 | INVALID_DESTINATION_ENDPOINT = 0x15
110 |
111 | # not returned for Broadcasts
112 | NETWORK_ACK_FAILURE = 0x21
113 |
114 | # TX failed because end device was not joined to the network
115 | INDIRECT_TX_FAILURE = 0x22
116 |
117 | # Self addressed
118 | SELF_ADDRESSED = 0x23
119 |
120 | # Address not found
121 | ADDRESS_NOT_FOUND = 0x24
122 |
123 | # Route not found
124 | ROUTE_NOT_FOUND = 0x25
125 |
126 | # Broadcast source failed to hear a neighbor relay the message
127 | BROADCAST_RELAY_FAILURE = 0x26
128 |
129 | # Invalid binding table index
130 | INVALID_BINDING_IDX = 0x2B
131 |
132 | # Resource error lack of free buffers, timers, and so forth.
133 | NO_RESOURCES = 0x2C
134 |
135 | # Attempted broadcast with APS transmission
136 | BROADCAST_APS_TX_ATTEMPT = 0x2D
137 |
138 | # Attempted unicast with APS transmission, but EE=0
139 | UNICAST_APS_TX_ATTEMPT = 0x2E
140 |
141 | INTERNAL_ERROR = 0x31
142 |
143 | # Transmission failed due to resource depletion (for example, out of
144 | # buffers, especially for indirect messages from coordinator)
145 | NO_RESOURCES_2 = 0x32
146 |
147 | # The payload in the frame was larger than allowed
148 | PAYLOAD_TOO_LARGE = 0x74
149 | _UNDEFINED = 0x2C
150 |
151 |
152 | class DiscoveryStatus(t.uint8_t, UndefinedEnum):
153 | """Discovery status of TX Status frame."""
154 |
155 | SUCCESS = 0x00
156 | ADDRESS_DISCOVERY = 0x01
157 | ROUTE_DISCOVERY = 0x02
158 | ADDRESS_AND_ROUTE = 0x03
159 | EXTENDED_TIMEOUT = 0x40
160 | _UNDEFINED = 0x00
161 |
162 |
163 | class TXOptions(t.bitmap8):
164 | """TX Options for explicit transmit frame."""
165 |
166 | NONE = 0x00
167 |
168 | Disable_Retries_and_Route_Repair = 0x01
169 | Enable_APS_Encryption = 0x20
170 | Use_Extended_TX_Timeout = 0x40
171 |
172 |
173 | class ModemStatus(t.uint8_t, UndefinedEnum):
174 | """Modem Status."""
175 |
176 | HARDWARE_RESET = 0x00
177 | WATCHDOG_TIMER_RESET = 0x01
178 | JOINED_NETWORK = 0x02
179 | DISASSOCIATED = 0x03
180 | CONFIGURATION_ERROR_SYNCHRONIZATION_LOST = 0x04
181 | COORDINATOR_REALIGNMENT = 0x05
182 | COORDINATOR_STARTED = 0x06
183 | NETWORK_SECURITY_KEY_UPDATED = 0x07
184 | NETWORK_WOKE_UP = 0x0B
185 | NETWORK_WENT_TO_SLEEP = 0x0C
186 | VOLTAGE_SUPPLY_LIMIT_EXCEEDED = 0x0D
187 | DEVICE_CLOUD_CONNECTED = 0x0E
188 | DEVICE_CLOUD_DISCONNECTED = 0x0F
189 | MODEM_KEY_ESTABLISHED = 0x10
190 | MODEM_CONFIGURATION_CHANGED_WHILE_JOIN_IN_PROGRESS = 0x11
191 | ACCESS_FAULT = 0x12
192 | FATAL_STACK_ERROR = 0x13
193 | PLKE_TABLE_INITIATED = 0x14
194 | PLKE_TABLE_SUCCESS = 0x15
195 | PLKE_TABLE_IS_FULL = 0x16
196 | PLKE_NOT_AUTHORIZED = 0x17
197 | PLKE_INVALID_TRUST_CENTER_REQUEST = 0x18
198 | PLKE_TRUST_CENTER_UPDATE_FAIL = 0x19
199 | PLKE_BAD_EUI_ADDRESS = 0x1A
200 | PLKE_LINK_KEY_REJECTED = 0x1B
201 | PLKE_UPDATE_OCCURED = 0x1C
202 | PLKE_LINK_KEY_TABLE_CLEAR = 0x1D
203 | ZIGBEE_FREQUENCY_AGILITY_HAS_REQUESTED_CHANNEL_CHANGE = 0x1E
204 | ZIGBEE_EXECUTE_ATFR_NO_JOINABLE_BEACON_RESPONSES = 0x1F
205 | ZIGBEE_TOKENS_SPACE_RECOVERED = 0x20
206 | ZIGBEE_TOKENS_SPACE_UNRECOVERABLE = 0x21
207 | ZIGBEE_TOKENS_SPACE_CORRUPTED = 0x22
208 | ZIGBEE_DUAL_MODE_METAFRAME_ERROR = 0x30
209 | BLE_CONNECT = 0x32
210 | BLE_DISCONNECT = 0x33
211 | NO_SECURE_SESSION_CONNECTION = 0x34
212 | CELL_COMPONENT_UPDATE_STARTED = 0x35
213 | CELL_COMPONENT_UPDATE_FAILED = 0x36
214 | CELL_COMPONENT_UPDATE_SUCCEDED = 0x37
215 | XBEE_FIRMWARE_UPDATE_STARTED = 0x38
216 | XBEE_FIRMWARE_UPDATE_FAILED = 0x39
217 | XBEE_WILL_RESET_TO_APPLY_FIRMWARE_UPDATE = 0x3A
218 | SECURE_SESSION_SUCCESSFULLY_ESTABLISHED = 0x3B
219 | SECURE_SESSION_ENDED = 0x3C
220 | SECURE_SESSION_AUTHENTICATION_FAILED = 0x3D
221 | PAN_ID_CONFLICT_DETECTED = 0x3E
222 | PAN_ID_UPDATED_DUE_TO_CONFLICT = 0x3F
223 | ROUTER_PAN_ID_CHANGED_BY_COORDINATOR_DUE_TO_CONFLICT = 0x40
224 | NETWORK_WATCHDOG_TIMEOUT_EXPIRED_THREE_TIMES = 0x42
225 | JOIN_WINDOW_OPENED = 0x43
226 | JOIN_WINDOW_CLOSED = 0x44
227 | NETWORK_SECURITY_KEY_ROTATION_INITIATED = 0x45
228 | STACK_RESET = 0x80
229 | FIB_BOOTLOADER_RESET = 0x81
230 | SEND_OR_JOIN_COMMAND_ISSUED_WITHOUT_CONNECTING_FROM_AP = 0x82
231 | ACCESS_POINT_NOT_FOUND = 0x83
232 | PSK_NOT_CONFIGURED = 0x84
233 | SSID_NOT_FOUND = 0x87
234 | FAILED_TO_JOIN_WITH_SECURITY_ENABLED = 0x88
235 | COER_LOCKUP_OR_CRYSTAL_FAILURE_RESET = 0x89
236 | INVALID_CHANNEL = 0x8A
237 | LOW_VOLTAGE_RESET = 0x8B
238 | FAILED_TO_JOIN_ACCESS_POINT = 0x8E
239 |
240 | UNKNOWN_MODEM_STATUS = 0xFF
241 | _UNDEFINED = 0xFF
242 |
243 |
244 | class RegistrationStatus(t.uint8_t, UndefinedEnum):
245 | """Key Registration Status."""
246 |
247 | SUCCESS = 0x00
248 | KEY_TOO_LONG = 0x01
249 | TRANSIENT_KEY_TABLE_IS_FULL = 0x18
250 | ADDRESS_NOT_FOUND_IN_THE_KEY_TABLE = 0xB1
251 | KEY_IS_INVALID_OR_RESERVED = 0xB2
252 | INVALID_ADDRESS = 0xB3
253 | KEY_TABLE_IS_FULL = 0xB4
254 | SECURITY_DATA_IS_INVALID_INSTALL_CODE_CRC_FAILS = 0xBD
255 |
256 | UNKNOWN_MODEM_STATUS = 0xFF
257 | _UNDEFINED = 0xFF
258 |
--------------------------------------------------------------------------------
/zigpy_xbee/uart.py:
--------------------------------------------------------------------------------
1 | """Module for UART communication to the device."""
2 |
3 | import asyncio
4 | import logging
5 | from typing import Any, Dict
6 |
7 | import zigpy.config
8 | import zigpy.serial
9 |
10 | LOGGER = logging.getLogger(__name__)
11 |
12 |
13 | class Gateway(zigpy.serial.SerialProtocol):
14 | """Class implementing the UART protocol."""
15 |
16 | START = b"\x7E"
17 | ESCAPE = b"\x7D"
18 | XON = b"\x11"
19 | XOFF = b"\x13"
20 |
21 | RESERVED = START + ESCAPE + XON + XOFF
22 | THIS_ONE = True
23 |
24 | def __init__(self, api):
25 | """Initialize instance."""
26 | super().__init__()
27 | self._api = api
28 | self._in_command_mode = False
29 |
30 | def send(self, data):
31 | """Send data, taking care of escaping and framing."""
32 | LOGGER.debug("Sending: %s", data)
33 | checksum = bytes([self._checksum(data)])
34 | frame = self.START + self._escape(
35 | len(data).to_bytes(2, "big") + data + checksum
36 | )
37 | self._transport.write(frame)
38 |
39 | @property
40 | def baudrate(self):
41 | """Baudrate."""
42 | return self._transport.serial.baudrate
43 |
44 | @baudrate.setter
45 | def baudrate(self, baudrate):
46 | """Set baudrate."""
47 | if baudrate in self._transport.serial.BAUDRATES:
48 | self._transport.serial.baudrate = baudrate
49 | else:
50 | raise ValueError(
51 | f"baudrate must be one of {self._transport.serial.BAUDRATES}"
52 | )
53 |
54 | def connection_lost(self, exc) -> None:
55 | """Port was closed expectedly or unexpectedly."""
56 | super().connection_lost(exc)
57 |
58 | if self._api is not None:
59 | self._api.connection_lost(exc)
60 |
61 | def command_mode_rsp(self, data):
62 | """Handle AT command mode response."""
63 | data = data.decode("ascii", "ignore")
64 | LOGGER.debug("Handling AT command mode response: %s", data)
65 | self._api.handle_command_mode_rsp(data)
66 |
67 | def command_mode_send(self, data):
68 | """Send data in command mode."""
69 | LOGGER.debug("Command mode sending %s to uart", data)
70 | self._in_command_mode = True
71 | self._transport.write(data)
72 |
73 | def data_received(self, data):
74 | """Handle data received from the UART callback."""
75 | super().data_received(data)
76 | while self._buffer:
77 | frame = self._extract_frame()
78 | if frame is None:
79 | break
80 | self.frame_received(frame)
81 | if self._in_command_mode and self._buffer[-1:] == b"\r":
82 | rsp = self._buffer[:-1]
83 | self._buffer.clear()
84 | self.command_mode_rsp(rsp)
85 |
86 | def frame_received(self, frame):
87 | """Frame receive handler."""
88 | LOGGER.debug("Frame received: %s", frame)
89 | self._api.frame_received(frame)
90 |
91 | def reset_command_mode(self):
92 | r"""Reset command mode and ignore '\r' character as command mode response."""
93 | self._in_command_mode = False
94 |
95 | def _extract_frame(self):
96 | first_start = self._buffer.find(self.START)
97 | if first_start < 0:
98 | return None
99 |
100 | data = self._buffer[first_start + 1 :]
101 | frame_len, data = self._get_unescaped(data, 2)
102 | if frame_len is None:
103 | return None
104 |
105 | frame_len = int.from_bytes(frame_len, "big")
106 | frame, data = self._get_unescaped(data, frame_len)
107 | if frame is None:
108 | return None
109 | checksum, data = self._get_unescaped(data, 1)
110 | if checksum is None:
111 | return None
112 | if self._checksum(frame) != checksum[0]:
113 | # TODO: Signal decode failure so that error frame can be sent
114 | self._buffer = data
115 | return None
116 |
117 | self._buffer = data
118 | return frame
119 |
120 | def _get_unescaped(self, data, n):
121 | ret = []
122 | idx = 0
123 | while len(ret) < n and idx < len(data):
124 | b = data[idx]
125 | if b == self.ESCAPE[0]:
126 | idx += 1
127 | if idx >= len(data):
128 | return None, None
129 | b = data[idx] ^ 0x020
130 | ret.append(b)
131 | idx += 1
132 |
133 | if len(ret) >= n:
134 | return bytes(ret), data[idx:]
135 | return None, None
136 |
137 | def _escape(self, data):
138 | ret = []
139 | for b in data:
140 | if b in self.RESERVED:
141 | ret.append(ord(self.ESCAPE))
142 | ret.append(b ^ 0x20)
143 | else:
144 | ret.append(b)
145 | return bytes(ret)
146 |
147 | def _checksum(self, data):
148 | return 0xFF - (sum(data) % 0x100)
149 |
150 |
151 | async def connect(device_config: Dict[str, Any], api) -> Gateway:
152 | """Connect to the device."""
153 | transport, protocol = await zigpy.serial.create_serial_connection(
154 | loop=asyncio.get_running_loop(),
155 | protocol_factory=lambda: Gateway(api),
156 | url=device_config[zigpy.config.CONF_DEVICE_PATH],
157 | baudrate=device_config[zigpy.config.CONF_DEVICE_BAUDRATE],
158 | xonxoff=device_config[zigpy.config.CONF_DEVICE_BAUDRATE],
159 | )
160 |
161 | await protocol.wait_until_connected()
162 |
163 | return protocol
164 |
--------------------------------------------------------------------------------
/zigpy_xbee/zigbee/__init__.py:
--------------------------------------------------------------------------------
1 | """XBee ControllerApplication implementation."""
2 |
--------------------------------------------------------------------------------
/zigpy_xbee/zigbee/application.py:
--------------------------------------------------------------------------------
1 | """ControllerApplication for XBee adapters."""
2 |
3 | from __future__ import annotations
4 |
5 | import asyncio
6 | import logging
7 | import math
8 | import statistics
9 | from typing import Any
10 |
11 | import zigpy.application
12 | import zigpy.config
13 | from zigpy.config import CONF_DEVICE
14 | import zigpy.device
15 | import zigpy.exceptions
16 | import zigpy.quirks
17 | import zigpy.state
18 | import zigpy.types
19 | import zigpy.util
20 | from zigpy.zcl import foundation
21 | from zigpy.zcl.clusters.general import Groups
22 | import zigpy.zdo.types as zdo_t
23 |
24 | import zigpy_xbee
25 | import zigpy_xbee.api
26 | import zigpy_xbee.config
27 | from zigpy_xbee.exceptions import InvalidCommand
28 | from zigpy_xbee.types import EUI64, UNKNOWN_IEEE, UNKNOWN_NWK, TXOptions, TXStatus
29 |
30 | # how long coordinator would hold message for an end device in 10ms units
31 | CONF_CYCLIC_SLEEP_PERIOD = 0x0300
32 | # end device poll timeout = 3 * SN * SP * 10ms
33 | CONF_POLL_TIMEOUT = 0x029B
34 | TIMEOUT_TX_STATUS = 120
35 | TIMEOUT_REPLY = 5
36 | TIMEOUT_REPLY_EXTENDED = 28
37 |
38 | LOGGER = logging.getLogger(__name__)
39 |
40 | XBEE_ENDPOINT_ID = 0xE6
41 |
42 |
43 | class ControllerApplication(zigpy.application.ControllerApplication):
44 | """Implementation of Zigpy ControllerApplication for XBee devices."""
45 |
46 | CONFIG_SCHEMA = zigpy_xbee.config.CONFIG_SCHEMA
47 |
48 | def __init__(self, config: dict[str, Any]):
49 | """Initialize instance."""
50 | super().__init__(config=config)
51 | self._api: zigpy_xbee.api.XBee | None = None
52 | self.topology.add_listener(self)
53 |
54 | async def disconnect(self):
55 | """Shutdown application."""
56 | if self._api:
57 | await self._api.disconnect()
58 | self._api = None
59 |
60 | async def connect(self):
61 | """Connect to the device."""
62 | api = zigpy_xbee.api.XBee(self._config[CONF_DEVICE])
63 | await api.connect()
64 | api.set_application(self)
65 |
66 | self._api = api
67 |
68 | async def start_network(self):
69 | """Configure the module to work with Zigpy."""
70 | association_state = await asyncio.wait_for(
71 | self._get_association_state(), timeout=4
72 | )
73 |
74 | # Enable ZDO passthrough
75 | await self._api._at_command("AO", 0x03)
76 |
77 | if self.state.node_info == zigpy.state.NodeInfo():
78 | await self.load_network_info()
79 |
80 | enc_enabled = await self._api._at_command("EE")
81 | enc_options = await self._api._at_command("EO")
82 | zb_profile = await self._api._at_command("ZS")
83 |
84 | if (
85 | enc_enabled != 1
86 | or enc_options & 0b0010 != 0b0010
87 | or zb_profile != 2
88 | or association_state != 0
89 | or self.state.node_info.nwk != 0x0000
90 | ):
91 | raise zigpy.exceptions.NetworkNotFormed("Network is not formed")
92 |
93 | # Disable joins
94 | await self._api._at_command("NJ", 0)
95 | await self._api._at_command("SP", CONF_CYCLIC_SLEEP_PERIOD)
96 | await self._api._at_command("SN", CONF_POLL_TIMEOUT)
97 |
98 | dev = zigpy.device.Device(
99 | self, self.state.node_info.ieee, self.state.node_info.nwk
100 | )
101 | dev.status = zigpy.device.Status.ENDPOINTS_INIT
102 | dev.add_endpoint(XBEE_ENDPOINT_ID)
103 |
104 | xbee_dev = XBeeCoordinator(
105 | self, self.state.node_info.ieee, self.state.node_info.nwk, dev
106 | )
107 | self.listener_event("raw_device_initialized", xbee_dev)
108 | self.devices[dev.ieee] = xbee_dev
109 |
110 | await self.register_endpoints()
111 |
112 | async def load_network_info(self, *, load_devices=False):
113 | """Load supported parameters of network_info and node_info from the device."""
114 | # Load node info
115 | node_info = self.state.node_info
116 | node_info.nwk = zigpy.types.NWK(await self._api._at_command("MY"))
117 | serial_high = await self._api._at_command("SH")
118 | serial_low = await self._api._at_command("SL")
119 | node_info.ieee = zigpy.types.EUI64(
120 | (serial_high.to_bytes(4, "big") + serial_low.to_bytes(4, "big"))[::-1]
121 | )
122 |
123 | try:
124 | if await self._api._at_command("CE") == 0x01:
125 | node_info.logical_type = zdo_t.LogicalType.Coordinator
126 | else:
127 | node_info.logical_type = zdo_t.LogicalType.EndDevice
128 | except InvalidCommand:
129 | LOGGER.warning("CE command failed, assuming node is coordinator")
130 | node_info.logical_type = zdo_t.LogicalType.Coordinator
131 |
132 | # TODO: Feature detect the XBee's exact model
133 | node_info.model = "XBee"
134 | node_info.manufacturer = "Digi"
135 |
136 | version = await self._api._at_command("VR")
137 | node_info.version = f"{int(version):#06x}"
138 |
139 | # Load network info
140 | pan_id = await self._api._at_command("OI")
141 | extended_pan_id = await self._api._at_command("ID")
142 |
143 | network_info = self.state.network_info
144 | network_info.source = f"zigpy-xbee@{zigpy_xbee.__version__}"
145 | network_info.pan_id = zigpy.types.PanId(pan_id)
146 | network_info.extended_pan_id = zigpy.types.ExtendedPanId(
147 | zigpy.types.uint64_t(extended_pan_id).serialize()
148 | )
149 | network_info.channel = await self._api._at_command("CH")
150 |
151 | async def reset_network_info(self) -> None:
152 | """Reset Zigbee network."""
153 | await self._api._at_command("NR", 0)
154 |
155 | async def write_network_info(self, *, network_info, node_info):
156 | """Write supported network_info and node_info parameters to the device."""
157 | epid, _ = zigpy.types.uint64_t.deserialize(
158 | network_info.extended_pan_id.serialize()
159 | )
160 | await self._api._queued_at("ID", epid)
161 |
162 | await self._api._queued_at("ZS", 2)
163 | scan_bitmask = 1 << (network_info.channel - 11)
164 | await self._api._queued_at("SC", scan_bitmask)
165 | await self._api._queued_at("EE", 1)
166 | await self._api._queued_at("EO", 0b0010)
167 | await self._api._queued_at("NK", network_info.network_key.key.serialize())
168 | await self._api._queued_at("KY", network_info.tc_link_key.key.serialize())
169 | await self._api._queued_at("NJ", 0)
170 | await self._api._queued_at("SP", CONF_CYCLIC_SLEEP_PERIOD)
171 | await self._api._queued_at("SN", CONF_POLL_TIMEOUT)
172 |
173 | try:
174 | await self._api._queued_at("CE", 1)
175 | except InvalidCommand:
176 | pass
177 |
178 | await self._api._at_command("WR")
179 |
180 | await asyncio.wait_for(self._api.coordinator_started_event.wait(), timeout=10)
181 | association_state = await asyncio.wait_for(
182 | self._get_association_state(), timeout=10
183 | )
184 | LOGGER.debug("Association state: %s", association_state)
185 |
186 | async def _move_network_to_channel(
187 | self, new_channel: int, new_nwk_update_id: int
188 | ) -> None:
189 | """Move the coordinator to a new channel."""
190 | scan_bitmask = 1 << (new_channel - 11)
191 | await self._api._queued_at("SC", scan_bitmask)
192 |
193 | async def energy_scan(
194 | self, channels: zigpy.types.Channels, duration_exp: int, count: int
195 | ) -> dict[int, float]:
196 | """Run an energy detection scan and returns the per-channel scan results."""
197 | all_results = {}
198 |
199 | for _ in range(count):
200 | try:
201 | results = await self._api._at_command("ED", bytes([duration_exp]))
202 | except InvalidCommand:
203 | LOGGER.warning("Coordinator does not support energy scanning")
204 | return {c: 0 for c in channels}
205 |
206 | results = {
207 | channel: -int(rssi) for channel, rssi in zip(range(11, 27), results)
208 | }
209 |
210 | for channel, rssi in results.items():
211 | all_results.setdefault(channel, []).append(rssi)
212 |
213 | def logistic(x: float, *, L: float = 1, x_0: float = 0, k: float = 1) -> float:
214 | """Logistic function."""
215 | return L / (1 + math.exp(-k * (x - x_0)))
216 |
217 | def map_rssi_to_energy(rssi: int) -> float:
218 | """Remaps RSSI (in dBm) to Energy (0-255)."""
219 | RSSI_MAX = -5
220 | RSSI_MIN = -92
221 | return logistic(
222 | x=rssi,
223 | L=255,
224 | x_0=RSSI_MIN + 0.45 * (RSSI_MAX - RSSI_MIN),
225 | k=0.13,
226 | )
227 |
228 | energy = {
229 | channel: map_rssi_to_energy(statistics.mean(all_rssi))
230 | for channel, all_rssi in all_results.items()
231 | }
232 |
233 | return {channel: energy.get(channel, 0) for channel in channels}
234 |
235 | async def force_remove(self, dev):
236 | """Forcibly remove device from NCP."""
237 |
238 | async def add_endpoint(self, descriptor: zdo_t.SimpleDescriptor) -> None:
239 | """Register a new endpoint on the device."""
240 | self._device.replacement["endpoints"][descriptor.endpoint] = {
241 | "device_type": descriptor.device_type,
242 | "profile_id": descriptor.profile,
243 | "input_clusters": descriptor.input_clusters,
244 | "output_clusters": descriptor.output_clusters,
245 | }
246 | self._device.add_endpoint(descriptor.endpoint)
247 |
248 | async def _get_association_state(self):
249 | """Wait for Zigbee to start."""
250 | state = await self._api._at_command("AI")
251 | while state == 0xFF:
252 | LOGGER.debug("Waiting for radio startup...")
253 | await asyncio.sleep(0.2)
254 | state = await self._api._at_command("AI")
255 | return state
256 |
257 | async def send_packet(self, packet: zigpy.types.ZigbeePacket) -> None:
258 | """Send ZigbeePacket via the device."""
259 | LOGGER.debug("Sending packet %r", packet)
260 |
261 | try:
262 | device = self.get_device_with_address(packet.dst)
263 | except (KeyError, ValueError):
264 | device = None
265 |
266 | tx_opts = TXOptions.NONE
267 |
268 | if packet.extended_timeout:
269 | tx_opts |= TXOptions.Use_Extended_TX_Timeout
270 |
271 | if packet.dst.addr_mode == zigpy.types.AddrMode.Group:
272 | tx_opts |= 0x08 # where did this come from?
273 |
274 | long_addr = UNKNOWN_IEEE
275 | short_addr = UNKNOWN_NWK
276 |
277 | if packet.dst.addr_mode == zigpy.types.AddrMode.Broadcast:
278 | long_addr = EUI64(
279 | [
280 | zigpy.types.uint8_t(b)
281 | for b in packet.dst.address.to_bytes(8, "little")
282 | ]
283 | )
284 | short_addr = packet.dst.address
285 | elif packet.dst.addr_mode == zigpy.types.AddrMode.Group:
286 | short_addr = packet.dst.address
287 | elif packet.dst.addr_mode == zigpy.types.AddrMode.IEEE:
288 | long_addr = EUI64(packet.dst.address)
289 | elif device is not None:
290 | long_addr = EUI64(device.ieee)
291 | short_addr = device.nwk
292 | else:
293 | raise zigpy.exceptions.DeliveryError(
294 | "Cannot send a packet to a device without a known IEEE address"
295 | )
296 |
297 | send_req = self._api.tx_explicit(
298 | long_addr,
299 | short_addr,
300 | packet.src_ep or 0,
301 | packet.dst_ep or 0,
302 | packet.cluster_id,
303 | packet.profile_id,
304 | packet.radius,
305 | tx_opts,
306 | packet.data.serialize(),
307 | )
308 |
309 | try:
310 | v = await asyncio.wait_for(send_req, timeout=TIMEOUT_TX_STATUS)
311 | except asyncio.TimeoutError:
312 | raise zigpy.exceptions.DeliveryError(
313 | "Timeout waiting for ACK", status=TXStatus.NETWORK_ACK_FAILURE
314 | )
315 |
316 | if v != TXStatus.SUCCESS:
317 | raise zigpy.exceptions.DeliveryError(
318 | f"Failed to deliver packet: {v!r}", status=v
319 | )
320 |
321 | @zigpy.util.retryable_request()
322 | def remote_at_command(
323 | self, nwk, cmd_name, *args, apply_changes=True, encryption=True
324 | ):
325 | """Execute AT command on another XBee module in the network."""
326 | LOGGER.debug("Remote AT%s command: %s", cmd_name, args)
327 | options = zigpy.types.uint8_t(0)
328 | if apply_changes:
329 | options |= 0x02
330 | if encryption:
331 | options |= 0x10
332 | dev = self.get_device(nwk=nwk)
333 | return self._api._remote_at_command(dev.ieee, nwk, options, cmd_name, *args)
334 |
335 | async def permit_ncp(self, time_s=60):
336 | """Permit join."""
337 | assert 0 <= time_s <= 254
338 | await self._api._at_command("NJ", time_s)
339 | await self._api._at_command("AC")
340 |
341 | async def permit_with_link_key(
342 | self, node: EUI64, link_key: zigpy.types.KeyData, time_s: int = 500, key_type=0
343 | ):
344 | """Permits a new device to join with the given IEEE and link key."""
345 | assert 0x1E <= time_s <= 0xFFFF
346 | await self._api._at_command("KT", time_s)
347 | reserved = 0xFFFE
348 | # Key type:
349 | # 0 = Pre-configured Link Key (KY command of the joining device)
350 | # 1 = Install Code With CRC (I? command of the joining device)
351 | await self._api.register_joining_device(node, reserved, key_type, link_key)
352 |
353 | def handle_modem_status(self, status):
354 | """Handle changed Modem Status of the device."""
355 | LOGGER.info("Modem status update: %s (%s)", status.name, status.value)
356 |
357 | def handle_rx(
358 | self, src_ieee, src_nwk, src_ep, dst_ep, cluster_id, profile_id, rxopts, data
359 | ):
360 | """Handle receipt of Zigbee data from the device."""
361 | src = zigpy.types.AddrModeAddress(
362 | addr_mode=zigpy.types.AddrMode.NWK, address=src_nwk
363 | )
364 |
365 | dst = zigpy.types.AddrModeAddress(
366 | addr_mode=zigpy.types.AddrMode.NWK, address=self.state.node_info.nwk
367 | )
368 |
369 | if src == dst:
370 | LOGGER.info("handle_rx self addressed")
371 |
372 | try:
373 | self._device.update_last_seen()
374 | except KeyError:
375 | pass
376 |
377 | self.packet_received(
378 | zigpy.types.ZigbeePacket(
379 | src=src,
380 | src_ep=src_ep,
381 | dst=dst,
382 | dst_ep=dst_ep,
383 | tsn=None,
384 | profile_id=profile_id,
385 | cluster_id=cluster_id,
386 | data=zigpy.types.SerializableBytes(data),
387 | )
388 | )
389 |
390 | def neighbors_updated(
391 | self, ieee: zigpy.types.EUI64, neighbors: list[zdo_t.Neighbor]
392 | ) -> None:
393 | """Neighbor update from Mgmt_Lqi_req."""
394 | for neighbor in neighbors:
395 | if neighbor.relationship == zdo_t.Neighbor.Relationship.Parent:
396 | device = self.get_device(ieee=ieee)
397 | device.radio_details(lqi=neighbor.lqi)
398 |
399 | elif neighbor.relationship == zdo_t.Neighbor.Relationship.Child:
400 | try:
401 | child_device = self.get_device(ieee=neighbor.ieee)
402 | child_device.radio_details(lqi=neighbor.lqi)
403 | except KeyError:
404 | LOGGER.warning("Unknown device %r", neighbor.ieee)
405 |
406 | def routes_updated(
407 | self, ieee: zigpy.types.EUI64, routes: list[zdo_t.Route]
408 | ) -> None:
409 | """Route update from Mgmt_Rtg_req."""
410 | self.create_task(
411 | self._routes_updated(ieee, routes), f"routes_updated-ieee={ieee}"
412 | )
413 |
414 | async def _routes_updated(
415 | self, ieee: zigpy.types.EUI64, routes: list[zdo_t.Route]
416 | ) -> None:
417 | """Get RSSI for adjacent routers on Route update from Mgmt_Rtg_req."""
418 | for route in routes:
419 | if (
420 | route.DstNWK == self.state.node_info.nwk
421 | and route.NextHop == self.state.node_info.nwk
422 | and route.RouteStatus == zdo_t.RouteStatus.Active
423 | ):
424 | device = self.get_device(ieee=ieee)
425 | rssi = await self._api._at_command("DB")
426 | device.radio_details(rssi=-rssi)
427 | break
428 |
429 |
430 | class XBeeCoordinator(zigpy.quirks.CustomDevice):
431 | """Zigpy Device representing Coordinator."""
432 |
433 | class XBeeGroup(zigpy.quirks.CustomCluster, Groups):
434 | """XBeeGroup custom cluster."""
435 |
436 | cluster_id = 0x0006
437 |
438 | class XBeeGroupResponse(zigpy.quirks.CustomCluster, Groups):
439 | """XBeeGroupResponse custom cluster."""
440 |
441 | cluster_id = 0x8006
442 | ep_attribute = "xbee_groups_response"
443 |
444 | client_commands = {
445 | **Groups.client_commands,
446 | 0x04: foundation.ZCLCommandDef(
447 | "remove_all_response",
448 | {"status": foundation.Status},
449 | direction=foundation.Direction.Client_to_Server,
450 | ),
451 | }
452 |
453 | def __init__(self, *args, **kwargs):
454 | """Initialize instance."""
455 |
456 | super().__init__(*args, **kwargs)
457 | self.node_desc = zdo_t.NodeDescriptor(
458 | logical_type=zdo_t.LogicalType.Coordinator,
459 | complex_descriptor_available=0,
460 | user_descriptor_available=0,
461 | reserved=0,
462 | aps_flags=0,
463 | frequency_band=zdo_t.NodeDescriptor.FrequencyBand.Freq2400MHz,
464 | mac_capability_flags=(
465 | zdo_t.NodeDescriptor.MACCapabilityFlags.AllocateAddress
466 | | zdo_t.NodeDescriptor.MACCapabilityFlags.RxOnWhenIdle
467 | | zdo_t.NodeDescriptor.MACCapabilityFlags.MainsPowered
468 | | zdo_t.NodeDescriptor.MACCapabilityFlags.FullFunctionDevice
469 | ),
470 | manufacturer_code=4126,
471 | maximum_buffer_size=82,
472 | maximum_incoming_transfer_size=255,
473 | server_mask=11264,
474 | maximum_outgoing_transfer_size=255,
475 | descriptor_capability_field=zdo_t.NodeDescriptor.DescriptorCapability.NONE,
476 | )
477 |
478 | replacement = {
479 | "manufacturer": "Digi",
480 | "model": "XBee",
481 | "endpoints": {
482 | XBEE_ENDPOINT_ID: {
483 | "device_type": 0x0050,
484 | "profile_id": 0xC105,
485 | "input_clusters": [XBeeGroup, XBeeGroupResponse],
486 | "output_clusters": [],
487 | }
488 | },
489 | }
490 |
--------------------------------------------------------------------------------