├── .coveragerc
├── .github
├── release-drafter.yml
└── workflows
│ ├── publish-to-pypi.yml
│ └── release-management.yml
├── .gitignore
├── .pre-commit-config.yaml
├── .travis.yml
├── COPYING
├── Contributors.md
├── LICENSE
├── MIGRATION.md
├── README.md
├── dev.sh
├── get_definitions.py
├── setup.cfg
├── setup.py
├── tdd.sh
├── test.py
├── tests
├── test_api.py
├── test_application.py
├── test_buffalo.py
├── test_types.py
└── test_uart.py
├── tox.ini
├── version.py
└── zigpy_cc
├── __init__.py
├── api.py
├── buffalo.py
├── config.py
├── const.py
├── definition.py
├── exception.py
├── ha.log
├── types.py
├── uart.py
├── zigbee
├── __init__.py
├── application.py
├── backup.py
├── common.py
├── nv_items.py
└── start_znp.py
└── zpi_object.py
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | source = zigpy_cc
3 |
--------------------------------------------------------------------------------
/.github/release-drafter.yml:
--------------------------------------------------------------------------------
1 | name-template: '$NEXT_PATCH_VERSION Release.'
2 | tag-template: '$NEXT_PATCH_VERSION'
3 | categories:
4 | - title: 'Breaking changes'
5 | labels:
6 | - 'breaking'
7 | - title: '🚀 Features'
8 | labels:
9 | - 'feature'
10 | - 'enhancement'
11 | - title: '🐛 Bug Fixes'
12 | labels:
13 | - 'fix'
14 | - 'bugfix'
15 | - 'bug'
16 | - title: '🧰 Maintenance'
17 | label: 'chore'
18 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
19 | template: |
20 | ## Changes
21 | $CHANGES
--------------------------------------------------------------------------------
/.github/workflows/publish-to-pypi.yml:
--------------------------------------------------------------------------------
1 | name: Publish distributions to PyPI and TestPyPI
2 | on:
3 | push:
4 | tags:
5 | - "*"
6 |
7 | jobs:
8 | build-and-publish:
9 | name: Build and publish distributions to PyPI and TestPyPI
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@master
13 | - name: Set up Python 3.7
14 | uses: actions/setup-python@v1
15 | with:
16 | version: 3.7
17 | - name: Install wheel
18 | run: >-
19 | pip install wheel
20 | - name: Update version
21 | run: >-
22 | python3 version.py ${{ github.ref }}
23 | - name: Build
24 | run: >-
25 | python3 setup.py sdist bdist_wheel
26 | - name: Publish distribution to PyPI
27 | uses: pypa/gh-action-pypi-publish@master
28 | with:
29 | password: ${{ secrets.PYPI_TOKEN }}
--------------------------------------------------------------------------------
/.github/workflows/release-management.yml:
--------------------------------------------------------------------------------
1 | name: Release Management
2 |
3 | on:
4 | push:
5 | # branches to consider in the event; optional, defaults to all
6 | branches:
7 | - master
8 |
9 | jobs:
10 | update_draft_release:
11 | runs-on: ubuntu-latest
12 | steps:
13 | # Drafts your next Release notes as Pull Requests are merged into "master"
14 | - uses: toolmantim/release-drafter@v5.2.0
15 | env:
16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
--------------------------------------------------------------------------------
/.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 |
72 | # Visual Studio Code
73 | .vscode
74 |
75 | # debug logs
76 | *.log
77 |
78 | # macOS stuff
79 | .DS_Store
80 | ._.DS_Store
81 |
82 | # project specific
83 | *.bak
84 | *.db
85 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/psf/black
3 | rev: 19.3b0
4 | hooks:
5 | - id: black
6 | args:
7 | - --safe
8 | - --quiet
9 | - repo: https://gitlab.com/pycqa/flake8
10 | rev: 3.7.8
11 | hooks:
12 | - id: flake8
13 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | matrix:
3 | fast_finish: true
4 | include:
5 | - python: "3.7"
6 | env: TOXENV=lint
7 | - python: "3.7"
8 | env: TOXENV=py37
9 | - python: "3.8"
10 | env: TOXENV=py38
11 | install: pip install -U setuptools tox coveralls
12 | script: tox
13 | after_success: coveralls
14 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | zigpy-cc
2 | Copyright (C) 2019 Balázs Sándor
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 | - [Balázs Sándor] (https://github.com/sanyatuning)
3 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/MIGRATION.md:
--------------------------------------------------------------------------------
1 | ## Migration to v0.5 (HA v0.115)
2 | Before version 0.5 we used fixed network options, now we are using network options from the config.
3 |
4 | If you want to upgrade from 0.4 to 0.5 you have two options:
5 | 1. Repair you devices
6 | 2. Add network options to config
7 |
8 | ```yaml
9 | zha:
10 | zigpy_config:
11 | network:
12 | channel: 11
13 | channels: [11]
14 | pan_id: 0x1A62
15 | extended_pan_id: "DD:DD:DD:DD:DD:DD:DD:DD"
16 | ```
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # zigpy-cc
2 |
3 | [](https://travis-ci.org/zigpy/zigpy-cc)
4 | [](https://coveralls.io/github/zigpy/zigpy-cc?branch=master)
5 |
6 | [zigpy-cc](https://github.com/zigpy/zigpy-cc) is a Python 3 library implemention to add support for Texas Instruments CC series of [Zigbee](https://www.zigbee.org) radio module chips hardware to the [zigpy](https://github.com/zigpy/) project. Including but possibly not limited to Texas Instruments CC253x, CC26x2R, and CC13x2 chips flashed with a custom Z-Stack coordinator firmware.
7 |
8 | The goal of this project is to add native support for inexpensive Texas Instruments CC chip based USB sticks in Home Assistant's built-in ZHA (Zigbee Home Automation) integration component (via the [zigpy](https://github.com/zigpy/) library), allowing Home Assistant with such hardware to nativly support direct control of compatible Zigbee devices such as Philips HUE, GE, Osram Lightify, Xiaomi/Aqara, IKEA Tradfri, Samsung SmartThings, and many more.
9 |
10 | - https://www.home-assistant.io/integrations/zha/
11 |
12 | zigpy-cc allows Zigpy to interact with Texas Instruments ZNP (Zigbee Network Processor) coordinator firmware via TI Z-Stack Monitor and Test(MT) APIs using an UART/serial interface.
13 |
14 | The zigpy-cc library itself initially began as a code port from the [zigbee-herdsman](https://github.com/Koenkk/zigbee-herdsman/tree/v0.12.24) project (version 0.12.24) for the [Zigbee2mqtt](https://www.zigbee2mqtt.io/) project by Koen Kanters (a.k.a. Koenkk GitHub). The zigbee-herdsman library itself in turn was originally a fork and rewrite of the [zigbee-shepherd](https://github.com/zigbeer/zigbee-shepherd) library by the [Zigbeer](https://github.com/zigbeer) project. Therefore, if the upstream code improvements or bug-fixes gets commited to the [zigbee-herdsman](https://github.com/Koenkk/zigbee-herdsman) library then it could, in theory, also be possible to downport some or many of those upstream code improvements to this zigpy-cc library for its benifit.
15 |
16 | ## Migration to v0.5 (HA v0.115)
17 | See: [Migration guide](./MIGRATION.md)
18 |
19 | ## WARNING!!! - Work in progress
20 | Disclaimer: This software is provided "AS IS", without warranty of any kind. The zigpy-cc project is under development as WIP (work in progress), it is not fully working yet.
21 |
22 | # Hardware requirement
23 | The zigpy-cc library has been tested by developers with Texas Instruments CC2531 and CC2652R based adapters/boards as reference hardware but it should in theory be possible to get it working with work most USB-adapters and GPIO-modules based on Texas Instruments CC Zigbee radio module chips hardware with Z-Stack Home 1.2.x or Z-Stack 3.x.x firmware. Note that unless you recieved your adapter pre-flashed with a compatible firmware you will also have to flash the chip a compatible Z-Stack coordinator firmware before you can use the hardware, please be sure to read the firmware requirement section further down below.
24 |
25 | ## Known working Zigbee radio modules from Texas Instruments
26 |
27 | - **Texas Instruments with Z-Stack Home 1.2.x firmware**
28 | - [CC2531 USB stick hardware flashed with Z-Stack Home 1.2.x firmware](https://www.zigbee2mqtt.io/information/supported_adapters)
29 | - [CC2530 + CC2591/CC2592 USB stick hardware flashed with Z-Stack Home 1.2.x firmware](https://www.zigbee2mqtt.io/information/supported_adapters)
30 | - [CC2538 + CC2592 dev board hardware flashed with Z-Stack Home 1.2.x firmware](https://www.zigbee2mqtt.io/information/supported_adapters)
31 |
32 | ## Experimental support for newer Zigbee radio modules
33 |
34 | - **Texas Instruments based radios with Z-Stack 3.x.x firmware**
35 | - [CC2652P/CC2652R/CC2652RB USB stick and dev board hardware flashed with Z-Stack 3.x.x firmware](https://www.zigbee2mqtt.io/information/supported_adapters)
36 | - [CC1352P/CC1352R USB stick and dev board hardware flashed with Z-Stack 3.x.x firmware](https://www.zigbee2mqtt.io/information/supported_adapters)
37 |
38 | ## Texas Instruments Chip Part Numbers
39 | Texas Instruments (TI) has quite a few different wireless MCU chips and they are all used/mentioned in open-source Zigbee world which can be daunting if you are just starting out. Here is a quick summary of part numbers and key features.
40 |
41 | ### Older generation TI chips
42 | - CC2530 = 2.4GHz Zigbee and IEEE 802.15.4 wireless MCU. 8051 core, has very little RAM. Needs expensive compiler license for official TI stack.
43 | - CC2531 = CC2530 with built-in USB. Used in the cheap "Zigbee sticks" sold everywhere.
44 | - CC2538 = CC2538 2.4GHz Zigbee and IEEE 802.15.4 wireless MCU. CC253x with a more powerful ARM Cortex-M3 CPU core, up to 32KB of RAM, and and up to 512KB on-chip flash. This is the only chip in the CC253x series that Texas Instruments has officially released Zigbee 3.0 (Z-Stack 3.0.x) firmware, however only as an option as it is still not as powerful a the newer generation of TI chips listed bellow.
45 |
46 | ### Newer generation TI chips
47 |
48 | #### 2.4GHz frequency only chips
49 | - CC2652R = 2.4GHz only wireless MCU for IEEE 802.15.4 multi-protocol (Zigbee, Bluetooth, Thread, IEEE 802.15.4g IPv6-enabled smart objects like 6LoWPAN, and proprietary systems). Cortex-M0 core for radio stack and Cortex-M4F core for application use, plenty of RAM. Free compiler option from TI.
50 | - CC2652RB = Pin compatible "Crystal-less" CC2652R, however not firmware compatible with CC2652R.
51 | - CC2652P = CC2652R with a built-in RF PA (Power Amplifier) for greatly improved range. Not pin or firmware compatible with CC2652R/CC2652RB.
52 |
53 | #### Multi frequency chips
54 | - CC1352R = Sub 1 GHz & 2.4 GHz wireless MCU. Essentially CC2652R with an extra sub-1GHz radio.
55 | - CC1352P = CC1352R with a built in RF PA (Power Amplifier) for greatly improved range.
56 |
57 | ### Auxiliary TI chips
58 | - CC2591 and CC2592 = 2.4 GHz range extenders. These are not wireless MCUs, just auxillary PA (Power Amplifier) and LNA (Low Noise Amplifier) in the same package to improve RF (Radio Frequency) range of any 2.4 GHz radio chip.
59 |
60 | ## Firmware requirement
61 | Firmware requirement is that they support Texas Instruments "Z-Stack Monitor and Test" APIs using an UART interface (serial communcation protocol), which they should do if they are flashed with custom Z-Stack "coordinator" for Zigbee Home Automation 1.2 (Z-Stack Home 1.2) or Zigbee 3.0 (Z-Stack 3.0.x or Z-Stack 3.x.0) firmware from the Zigbee2mqtt project.
62 |
63 | - https://github.com/Koenkk/Z-Stack-firmware/tree/master/coordinator
64 |
65 | The necessary hardware and equipment for flashing firmware and the device preparation process is best described by the [Zigbee2mqtt](https://www.zigbee2mqtt.io/) project whos community maintain and distribute a custom pre-compiled Z-Stack coordinator firmware (.hex files) for their [Zigbee-Heardsman](https://github.com/Koenkk/zigbee-herdsman/) libary which also makes it compatible with the zigpy-cc library.
66 |
67 | CC253x based USB adapters, modules and dev boards in general does not come with a bootloader from the factory so needs to first be hardware flashed with a pre-compiled Z-Stack coordinator firmware (.hex file) via a Texas Instruments CC Debugger or a DIY GPIO debug adapter using the official "SmartRF Flash-Programmer" (v1.1x) software from Texas Instruments, or comparative alternative metods and software. These older less powerful chips are only designed for Zigbee Home Automation 1.2 (Z-Stack Home 1.2) firmware as they are not really powerfull enough to run the newer Zigbee 3.0 (Z-Stack 3.0.x) firmware. It should be mentioned that there it is technically possible to run inofficial Zigbee 3.0 (Z-Stack 3.0.x) firmware releases for CC253x, but such newer firmware are generally not recommended on these older adapters if you want to achieve a stable Zigbee network with more than a few paired devices.
68 |
69 | CC13x2/CC13x2x and CC26x2/CC26x2x based USB adapters, modules and dev boards in general already come with a bootloader from the factory so can be software flashed with a pre-compiled Z-Stack coordinator firmware (.hex file) directly over USB using the official "SmartRF Flash-Programmer-2" (v1.8+) or "UniFlash" (6.x) from Texas Instruments, or comparative alternative metods and software. These newer more powerful chips only support newer Zigbee 3.0 (Z-Stack 3.0.x or Z-Stack 3.x.0) firmware.
70 |
71 | The [Zigbee2mqtt](https://www.zigbee2mqtt.io/) project has step-by-step intructions for both flashing with Texas Instruments official software as well as several alternative metods on how to initially flash their custom Z-Stack coordinator firmware on a new CC253x, CC13x2, CC26x2 and other Texas Instruments CCxxxx based USB adapters and development boards that comes or do not come with a bootloader.
72 |
73 | - https://www.zigbee2mqtt.io/information/supported_adapters.html
74 | - https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html
75 | - https://www.zigbee2mqtt.io/getting_started/flashing_the_cc2531.html
76 | - https://www.zigbee2mqtt.io/information/alternative_flashing_methods.html
77 |
78 | Note that the [Zigbee2mqtt](https://www.zigbee2mqtt.io/) project also have a FAQ and knowledgebase that can be useful for working with these Texas Instruments ZNP coordinator hardware adapters/equipment for their Z-Stack as well as lists Zigbee devices which should be supported.
79 |
80 | ## Port configuration
81 |
82 | - To configure __usb__ port path for your TI CC serial device, just specify the TTY (serial com) port, example : `/dev/ttyACM0`
83 | - Alternatively you could try to set just port to `auto` to enable automatic usb port discovery (not garanteed to work).
84 |
85 | Developers should note that Texas Instruments recommends different baud rates for UART interface of different TI CC chips.
86 | - CC2530 and CC2531 default recommended UART baud rate is 115200 baud.
87 | - CC2538 also supports flexible UART baud rate generation but only up to a maximum of 460800 baud.
88 | - CC13x2 and CC26x2 support flexible UART baud rate generation up to a maximum of 1.5 Mbps.
89 |
90 | # Toubleshooting
91 |
92 | For toubleshooting with Home Assistant, the general recommendation is to first only enable DEBUG logging for homeassistant.core and homeassistant.components.zha in Home Assistant, then look in the home-assistant.log file and try to get the Home Assistant community to exhausted their combined troubleshooting knowledge of the ZHA component before posting issue directly to a radio library like zigpy-cc.
93 |
94 | That is, begin with checking debug logs for Home Assistant core and the ZHA component first, (troubleshooting/debugging from the top down instead of from the bottom up), trying to getting help via Home Assistant community forum before moving on to posting debug logs to zigpy and zigpy-cc. This is to general suggestion to help filter away common problems and not flood the zigpy-cc developer(s) with to many logs.
95 |
96 | Please also try the very latest versions of zigpy and zigpy-cc, (see the section below about "Testing new releases"), and only if you still have the same issues with the latest versions then enable debug logging for zigpy and zigpy_cc in Home Assistant in addition to core and zha. Once enabled debug logging for all those libraries in Home Assistant you should try to reproduce the problem and then raise an issue in zigpy-cc repo with a copy of those logs.
97 |
98 | To enable debugging in Home Assistant to get debug logs, either update logger configuration section in configuration.yaml or call logger.set_default_level service with {"level": "debug"} data.
99 |
100 | Check logger component configuration where you want something in your Home Assistant configuration.yaml like this:
101 | ```
102 | logger:
103 | default: info
104 | logs:
105 | asyncio: debug
106 | homeassistant.core: debug
107 | homeassistant.components.zha: debug
108 | zigpy: debug
109 | zigpy_cc: debug
110 | ```
111 |
112 | # Testing new releases
113 |
114 | Testing a new release of the zigpy-cc library before it is released in Home Assistant.
115 |
116 | If you are using Supervised Home Assistant (formerly known as the Hassio/Hass.io distro):
117 | - Add https://github.com/home-assistant/hassio-addons-development as "add-on" repository
118 | - Install "Custom deps deployment" addon
119 | - Update config like:
120 | ```
121 | pypi:
122 | - zigpy-cc==0.2.3
123 | apk: []
124 | ```
125 | where 0.2.3 is the new version
126 | - Start the addon
127 |
128 | This version will persist even so you update HA core.
129 | You can remove custom deps with this config:
130 | ```
131 | pypi: []
132 | apk: []
133 | ```
134 |
135 | If you are instead using some custom python installation of Home Assistant then do this:
136 | - Activate your python virtual env
137 | - Update package with ``pip``
138 | ```
139 | pip install zigpy-cc==0.2.3
140 | ```
141 |
142 | # Releases via PyPI
143 |
144 | Tagged versions will also be released via PyPI
145 |
146 | - https://pypi.org/project/zigpy-cc/
147 | - https://pypi.org/project/zigpy-cc/#history
148 | - https://pypi.org/project/zigpy-cc/#files
149 |
150 | # External documentation and reference
151 |
152 | - http://www.ti.com/tool/LAUNCHXL-CC26X2R1
153 | - http://www.ti.com/tool/LAUNCHXL-CC1352P
154 |
155 | # How to contribute
156 |
157 | If you are looking to make a code or documentation contribution to this project we suggest that you follow the steps in these guides:
158 | - https://github.com/firstcontributions/first-contributions/blob/master/README.md
159 | - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md
160 |
161 | # Related projects
162 |
163 | ### Zigpy
164 | **[zigpy](https://github.com/zigpy/zigpy)** is a [Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee) integration project to implement the **[Zigbee Home Automation](https://www.zigbee.org/)** standard as a Python 3 library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee based devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g., motion and door sensors), sensors (e.g., temperature sensors), lightbulbs, switches, and fans. A working implementation of zigbe exist in **[Home Assistant](https://www.home-assistant.io)** (Python based open source home automation software) as part of its **[ZHA component](https://www.home-assistant.io/components/zha/)**
165 |
166 | ### ZHA Device Handlers
167 | ZHA deviation handling in Home Assistant relies on on the third-party [ZHA Device Handlers](https://github.com/dmulcahey/zha-device-handlers) project. Zigbee devices that deviate from or do not fully conform to the standard specifications set by the [Zigbee Alliance](https://www.zigbee.org) may require the development of custom [ZHA Device Handlers](https://github.com/dmulcahey/zha-device-handlers) (ZHA custom quirks handler implementation) to for all their functions to work properly with the ZHA component in Home Assistant. These ZHA Device Handlers for Home Assistant can thus be used to parse custom messages to and from non-compliant Zigbee devices. The custom quirks implementations for zigpy implemented as ZHA Device Handlers for Home Assistant are a similar concept to that of [Zigbee-Herdsman Converters / Zigbee-Shepherd Converters as used by Zigbee2mqtt](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html) as well as that of [Hub-connected Device Handlers for the SmartThings Classics platform](https://docs.smartthings.com/en/latest/device-type-developers-guide/), meaning they are each virtual representations of a physical device that expose additional functionality that is not provided out-of-the-box by the existing integration between these platforms.
168 |
169 | ### ZHA Map
170 | Home Assistant can build ZHA network topology map using the [zha-map](https://github.com/zha-ng/zha-map) project.
171 |
172 | ### zha-network-visualization-card
173 | [zha-network-visualization-card](https://github.com/dmulcahey/zha-network-visualization-card) is a custom Lovelace element for visualizing the ZHA Zigbee network in Home Assistant.
174 |
175 | ### ZHA Network Card
176 | [zha-network-card](https://github.com/dmulcahey/zha-network-card) is a custom Lovelace card that displays ZHA network and device information in Home Assistant
177 |
--------------------------------------------------------------------------------
/dev.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | export PYTHONPATH="`pwd`/../zigpy"
4 |
5 | nodemon test.py
6 |
--------------------------------------------------------------------------------
/get_definitions.py:
--------------------------------------------------------------------------------
1 | import fileinput
2 | import os
3 | import urllib.request
4 |
5 | from py._builtin import execfile
6 |
7 | url = (
8 | "https://raw.githubusercontent.com/Koenkk/zigbee-herdsman/"
9 | "v0.12.24/src/adapter/z-stack/znp/definition.ts"
10 | )
11 | target_path = "zigpy_cc/definition.py"
12 |
13 | print("Download file...")
14 | response = urllib.request.urlopen(url)
15 | data = response.read() # a `bytes` object
16 | text = data.decode("utf-8")
17 |
18 | ts_head = "\n".join(
19 | (
20 | "import {Subsystem, Type as CommandType} from '../unpi/constants';",
21 | "import ParameterType from './parameterType';",
22 | "import {MtCmd} from './tstype';",
23 | "",
24 | "const Definition: {",
25 | " [s: number]: MtCmd[];",
26 | "}",
27 | "",
28 | )
29 | )
30 |
31 | py_head = "\n".join(
32 | (
33 | '"""',
34 | "GENERATED BY get_definitions.py",
35 | '"""',
36 | "from zigpy_cc.types import Subsystem, CommandType, ParameterType",
37 | "",
38 | "name = 'name'",
39 | "ID = 'ID'",
40 | "request = 'request'",
41 | "response = 'response'",
42 | "parameterType = 'parameterType'",
43 | "type = 'type'",
44 | "",
45 | "Definition ",
46 | )
47 | )
48 |
49 | ts_export = "export default Definition;"
50 |
51 | print("Convert to python...")
52 | text = text.replace(ts_head, py_head)
53 | text = text.replace(ts_export, "")
54 | text = text.replace("//", "#")
55 | text = text.replace(" [Subsystem", " Subsystem")
56 | text = text.replace("]: [", ": [")
57 |
58 | with open(target_path, "w") as text_file:
59 | text_file.write(text)
60 |
61 | print("Check syntax...")
62 | execfile(target_path)
63 |
64 | print("Format with black...")
65 | os.system("black " + target_path)
66 |
67 | with fileinput.FileInput(target_path, inplace=True) as file:
68 | for line in file:
69 | line = line.replace("},],", "}],")
70 | line = line.replace("],},", "]},")
71 | print(line, end="")
72 |
73 | print("Check syntax...")
74 | execfile(target_path)
75 |
76 | print("Success")
77 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = .venv,.git,.tox,docs,venv,bin,lib,deps,build
3 | # To work with Black
4 | max-line-length = 88
5 | # W503: Line break occurred before a binary operator
6 | # E203: Whitespace before ':'
7 | # D202 No blank lines allowed after function docstring
8 | ignore =
9 | W503,
10 | E203,
11 | D202
12 |
13 | [isort]
14 | # https://github.com/timothycrosley/isort
15 | # https://github.com/timothycrosley/isort/wiki/isort-Settings
16 | # splits long import on multiple lines indented by 4 spaces
17 | multi_line_output = 3
18 | include_trailing_comma=True
19 | force_grid_wrap=0
20 | use_parentheses=True
21 | line_length=88
22 | indent = " "
23 | # by default isort don't check module indexes
24 | not_skip = __init__.py
25 | # will group `import x` and `from x import` of the same module.
26 | force_sort_within_sections = true
27 | sections = FUTURE,STDLIB,INBETWEENS,THIRDPARTY,FIRSTPARTY,LOCALFOLDER
28 | default_section = THIRDPARTY
29 | known_first_party = zigpy_cc,tests
30 | forced_separate = tests
31 | combine_as_imports = true
32 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """Setup module for zigpy-cc"""
2 |
3 | import os
4 |
5 | from setuptools import find_packages, setup
6 |
7 | import zigpy_cc
8 |
9 | this_directory = os.path.join(os.path.abspath(os.path.dirname(__file__)))
10 | with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
11 | long_description = f.read()
12 |
13 | setup(
14 | name="zigpy-cc",
15 | version=zigpy_cc.__version__,
16 | description="A library which communicates with "
17 | "Texas Instruments CC2531 radios for zigpy",
18 | long_description=long_description,
19 | long_description_content_type="text/markdown",
20 | url="http://github.com/zigpy/zigpy-cc",
21 | author="Balazs Sandor",
22 | author_email="sanyatuning@gmail.com",
23 | license="GPL-3.0",
24 | packages=find_packages(exclude=["*.tests"]),
25 | install_requires=["pyserial-asyncio", "zigpy>=0.23.1"],
26 | tests_require=["asynctest", "pytest", "pytest-asyncio"],
27 | )
28 |
--------------------------------------------------------------------------------
/tdd.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | export PYTHONPATH=`pwd`
4 |
5 | while true; do
6 |
7 | #echo -ne "\033c"
8 | py.test --color yes -x -vv $@
9 | #python test.py
10 | #python get_definitions.py
11 | echo "exit code: $?"
12 |
13 | inotifywait -rq -e close_write,moved_to,create *.py tests zigpy_cc
14 |
15 | done
--------------------------------------------------------------------------------
/test.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | import os
4 |
5 | import coloredlogs as coloredlogs
6 | import zigpy.config
7 | from zigpy.device import Device
8 |
9 | from zigpy_cc import config
10 | from zigpy_cc.zigbee import application
11 |
12 | fmt = "%(name)s %(levelname)s %(message)s"
13 | coloredlogs.install(level="DEBUG", fmt=fmt)
14 |
15 | APP_CONFIG = {
16 | zigpy.config.CONF_NWK: {
17 | zigpy.config.CONF_NWK_PAN_ID: 0x2A61,
18 | zigpy.config.CONF_NWK_EXTENDED_PAN_ID: "A0:B0:C0:D0:10:20:30:40",
19 | },
20 | config.CONF_DEVICE: {
21 | config.CONF_DEVICE_PATH: "auto",
22 | config.CONF_DEVICE_BAUDRATE: 115200,
23 | # config.CONF_FLOW_CONTROL: "hardware",
24 | config.CONF_FLOW_CONTROL: None,
25 | },
26 | config.CONF_DATABASE: "store.db",
27 | }
28 |
29 | LOGGER = logging.getLogger(__name__)
30 |
31 | # logging.basicConfig(level=logging.DEBUG)
32 | # logging.getLogger('zigpy_cc.uart').setLevel(logging.INFO)
33 | # logging.getLogger('zigpy_cc.api').setLevel(logging.INFO)
34 |
35 | loop = asyncio.get_event_loop()
36 |
37 |
38 | class TestApp:
39 | def device_joined(self, app, device: Device):
40 | async def init_dev():
41 | LOGGER.info("endpoints %s", device.endpoints)
42 |
43 | for key, endp in device.endpoints.items():
44 | LOGGER.info("endpoint %s", key)
45 | if hasattr(endp, "in_clusters"):
46 | LOGGER.info("in_clusters %s", endp.in_clusters)
47 | LOGGER.info("out_clusters %s", endp.out_clusters)
48 |
49 | await asyncio.sleep(2)
50 | await endp.out_clusters[8].bind()
51 |
52 | # res = await device.zdo.bind(endp.out_clusters[8])
53 | # LOGGER.warning(res)
54 | # res = await device.zdo.bind(endp.out_clusters[6])
55 | # LOGGER.warning(res)
56 | # res = await device.zdo.bind(endp.in_clusters[1])
57 | # LOGGER.warning(res)
58 |
59 | # power_cluster: PowerConfiguration = endp.in_clusters[1]
60 | # res = await power_cluster.configure_reporting(
61 | # 'battery_percentage_remaining', 3600, 62000, 0
62 | # )
63 | # LOGGER.warning(res)
64 |
65 | loop.create_task(init_dev())
66 |
67 |
68 | async def main():
69 | # noinspection PyUnresolvedReferences
70 | import zhaquirks # noqa: F401
71 |
72 | try:
73 | app = application.ControllerApplication(APP_CONFIG)
74 | except KeyError:
75 | LOGGER.error("DB error, removing DB...")
76 | await asyncio.sleep(1)
77 | os.remove(APP_CONFIG[config.CONF_DATABASE])
78 | app = application.ControllerApplication(APP_CONFIG)
79 |
80 | testapp = TestApp()
81 |
82 | app.add_context_listener(testapp)
83 |
84 | LOGGER.info("STARTUP")
85 | await app.startup(auto_form=False)
86 | await app.form_network()
87 |
88 | await app.permit_ncp()
89 |
90 |
91 | loop.run_until_complete(main())
92 | loop.run_forever()
93 | loop.close()
94 |
--------------------------------------------------------------------------------
/tests/test_api.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 |
3 | from asynctest import CoroutineMock, mock
4 | import pytest
5 | import serial
6 |
7 | from zigpy_cc import types as t, uart
8 | import zigpy_cc.api
9 | import zigpy_cc.config
10 | from zigpy_cc.definition import Definition
11 | import zigpy_cc.exception
12 | import zigpy_cc.uart
13 | from zigpy_cc.uart import UnpiFrame
14 | from zigpy_cc.zpi_object import ZpiObject
15 |
16 | DEVICE_CONFIG = zigpy_cc.config.SCHEMA_DEVICE(
17 | {zigpy_cc.config.CONF_DEVICE_PATH: "/dev/null"}
18 | )
19 |
20 |
21 | @pytest.fixture
22 | def api():
23 | api = zigpy_cc.api.API(DEVICE_CONFIG)
24 | api._uart = mock.MagicMock()
25 | return api
26 |
27 |
28 | def test_set_application(api):
29 | api.set_application(mock.sentinel.app)
30 | assert api._app == mock.sentinel.app
31 |
32 |
33 | @pytest.mark.asyncio
34 | async def test_connect(monkeypatch):
35 | api = zigpy_cc.api.API(DEVICE_CONFIG)
36 | monkeypatch.setattr(
37 | uart, "connect", mock.MagicMock(side_effect=asyncio.coroutine(mock.MagicMock()))
38 | )
39 | await api.connect()
40 |
41 |
42 | def test_close(api):
43 | api._uart.close = mock.MagicMock()
44 | uart = api._uart
45 | api.close()
46 | assert uart.close.call_count == 1
47 |
48 |
49 | @pytest.mark.skip("TODO")
50 | def test_commands():
51 | for cmd, cmd_opts in zigpy_cc.api.RX_COMMANDS.items():
52 | assert len(cmd_opts) == 2
53 | schema, solicited = cmd_opts
54 | assert isinstance(cmd, int) is True
55 | assert isinstance(schema, tuple) is True
56 | assert isinstance(solicited, bool)
57 |
58 | for cmd, schema in zigpy_cc.api.TX_COMMANDS.items():
59 | assert isinstance(cmd, int) is True
60 | assert isinstance(schema, tuple) is True
61 |
62 |
63 | @pytest.mark.skip("TODO")
64 | @pytest.mark.asyncio
65 | async def test_command(api, monkeypatch):
66 | def mock_api_frame():
67 | return mock.sentinel.api_frame_data
68 |
69 | def mock_obj(subsystem, command, payload):
70 | obj = mock.sentinel.zpi_object
71 | obj.to_unpi_frame = mock.MagicMock(side_effect=mock_api_frame)
72 | return obj
73 |
74 | api._create_obj = mock.MagicMock(side_effect=mock_obj)
75 | api._uart.send = mock.MagicMock()
76 |
77 | async def mock_fut():
78 | return mock.sentinel.cmd_result
79 |
80 | monkeypatch.setattr(asyncio, "Future", mock_fut)
81 |
82 | for subsystem, commands in Definition.items():
83 | for cmd in commands:
84 | ret = await api.request(subsystem, cmd["name"], mock.sentinel.cmd_data)
85 | assert ret is mock.sentinel.cmd_result
86 | # assert api._api_frame.call_count == 1
87 | # assert api._api_frame.call_args[0][0] == cmd
88 | # assert api._api_frame.call_args[0][1] == mock.sentinel.cmd_data
89 | assert api._uart.send.call_count == 1
90 | # assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
91 | # api._api_frame.reset_mock()
92 | api._uart.send.reset_mock()
93 |
94 |
95 | @pytest.mark.skip("TODO")
96 | @pytest.mark.asyncio
97 | async def test_command_timeout(api, monkeypatch):
98 | def mock_api_frame():
99 | return mock.sentinel.api_frame_data
100 |
101 | def mock_obj(subsystem, command, payload):
102 | obj = mock.sentinel.zpi_object
103 | obj.to_unpi_frame = mock.MagicMock(side_effect=mock_api_frame)
104 | return obj
105 |
106 | api._create_obj = mock.MagicMock(side_effect=mock_obj)
107 | api._uart.send = mock.MagicMock()
108 |
109 | monkeypatch.setattr(zigpy_cc.api, "COMMAND_TIMEOUT", 0.1)
110 |
111 | for subsystem, commands in Definition.items():
112 | for cmd in commands:
113 | with pytest.raises(asyncio.TimeoutError):
114 | await api.request(subsystem, cmd["name"], mock.sentinel.cmd_data)
115 | # assert api._api_frame.call_count == 1
116 | # assert api._api_frame.call_args[0][0] == cmd
117 | # assert api._api_frame.call_args[0][1] == mock.sentinel.cmd_data
118 | assert api._uart.send.call_count == 1
119 | # assert api._uart.send.call_args[0][0] == mock.sentinel.api_frame_data
120 | # api._api_frame.reset_mock()
121 | api._uart.send.reset_mock()
122 |
123 |
124 | @pytest.mark.skip("TODO")
125 | def test_api_frame(api):
126 | addr = t.DeconzAddressEndpoint()
127 | addr.address_mode = t.ADDRESS_MODE.NWK
128 | addr.address = t.uint8_t(0)
129 | addr.endpoint = t.uint8_t(0)
130 | for cmd, schema in zigpy_cc.api.TX_COMMANDS.items():
131 | if schema:
132 | args = [
133 | addr if isinstance(a(), t.DeconzAddressEndpoint) else a()
134 | for a in schema
135 | ]
136 | api._api_frame(cmd, *args)
137 | else:
138 | api._api_frame(cmd)
139 |
140 |
141 | @pytest.mark.skip("TODO")
142 | def test_data_received(api, monkeypatch):
143 | monkeypatch.setattr(
144 | t,
145 | "deserialize",
146 | mock.MagicMock(return_value=(mock.sentinel.deserialize_data, b"")),
147 | )
148 | my_handler = mock.MagicMock()
149 |
150 | data = UnpiFrame(3, 1, 2, b"\x02\x00\x02\x06\x03\x90\x154\x01\x02\x01\x00\x00\x00")
151 | setattr(api, "_handle_version", my_handler)
152 | api._awaiting[0] = mock.MagicMock()
153 | api.data_received(data)
154 | # assert t.deserialize.call_count == 1
155 | # assert t.deserialize.call_args[0][0] == payload
156 | assert my_handler.call_count == 1
157 | assert str(my_handler.call_args[0][0]) == str(
158 | ZpiObject(
159 | 3,
160 | 1,
161 | "version",
162 | 2,
163 | {
164 | "transportrev": 2,
165 | "product": 0,
166 | "majorrel": 2,
167 | "minorrel": 6,
168 | "maintrel": 3,
169 | "revision": 20190608,
170 | },
171 | [],
172 | )
173 | )
174 |
175 |
176 | """
177 | zigpy_cc.api DEBUG <-- SREQ ZDO nodeDescReq {'dstaddr': 53322, 'nwkaddrofinterest': 0}
178 | zigpy_cc.api DEBUG --> SRSP ZDO nodeDescReq {'status': 0}
179 | zigpy_cc.api DEBUG --> AREQ ZDO nodeDescRsp {'srcaddr': 53322, 'status': 128,
180 | 'nwkaddr': 0, 'logicaltype_cmplxdescavai_userdescavai': 0, 'apsflags_freqband': 0,
181 | 'maccapflags': 0, 'manufacturercode': 0, 'maxbuffersize': 0, 'maxintransfersize': 0,
182 | 'servermask': 0, 'maxouttransfersize': 0, 'descriptorcap': 0}
183 | """
184 |
185 |
186 | @pytest.mark.asyncio
187 | async def test_node_desc(api: zigpy_cc.api.API):
188 | api._uart.send = mock.MagicMock()
189 |
190 | fut = api.request(5, "nodeDescReq", {"dstaddr": 53322, "nwkaddrofinterest": 0})
191 | fut = asyncio.ensure_future(fut)
192 |
193 | async def asd():
194 | api.data_received(UnpiFrame(3, 5, 2, b"\x00"))
195 | pass
196 |
197 | await asyncio.wait([fut, asd()], timeout=0.1)
198 |
199 | assert api._uart.send.call_count == 1
200 | assert fut.done()
201 | assert "SRSP ZDO nodeDescReq tsn: None {'status': 0}" == str(fut.result())
202 |
203 |
204 | #
205 | # @pytest.mark.parametrize(
206 | # "protocol_ver, firmware_version, flags",
207 | # [
208 | # (0x010A, 0x123405DD, 0x01),
209 | # (0x010B, 0x123405DD, 0x04),
210 | # (0x010A, 0x123407DD, 0x01),
211 | # (0x010B, 0x123407DD, 0x01),
212 | # ],
213 | # )
214 | # @pytest.mark.asyncio
215 | # async def test_version(protocol_ver, firmware_version, flags, api):
216 | # api.read_parameter = mock.MagicMock()
217 | # api.read_parameter.side_effect = asyncio.coroutine(
218 | # mock.MagicMock(return_value=[protocol_ver])
219 | # )
220 | # api._command = mock.MagicMock()
221 | # api._command.side_effect = asyncio.coroutine(
222 | # mock.MagicMock(return_value=[firmware_version])
223 | # )
224 | # r = await api.version()
225 | # assert r == firmware_version
226 | # assert api._aps_data_ind_flags == flags
227 | #
228 | #
229 | # def test_handle_version(api):
230 | # api._handle_version([mock.sentinel.version])
231 |
232 |
233 | @pytest.mark.asyncio
234 | @mock.patch.object(zigpy_cc.uart, "connect")
235 | async def test_api_new(conn_mck):
236 | """Test new class method."""
237 | api = await zigpy_cc.api.API.new(mock.sentinel.application, DEVICE_CONFIG)
238 | assert isinstance(api, zigpy_cc.api.API)
239 | assert conn_mck.call_count == 1
240 | assert conn_mck.await_count == 1
241 |
242 |
243 | @pytest.mark.asyncio
244 | @mock.patch.object(zigpy_cc.api.API, "version", new_callable=CoroutineMock)
245 | @mock.patch.object(uart, "connect")
246 | async def test_probe_success(mock_connect, mock_version):
247 | """Test device probing."""
248 |
249 | res = await zigpy_cc.api.API.probe(DEVICE_CONFIG)
250 | assert res is True
251 | assert mock_connect.call_count == 1
252 | assert mock_connect.await_count == 1
253 | assert mock_connect.call_args[0][0] == DEVICE_CONFIG
254 | assert mock_version.call_count == 1
255 | assert mock_connect.return_value.close.call_count == 1
256 |
257 |
258 | @pytest.mark.asyncio
259 | @mock.patch.object(zigpy_cc.api.API, "version", side_effect=asyncio.TimeoutError)
260 | @mock.patch.object(uart, "connect")
261 | @pytest.mark.parametrize("exception", (asyncio.TimeoutError, serial.SerialException))
262 | async def test_probe_fail(mock_connect, mock_version, exception):
263 | """Test device probing fails."""
264 |
265 | mock_version.side_effect = exception
266 | mock_connect.reset_mock()
267 | mock_version.reset_mock()
268 | res = await zigpy_cc.api.API.probe(DEVICE_CONFIG)
269 | assert res is False
270 | assert mock_connect.call_count == 1
271 | assert mock_connect.await_count == 1
272 | assert mock_connect.call_args[0][0] == DEVICE_CONFIG
273 | assert mock_version.call_count == 1
274 | assert mock_connect.return_value.close.call_count == 1
275 |
--------------------------------------------------------------------------------
/tests/test_application.py:
--------------------------------------------------------------------------------
1 | # flake8: noqa: E501
2 | import asyncio
3 | from unittest import mock
4 |
5 | import pytest
6 | from zigpy.types import EUI64, Group, BroadcastAddress
7 | import zigpy.zdo.types as zdo_t
8 | from zigpy.zcl.clusters.general import Groups
9 |
10 | from zigpy_cc import types as t
11 | from zigpy_cc.api import API
12 | import zigpy_cc.config as config
13 | import zigpy_cc.zigbee.application as application
14 | from zigpy_cc.zpi_object import ZpiObject
15 |
16 | APP_CONFIG = {
17 | config.CONF_DEVICE: {
18 | config.CONF_DEVICE_PATH: "/dev/null",
19 | config.CONF_DEVICE_BAUDRATE: 115200,
20 | },
21 | config.CONF_DATABASE: None,
22 | }
23 |
24 |
25 | @pytest.fixture
26 | def app():
27 | app = application.ControllerApplication(APP_CONFIG)
28 | app._api = API(APP_CONFIG[config.CONF_DEVICE])
29 | app._api.set_application(app)
30 | app._semaphore = asyncio.Semaphore()
31 | return app
32 |
33 |
34 | @pytest.fixture
35 | def ieee():
36 | return EUI64.deserialize(b"\x00\x01\x02\x03\x04\x05\x06\x07")[0]
37 |
38 |
39 | @pytest.fixture
40 | def nwk():
41 | return t.uint16_t(0x0100)
42 |
43 |
44 | @pytest.fixture
45 | def addr_ieee(ieee):
46 | addr = t.Address()
47 | addr.address_mode = t.ADDRESS_MODE.IEEE
48 | addr.address = ieee
49 | return addr
50 |
51 |
52 | @pytest.fixture
53 | def addr_nwk(nwk):
54 | addr = t.Address()
55 | addr.address_mode = t.ADDRESS_MODE.NWK
56 | addr.address = nwk
57 | return addr
58 |
59 |
60 | @pytest.fixture
61 | def addr_nwk_and_ieee(nwk, ieee):
62 | addr = t.Address()
63 | addr.address_mode = t.ADDRESS_MODE.NWK_AND_IEEE
64 | addr.address = nwk
65 | addr.ieee = ieee
66 | return addr
67 |
68 |
69 | def test_join(app):
70 | payload = {"nwkaddr": 27441, "extaddr": "0x07a3c302008d1500", "parentaddr": 0}
71 | obj = ZpiObject(2, 5, "tcDeviceInd", 202, payload, [])
72 | app.handle_znp(obj)
73 |
74 | print(app.devices)
75 |
76 | payload = {
77 | "groupid": 0,
78 | "clusterid": 6,
79 | "srcaddr": 27441,
80 | "srcendpoint": 1,
81 | "dstendpoint": 1,
82 | "wasbroadcast": 0,
83 | "linkquality": 136,
84 | "securityuse": 0,
85 | "timestamp": 15458350,
86 | "transseqnumber": 0,
87 | "len": 7,
88 | "data": bytearray(b"\x18\x0c\n\x00\x00\x10\x00"),
89 | }
90 | obj = ZpiObject(2, 4, "incomingMsg", 129, payload, [])
91 | app.handle_znp(obj)
92 |
93 |
94 | """
95 | DEBUG:zigpy_cc.api:--> AREQ ZDO tcDeviceInd {'nwkaddr': 19542, 'extaddr': '0x07a3c302008d1500', 'parentaddr': 0}
96 | INFO:zigpy_cc.zigbee.application:New device joined: 0x4c56, 32:30:33:63:33:61:37:30
97 | INFO:zigpy.application:Device 0x4c56 (32:30:33:63:33:61:37:30) joined the network
98 |
99 | INFO:zigpy.device:[0x4c56] Requesting 'Node Descriptor'
100 | Tries remaining: 2
101 | DEBUG:zigpy.device:[0x4c56] Extending timeout for 0x01 request
102 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 1 under 2 request id, data: b'01564c'
103 | profile 0
104 | cluster ZDOCmd.Node_Desc_req
105 | src_ep 0
106 | dst_ep 0
107 | WARNING:zigpy.device:[0x4c56] Requesting Node Descriptor failed: 'destination'
108 |
109 | INFO:zigpy.device:[0x4c56] Discovering endpoints
110 | Tries remaining: 3
111 | DEBUG:zigpy.device:[0x4c56] Extending timeout for 0x03 request
112 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 3 under 4 request id, data: b'03564c'
113 | profile 0
114 | cluster ZDOCmd.Active_EP_req
115 | src_ep 0
116 | dst_ep 0
117 |
118 | INFO:zigpy.device:[0xd04a] Requesting 'Node Descriptor'
119 | Tries remaining: 2
120 | DEBUG:zigpy.device:[0xd04a] Extending timeout for 0x05 request
121 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 5 under 6 request id, data: b'054ad0'
122 | WARNING:zigpy.device:[0xd04a] Requesting Node Descriptor failed: 'API' object has no attribute 'aps_data_request'
123 | INFO:zigpy.device:[0xd04a] Discovering endpoints
124 | Tries remaining: 3
125 | DEBUG:zigpy.device:[0xd04a] Extending timeout for 0x07 request
126 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 7 under 8 request id, data: b'074ad0'
127 | ERROR:zigpy.device:Failed ZDO request during device initialization: 'API' object has no attribute 'aps_data_request'
128 |
129 | INFO:zigpy.device:[0xc00c] Requesting 'Node Descriptor'
130 | Tries remaining: 2
131 | DEBUG:zigpy.device:[0xc00c] Extending timeout for 0x09 request
132 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 9 under 10 request id, data: b'090cc0'
133 | WARNING:zigpy.device:[0xc00c] Requesting Node Descriptor failed: 'API' object has no attribute 'aps_data_request'
134 | INFO:zigpy.device:[0xc00c] Discovering endpoints
135 | Tries remaining: 3
136 | DEBUG:zigpy.device:[0xc00c] Extending timeout for 0x0b request
137 | DEBUG:zigpy_cc.zigbee.application:Sending Zigbee request with tsn 11 under 12 request id, data: b'0b0cc0'
138 | ERROR:zigpy.device:Failed ZDO request during device initialization: 'API' object has no attribute 'aps_data_request'
139 | """
140 |
141 |
142 | async def device_annce(app: application.ControllerApplication):
143 | # payload = {'nwkaddr': 27441, 'extaddr': '0x07a3c302008d1500', 'parentaddr': 0}
144 | # obj = ZpiObject(2, 5, 'tcDeviceInd', 202, payload, [])
145 |
146 | payload = {
147 | "srcaddr": 53322,
148 | "nwkaddr": 53322,
149 | "ieeeaddr": 0x41E54B02008D1500 .to_bytes(8, "little"),
150 | "capabilities": 132,
151 | }
152 | obj = ZpiObject(2, 5, "endDeviceAnnceInd", 193, payload, [])
153 |
154 | app.handle_znp(obj)
155 |
156 |
157 | @pytest.mark.asyncio
158 | async def test_request(app: application.ControllerApplication):
159 | await device_annce(app)
160 | device = app.get_device(nwk=53322)
161 |
162 | fut = asyncio.Future()
163 | fut.set_result(None)
164 | app._api.request_raw = mock.MagicMock(return_value=fut)
165 |
166 | res = await app.request(
167 | device, 0, zdo_t.ZDOCmd.Node_Desc_req, 0, 0, 1, b"\x01\xa2\x2e"
168 | )
169 |
170 | assert len(app._api._waiters) == 1
171 | assert (
172 | "SREQ ZDO nodeDescReq tsn: 1 {'dstaddr': 0xD04A, 'nwkaddrofinterest': 0x2EA2}"
173 | == str(app._api.request_raw.call_args[0][0])
174 | )
175 | assert res == (0, "message send success")
176 |
177 |
178 | @pytest.mark.asyncio
179 | async def test_mrequest(app: application.ControllerApplication):
180 | fut = asyncio.Future()
181 | fut.set_result(None)
182 | app._api.request_raw = mock.MagicMock(return_value=fut)
183 |
184 | # multicast (0x0002, 260, 6, 1, 39, b"\x01'\x00", 0, 3)
185 | res = await app.mrequest(Group(2), 260, Groups.cluster_id, 1, 39, b"\x01'\x00")
186 |
187 | assert 1 == len(app._api._waiters)
188 | assert (
189 | "SREQ AF dataRequestExt tsn: 39 {'dstaddrmode': , "
190 | "'dstaddr': 0x0002, 'destendpoint': 255, 'dstpanid': 0, "
191 | "'srcendpoint': 1, 'clusterid': 4, 'transid': 39, 'options': 0, 'radius': 30, 'len': 3, "
192 | "'data': b\"\\x01'\\x00\"}" == str(app._api.request_raw.call_args[0][0])
193 | )
194 | assert (0, "message send success") == res
195 |
196 |
197 | @pytest.mark.asyncio
198 | async def test_broadcast(app: application.ControllerApplication):
199 | fut = asyncio.Future()
200 | fut.set_result(None)
201 | app._api.request_raw = mock.MagicMock(return_value=fut)
202 |
203 | # broadcast (0, 54, 0, 0, 0, 0, 45, b'-<\x00', )
204 | res = await app.broadcast(
205 | 0, 54, 0, 0, 0, 0, 45, b"-<\x00", BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR
206 | )
207 |
208 | assert 0 == len(app._api._waiters)
209 | assert (
210 | "SREQ ZDO mgmtPermitJoinReq tsn: 45 {'addrmode': , "
211 | "'dstaddr': 0xFFFC, 'duration': 60, 'tcsignificance': 0}"
212 | == str(app._api.request_raw.call_args[0][0])
213 | )
214 | assert (0, "broadcast send success") == res
215 |
216 |
217 | """
218 | zigpy_cc.api DEBUG <-- SREQ ZDO nodeDescReq {'dstaddr': 53322, 'nwkaddrofinterest': 0}
219 | zigpy_cc.api DEBUG --> SRSP ZDO nodeDescReq {'status': 0}
220 | zigpy_cc.api DEBUG --> AREQ ZDO nodeDescRsp {'srcaddr': 53322, 'status': 128, 'nwkaddr': 0,
221 | 'logicaltype_cmplxdescavai_userdescavai': 0, 'apsflags_freqband': 0, 'maccapflags': 0, 'manufacturercode': 0,
222 | 'maxbuffersize': 0, 'maxintransfersize': 0, 'servermask': 0, 'maxouttransfersize': 0, 'descriptorcap': 0}
223 | """
224 |
225 |
226 | @pytest.mark.asyncio
227 | async def test_get_node_descriptor(app: application.ControllerApplication):
228 | await device_annce(app)
229 | device = app.get_device(nwk=53322)
230 |
231 | fut = asyncio.Future()
232 | fut.set_result([0, "message send success"])
233 | app._api.request_raw = mock.MagicMock(return_value=fut)
234 |
235 | payload = {
236 | "srcaddr": 53322,
237 | "status": 0,
238 | "nwkaddr": 0,
239 | "logicaltype_cmplxdescavai_userdescavai": 0,
240 | "apsflags_freqband": 0,
241 | "maccapflags": 0,
242 | "manufacturercode": 1234,
243 | "maxbuffersize": 0,
244 | "maxintransfersize": 0,
245 | "servermask": 0,
246 | "maxouttransfersize": 0,
247 | "descriptorcap": 0,
248 | }
249 | obj = ZpiObject.from_command(5, "nodeDescRsp", payload)
250 | frame = obj.to_unpi_frame()
251 |
252 | async def nested():
253 | await asyncio.sleep(0)
254 | app._api.data_received(frame)
255 |
256 | await asyncio.wait([device.get_node_descriptor(), nested()], timeout=0.2)
257 |
258 | assert isinstance(device.node_desc, zdo_t.NodeDescriptor)
259 | assert 1234 == device.node_desc.manufacturer_code
260 |
261 |
262 | @pytest.mark.asyncio
263 | async def test_read_attributes(app: application.ControllerApplication):
264 | await device_annce(app)
265 | device = app.get_device(nwk=53322)
266 |
267 | # res = await app.request(device, 260, 0, 1, 1, 1, b'\x00\x0b\x00\x04\x00\x05\x00')
268 | #
269 | # assert res == []
270 |
271 |
272 | # def _test_rx(app, addr_ieee, addr_nwk, device, data):
273 | # app.get_device = mock.MagicMock(return_value=device)
274 | # app.devices = (EUI64(addr_ieee.address),)
275 | #
276 | # app.handle_rx(
277 | # addr_nwk,
278 | # mock.sentinel.src_ep,
279 | # mock.sentinel.dst_ep,
280 | # mock.sentinel.profile_id,
281 | # mock.sentinel.cluster_id,
282 | # data,
283 | # mock.sentinel.lqi,
284 | # mock.sentinel.rssi,
285 | # )
286 | #
287 | #
288 | # def test_znp(app, addr_ieee, addr_nwk):
289 | # device = mock.MagicMock()
290 | # app.handle_message = mock.MagicMock()
291 | # _test_rx(app, addr_ieee, addr_nwk, device, mock.sentinel.args)
292 | # assert app.handle_message.call_count == 1
293 | # assert app.handle_message.call_args == (
294 | # (
295 | # device,
296 | # mock.sentinel.profile_id,
297 | # mock.sentinel.cluster_id,
298 | # mock.sentinel.src_ep,
299 | # mock.sentinel.dst_ep,
300 | # mock.sentinel.args,
301 | # ),
302 | # )
303 | #
304 | #
305 | # def test_rx_ieee(app, addr_ieee, addr_nwk):
306 | # device = mock.MagicMock()
307 | # app.handle_message = mock.MagicMock()
308 | # _test_rx(app, addr_ieee, addr_ieee, device, mock.sentinel.args)
309 | # assert app.handle_message.call_count == 1
310 | # assert app.handle_message.call_args == (
311 | # (
312 | # device,
313 | # mock.sentinel.profile_id,
314 | # mock.sentinel.cluster_id,
315 | # mock.sentinel.src_ep,
316 | # mock.sentinel.dst_ep,
317 | # mock.sentinel.args,
318 | # ),
319 | # )
320 | #
321 | #
322 | # def test_rx_nwk_ieee(app, addr_ieee, addr_nwk_and_ieee):
323 | # device = mock.MagicMock()
324 | # app.handle_message = mock.MagicMock()
325 | # _test_rx(app, addr_ieee, addr_nwk_and_ieee, device, mock.sentinel.args)
326 | # assert app.handle_message.call_count == 1
327 | # assert app.handle_message.call_args == (
328 | # (
329 | # device,
330 | # mock.sentinel.profile_id,
331 | # mock.sentinel.cluster_id,
332 | # mock.sentinel.src_ep,
333 | # mock.sentinel.dst_ep,
334 | # mock.sentinel.args,
335 | # ),
336 | # )
337 | #
338 | #
339 | # def test_rx_wrong_addr_mode(app, addr_ieee, addr_nwk, caplog):
340 | # device = mock.MagicMock()
341 | # app.handle_message = mock.MagicMock()
342 | # app.get_device = mock.MagicMock(return_value=device)
343 | #
344 | # app.devices = (EUI64(addr_ieee.address),)
345 | #
346 | # with pytest.raises(Exception): # TODO: don't use broad exceptions
347 | # addr_nwk.address_mode = 0x22
348 | # app.handle_rx(
349 | # addr_nwk,
350 | # mock.sentinel.src_ep,
351 | # mock.sentinel.dst_ep,
352 | # mock.sentinel.profile_id,
353 | # mock.sentinel.cluster_id,
354 | # b"",
355 | # mock.sentinel.lqi,
356 | # mock.sentinel.rssi,
357 | # )
358 | #
359 | # assert app.handle_message.call_count == 0
360 | #
361 | #
362 | # def test_rx_unknown_device(app, addr_ieee, addr_nwk, caplog):
363 | # app.handle_message = mock.MagicMock()
364 | #
365 | # caplog.set_level(logging.DEBUG)
366 | # app.handle_rx(
367 | # addr_nwk,
368 | # mock.sentinel.src_ep,
369 | # mock.sentinel.dst_ep,
370 | # mock.sentinel.profile_id,
371 | # mock.sentinel.cluster_id,
372 | # b"",
373 | # mock.sentinel.lqi,
374 | # mock.sentinel.rssi,
375 | # )
376 | #
377 | # assert "Received frame from unknown device" in caplog.text
378 | # assert app.handle_message.call_count == 0
379 | #
380 | #
381 | # # @pytest.mark.asyncio
382 | # # async def test_form_network(app):
383 | # # app._api.change_network_state = mock.MagicMock(
384 | # # side_effect=asyncio.coroutine(mock.MagicMock())
385 | # # )
386 | # # app._api.device_state = mock.MagicMock(
387 | # # side_effect=asyncio.coroutine(mock.MagicMock())
388 | # # )
389 | # #
390 | # # app._api.network_state = 2
391 | # # await app.form_network()
392 | # # assert app._api.device_state.call_count == 0
393 | # #
394 | # # app._api.network_state = 0
395 | # # application.CHANGE_NETWORK_WAIT = 0.001
396 | # # with pytest.raises(Exception):
397 | # # await app.form_network()
398 | # # assert app._api.device_state.call_count == 10
399 | #
400 | #
401 | # @pytest.mark.parametrize(
402 | # "protocol_ver, watchdog_cc", [(0x0107, False), (0x0108, True), (0x010B, True)]
403 | # )
404 | # @pytest.mark.asyncio
405 | # async def test_startup(protocol_ver, watchdog_cc, app, monkeypatch, version=0):
406 | # async def _version():
407 | # app._api._proto_ver = protocol_ver
408 | # return [version]
409 | #
410 | # app._reset_watchdog = mock.MagicMock(
411 | # side_effect=asyncio.coroutine(mock.MagicMock())
412 | # )
413 | # app.form_network = mock.MagicMock(side_effect=asyncio.coroutine(mock.MagicMock()))
414 | # app._api._command = mock.MagicMock(side_effect=asyncio.coroutine(mock.MagicMock()))
415 | # app._api.read_parameter = mock.MagicMock(
416 | # side_effect=asyncio.coroutine(mock.MagicMock(return_value=[[0]]))
417 | # )
418 | # app._api.version = mock.MagicMock(side_effect=_version)
419 | # app._api.write_parameter = mock.MagicMock(
420 | # side_effect=asyncio.coroutine(mock.MagicMock())
421 | # )
422 | #
423 | # new_mock = mock.MagicMock(side_effect=asyncio.coroutine(mock.MagicMock()))
424 | # monkeypatch.setattr(application.ConBeeDevice, "new", new_mock)
425 | # await app.startup(auto_form=False)
426 | # assert app.form_network.call_count == 0
427 | # assert app._reset_watchdog.call_count == watchdog_cc
428 | # await app.startup(auto_form=True)
429 | # assert app.form_network.call_count == 1
430 | #
431 | #
432 | # @pytest.mark.asyncio
433 | # async def test_permit(app, nwk):
434 | # app._api.write_parameter = mock.MagicMock(
435 | # side_effect=asyncio.coroutine(mock.MagicMock())
436 | # )
437 | # time_s = 30
438 | # await app.permit_ncp(time_s)
439 | # assert app._api.write_parameter.call_count == 1
440 | # assert app._api.write_parameter.call_args_list[0][0][1] == time_s
441 | #
442 | #
443 | # async def _test_request(app, send_success=True, aps_data_error=False, **kwargs):
444 | # seq = 123
445 | #
446 | # async def req_mock(req_id, dst_addr_ep, profile, cluster, src_ep, data):
447 | # if aps_data_error:
448 | # raise zigpy_cc.exception.CommandError(1, "Command Error")
449 | # if send_success:
450 | # app._pending[req_id].result.set_result(0)
451 | # else:
452 | # app._pending[req_id].result.set_result(1)
453 | #
454 | # app._api.aps_data_request = mock.MagicMock(side_effect=req_mock)
455 | # device = zigpy.device.Device(app, mock.sentinel.ieee, 0x1122)
456 | # app.get_device = mock.MagicMock(return_value=device)
457 | #
458 | # return await app.request(device, 0x0260, 1, 2, 3, seq, b"\x01\x02\x03", **kwargs)
459 | #
460 | #
461 | # @pytest.mark.asyncio
462 | # async def test_request_send_success(app):
463 | # req_id = mock.sentinel.req_id
464 | # app.get_sequence = mock.MagicMock(return_value=req_id)
465 | # r = await _test_request(app, True)
466 | # assert r[0] == 0
467 | #
468 | # r = await _test_request(app, True, use_ieee=True)
469 | # assert r[0] == 0
470 | #
471 | #
472 | # @pytest.mark.asyncio
473 | # async def test_request_send_fail(app):
474 | # req_id = mock.sentinel.req_id
475 | # app.get_sequence = mock.MagicMock(return_value=req_id)
476 | # r = await _test_request(app, False)
477 | # assert r[0] != 0
478 | #
479 | #
480 | # @pytest.mark.asyncio
481 | # async def test_request_send_aps_data_error(app):
482 | # req_id = mock.sentinel.req_id
483 | # app.get_sequence = mock.MagicMock(return_value=req_id)
484 | # r = await _test_request(app, False, aps_data_error=True)
485 | # assert r[0] != 0
486 | #
487 | #
488 | # async def _test_broadcast(app, send_success=True, aps_data_error=False, **kwargs):
489 | # seq = mock.sentinel.req_id
490 | #
491 | # async def req_mock(req_id, dst_addr_ep, profile, cluster, src_ep, data):
492 | # if aps_data_error:
493 | # raise zigpy_cc.exception.CommandError(1, "Command Error")
494 | # if send_success:
495 | # app._pending[req_id].result.set_result(0)
496 | # else:
497 | # app._pending[req_id].result.set_result(1)
498 | #
499 | # app._api.aps_data_request = mock.MagicMock(side_effect=req_mock)
500 | # app.get_device = mock.MagicMock(spec_set=zigpy.device.Device)
501 | #
502 | # r = await app.broadcast(
503 | # mock.sentinel.profile,
504 | # mock.sentinel.cluster,
505 | # 2,
506 | # mock.sentinel.dst_ep,
507 | # mock.sentinel.grp_id,
508 | # mock.sentinel.radius,
509 | # seq,
510 | # b"\x01\x02\x03",
511 | # **kwargs
512 | # )
513 | # assert app._api.aps_data_request.call_count == 1
514 | # assert app._api.aps_data_request.call_args[0][0] is seq
515 | # assert app._api.aps_data_request.call_args[0][2] is mock.sentinel.profile
516 | # assert app._api.aps_data_request.call_args[0][3] is mock.sentinel.cluster
517 | # assert app._api.aps_data_request.call_args[0][5] == b"\x01\x02\x03"
518 | # return r
519 | #
520 | #
521 | # @pytest.mark.asyncio
522 | # async def test_broadcast_send_success(app):
523 | # req_id = mock.sentinel.req_id
524 | # app.get_sequence = mock.MagicMock(return_value=req_id)
525 | # r = await _test_broadcast(app, True)
526 | # assert r[0] == 0
527 | #
528 | #
529 | # @pytest.mark.asyncio
530 | # async def test_broadcast_send_fail(app):
531 | # req_id = mock.sentinel.req_id
532 | # app.get_sequence = mock.MagicMock(return_value=req_id)
533 | # r = await _test_broadcast(app, False)
534 | # assert r[0] != 0
535 | #
536 | #
537 | # @pytest.mark.asyncio
538 | # async def test_broadcast_send_aps_data_error(app):
539 | # req_id = mock.sentinel.req_id
540 | # app.get_sequence = mock.MagicMock(return_value=req_id)
541 | # r = await _test_broadcast(app, False, aps_data_error=True)
542 | # assert r[0] != 0
543 | #
544 | #
545 | # def _handle_reply(app, tsn):
546 | # app.handle_message = mock.MagicMock()
547 | # return app._handle_reply(
548 | # mock.sentinel.device,
549 | # mock.sentinel.profile,
550 | # mock.sentinel.cluster,
551 | # mock.sentinel.src_ep,
552 | # mock.sentinel.dst_ep,
553 | # tsn,
554 | # mock.sentinel.command_id,
555 | # mock.sentinel.args,
556 | # )
557 | #
558 | #
559 | # @pytest.mark.asyncio
560 | # async def test_shutdown(app):
561 | # app._api.close = mock.MagicMock()
562 | # await app.shutdown()
563 | # assert app._api.close.call_count == 1
564 | #
565 | #
566 | # def test_rx_device_annce(app, addr_ieee, addr_nwk):
567 | # dst_ep = 0
568 | # cluster_id = zdo_t.ZDOCmd.Device_annce
569 | # device = mock.MagicMock()
570 | # device.status = zigpy.device.Status.NEW
571 | # app.get_device = mock.MagicMock(return_value=device)
572 | #
573 | # app.handle_join = mock.MagicMock()
574 | # app._handle_reply = mock.MagicMock()
575 | # app.handle_message = mock.MagicMock()
576 | #
577 | # data = t.uint8_t(0xAA).serialize()
578 | # data += addr_nwk.address.serialize()
579 | # data += addr_ieee.address.serialize()
580 | # data += t.uint8_t(0x8E).serialize()
581 | #
582 | # app.handle_rx(
583 | # addr_nwk,
584 | # mock.sentinel.src_ep,
585 | # dst_ep,
586 | # mock.sentinel.profile_id,
587 | # cluster_id,
588 | # data,
589 | # mock.sentinel.lqi,
590 | # mock.sentinel.rssi,
591 | # )
592 | #
593 | # assert app.handle_message.call_count == 1
594 | # assert app.handle_join.call_count == 1
595 | # assert app.handle_join.call_args[0][0] == addr_nwk.address
596 | # assert app.handle_join.call_args[0][1] == addr_ieee.address
597 | # assert app.handle_join.call_args[0][2] == 0
598 | #
599 | #
600 | # @pytest.mark.asyncio
601 | # async def test_conbee_dev_add_to_group(app, nwk):
602 | # group = mock.MagicMock()
603 | # app._groups = mock.MagicMock()
604 | # app._groups.add_group.return_value = group
605 | #
606 | # conbee = application.ConBeeDevice(app, mock.sentinel.ieee, nwk)
607 | # conbee.endpoints = {
608 | # 0: mock.sentinel.zdo,
609 | # 1: mock.sentinel.ep1,
610 | # 2: mock.sentinel.ep2,
611 | # }
612 | #
613 | # await conbee.add_to_group(mock.sentinel.grp_id, mock.sentinel.grp_name)
614 | # assert group.add_member.call_count == 2
615 | #
616 | # assert app.groups.add_group.call_count == 1
617 | # assert app.groups.add_group.call_args[0][0] is mock.sentinel.grp_id
618 | # assert app.groups.add_group.call_args[0][1] is mock.sentinel.grp_name
619 | #
620 | #
621 | # @pytest.mark.asyncio
622 | # async def test_conbee_dev_remove_from_group(app, nwk):
623 | # group = mock.MagicMock()
624 | # app.groups[mock.sentinel.grp_id] = group
625 | # conbee = application.ConBeeDevice(app, mock.sentinel.ieee, nwk)
626 | # conbee.endpoints = {
627 | # 0: mock.sentinel.zdo,
628 | # 1: mock.sentinel.ep1,
629 | # 2: mock.sentinel.ep2,
630 | # }
631 | #
632 | # await conbee.remove_from_group(mock.sentinel.grp_id)
633 | # assert group.remove_member.call_count == 2
634 | #
635 | #
636 | # def test_conbee_props(nwk):
637 | # conbee = application.ConBeeDevice(app, mock.sentinel.ieee, nwk)
638 | # assert conbee.manufacturer is not None
639 | # assert conbee.model is not None
640 | #
641 | #
642 | # @pytest.mark.asyncio
643 | # async def test_conbee_new(app, nwk, monkeypatch):
644 | # mock_init = mock.MagicMock(side_effect=asyncio.coroutine(mock.MagicMock()))
645 | # monkeypatch.setattr(zigpy.device.Device, "_initialize", mock_init)
646 | #
647 | # conbee = await application.ConBeeDevice.new(app, mock.sentinel.ieee, nwk)
648 | # assert isinstance(conbee, application.ConBeeDevice)
649 | # assert mock_init.call_count == 1
650 | # mock_init.reset_mock()
651 | #
652 | # mock_dev = mock.MagicMock()
653 | # mock_dev.endpoints = {
654 | # 0: mock.MagicMock(),
655 | # 1: mock.MagicMock(),
656 | # 22: mock.MagicMock(),
657 | # }
658 | # app.devices[mock.sentinel.ieee] = mock_dev
659 | # conbee = await application.ConBeeDevice.new(app, mock.sentinel.ieee, nwk)
660 | # assert isinstance(conbee, application.ConBeeDevice)
661 | # assert mock_init.call_count == 0
662 | #
663 | #
664 | # def test_tx_confirm_success(app):
665 | # tsn = 123
666 | # req = app._pending[tsn] = mock.MagicMock()
667 | # app.handle_tx_confirm(tsn, mock.sentinel.status)
668 | # assert req.result.set_result.call_count == 1
669 | # assert req.result.set_result.call_args[0][0] is mock.sentinel.status
670 | #
671 | #
672 | # def test_tx_confirm_dup(app, caplog):
673 | # caplog.set_level(logging.DEBUG)
674 | # tsn = 123
675 | # req = app._pending[tsn] = mock.MagicMock()
676 | # req.result.set_result.side_effect = asyncio.InvalidStateError
677 | # app.handle_tx_confirm(tsn, mock.sentinel.status)
678 | # assert req.result.set_result.call_count == 1
679 | # assert req.result.set_result.call_args[0][0] is mock.sentinel.status
680 | # assert any(r.levelname == "DEBUG" for r in caplog.records)
681 | # assert "probably duplicate response" in caplog.text
682 | #
683 | #
684 | # def test_tx_confirm_unexpcted(app, caplog):
685 | # app.handle_tx_confirm(123, 0x00)
686 | # assert any(r.levelname == "WARNING" for r in caplog.records)
687 | # assert "Unexpected transmit confirm for request id" in caplog.text
688 | #
689 | #
690 | # async def _test_mrequest(app, send_success=True, aps_data_error=False, **kwargs):
691 | # seq = 123
692 | # req_id = mock.sentinel.req_id
693 | # app.get_sequence = mock.MagicMock(return_value=req_id)
694 | #
695 | # async def req_mock(req_id, dst_addr_ep, profile, cluster, src_ep, data):
696 | # if aps_data_error:
697 | # raise zigpy_cc.exception.CommandError(1, "Command Error")
698 | # if send_success:
699 | # app._pending[req_id].result.set_result(0)
700 | # else:
701 | # app._pending[req_id].result.set_result(1)
702 | #
703 | # app._api.aps_data_request = mock.MagicMock(side_effect=req_mock)
704 | # device = zigpy.device.Device(app, mock.sentinel.ieee, 0x1122)
705 | # app.get_device = mock.MagicMock(return_value=device)
706 | #
707 | # return await app.mrequest(0x55AA, 0x0260, 1, 2, seq, b"\x01\x02\x03", **kwargs)
708 | #
709 | #
710 | # @pytest.mark.asyncio
711 | # async def test_mrequest_send_success(app):
712 | # r = await _test_mrequest(app, True)
713 | # assert r[0] == 0
714 | #
715 | #
716 | # @pytest.mark.asyncio
717 | # async def test_mrequest_send_fail(app):
718 | # r = await _test_mrequest(app, False)
719 | # assert r[0] != 0
720 | #
721 | #
722 | # @pytest.mark.asyncio
723 | # async def test_mrequest_send_aps_data_error(app):
724 | # r = await _test_mrequest(app, False, aps_data_error=True)
725 | # assert r[0] != 0
726 |
--------------------------------------------------------------------------------
/tests/test_buffalo.py:
--------------------------------------------------------------------------------
1 | from zigpy.types import EUI64, Group, NWK
2 |
3 | import zigpy_cc.types as t
4 | from zigpy_cc.buffalo import Buffalo, BuffaloOptions
5 |
6 | ieeeAddr1 = {
7 | "string": EUI64.convert("ae:44:01:12:00:4b:12:00"),
8 | "hex": bytes([0x00, 0x12, 0x4B, 0x00, 0x12, 0x01, 0x44, 0xAE]),
9 | }
10 |
11 | ieeeAddr2 = {
12 | "string": EUI64.convert("af:44:01:12:00:5b:12:00"),
13 | "hex": bytes([0x00, 0x12, 0x5B, 0x00, 0x12, 0x01, 0x44, 0xAF]),
14 | }
15 |
16 |
17 | def test_write_ieee():
18 | data_out = Buffalo(b"")
19 | data_out.write_parameter(t.ParameterType.IEEEADDR, ieeeAddr1["string"], {})
20 | assert ieeeAddr1["hex"] == data_out.buffer
21 |
22 |
23 | def test_write_ieee2():
24 | data_out = Buffalo(b"")
25 | data_out.write_parameter(t.ParameterType.IEEEADDR, ieeeAddr2["string"], {})
26 | assert ieeeAddr2["hex"] == data_out.buffer
27 |
28 |
29 | def test_write_ieee_group():
30 | data_out = Buffalo(b"")
31 | data_out.write_parameter(t.ParameterType.IEEEADDR, Group(2), {})
32 | assert b"\x02\x00\x00\x00\x00\x00\x00\x00" == data_out.buffer
33 |
34 |
35 | def test_read_ieee():
36 | data_in = Buffalo(ieeeAddr1["hex"])
37 | actual = data_in.read_parameter("test", t.ParameterType.IEEEADDR, {})
38 | assert ieeeAddr1["string"] == actual
39 |
40 |
41 | def test_read_ieee2():
42 | data_in = Buffalo(ieeeAddr2["hex"])
43 | actual = data_in.read_parameter("test", t.ParameterType.IEEEADDR, {})
44 | assert ieeeAddr2["string"] == actual
45 |
46 |
47 | def test_list_nighbor_lqi():
48 | value = [
49 | {
50 | "extPanId": EUI64.convert("d8:dd:dd:dd:d0:dd:ed:dd"),
51 | "extAddr": EUI64.convert("00:15:8d:00:04:21:dc:b3"),
52 | "nwkAddr": NWK(0xE961),
53 | "deviceType": 1,
54 | "rxOnWhenIdle": 2,
55 | "relationship": 2,
56 | "permitJoin": 2,
57 | "depth": 255,
58 | "lqi": 69,
59 | }
60 | ]
61 | data_out = Buffalo(b"")
62 | data_out.write_parameter(t.ParameterType.LIST_NEIGHBOR_LQI, value, {})
63 | assert (
64 | b"\xdd\xed\xdd\xd0\xdd\xdd\xdd\xd8\xb3\xdc!\x04\x00\x8d\x15\x00a\xe9)\x02\xffE"
65 | == data_out.buffer
66 | )
67 |
68 | data_in = Buffalo(data_out.buffer)
69 | options = BuffaloOptions()
70 | options.length = len(value)
71 | act = data_in.read_parameter("test", t.ParameterType.LIST_NEIGHBOR_LQI, options)
72 | assert value == act
73 |
--------------------------------------------------------------------------------
/tests/test_types.py:
--------------------------------------------------------------------------------
1 | # flake8: noqa: E501
2 | from unittest import mock
3 |
4 | from zigpy.zcl.clusters.general import PowerConfiguration
5 |
6 | import zigpy_cc.types as t
7 | from zigpy.zcl import Cluster
8 | from zigpy.types import NWK, EUI64
9 | from zigpy.zdo.types import ZDOCmd
10 | from zigpy_cc import uart
11 | from zigpy_cc.zpi_object import ZpiObject
12 |
13 | DIMMER = "0x000b57fffe27783c"
14 | COORDINATOR = "0x00124b0018ed250c"
15 |
16 |
17 | def test_incoming_msg():
18 | """
19 | zigpy_cc.api DEBUG --> AREQ AF incomingMsg
20 | {'groupid': 0, 'clusterid': 0, 'srcaddr': 28294, 'srcendpoint': 1, 'dstendpoint': 1,
21 | 'wasbroadcast': 0, 'linkquality': 115, 'securityuse': 0, 'timestamp': 15812278,
22 | 'transseqnumber': 0, 'len': 25, 'data': b'\x18\x00\n\x05\x00B\x12lumi.sensor_switch'
23 | }
24 |
25 | ZLC msg not ZDO
26 | """
27 | epmock = mock.MagicMock()
28 |
29 | cls = Cluster.from_id(epmock, 0)
30 | hdr, data = cls.deserialize(b"\x18\x00\n\x05\x00B\x12lumi.sensor_switch")
31 | assert (
32 | str(data) == "[[Attribute(attrid=5, value=<"
33 | "TypeValue type=CharacterString, value=lumi.sensor_switch>)]]"
34 | )
35 | assert (
36 | str(hdr) == " "
38 | "manufacturer=None tsn=0 command_id=Command.Report_Attributes>"
39 | )
40 |
41 |
42 | def test_incoming_msg2():
43 | """
44 | zigpy_cc.api DEBUG --> AREQ AF incomingMsg
45 | {'groupid': 0, 'clusterid': 0, 'srcaddr': 4835, 'srcendpoint': 1, 'dstendpoint': 1,
46 | 'wasbroadcast': 0, 'linkquality': 110, 'securityuse': 0, 'timestamp': 8255669,
47 | 'transseqnumber': 0, 'len': 29,
48 | 'data': b'\x1c4\x12\x02\n\x02\xffL\x06\x00\x10\x00!\xce\x0b!\xa8\x01$
49 | \x00\x00\x00\x00\x00!\xbdJ ]'}
50 | """
51 | epmock = mock.MagicMock()
52 |
53 | cls = Cluster.from_id(epmock, 0)
54 | hdr, data = cls.deserialize(
55 | b"\x1c\x34\x12\x02\x0a\x02\xffL\x06\x00\x10\x00!\xce\x0b!\xa8\x01$"
56 | b"\x00\x00\x00\x00\x00!\xbdJ ]"
57 | )
58 | assert (
59 | str(hdr) == " "
61 | "manufacturer=4660 tsn=2 command_id=Command.Report_Attributes>"
62 | )
63 |
64 |
65 | def test_from_unpi_frame():
66 | frame = uart.UnpiFrame(3, 1, 2, b"\x02\x00\x02\x06\x03\x90\x154\x01")
67 | extra = {
68 | "maintrel": 3,
69 | "majorrel": 2,
70 | "minorrel": 6,
71 | "product": 0,
72 | "revision": 20190608,
73 | "transportrev": 2,
74 | }
75 |
76 | obj = ZpiObject.from_unpi_frame(frame)
77 | assert obj.command == "version"
78 | assert obj.payload == extra
79 |
80 | assert str(obj.to_unpi_frame()) == str(frame)
81 |
82 |
83 | def test_from_unpi_frame2():
84 | frame = uart.UnpiFrame(
85 | 2,
86 | 4,
87 | 129,
88 | b"\x00\x00\x01\x00\xbbm\x01\x01\x00s\x00YC3\x00\x00\t\x18\x01\x01\x04\x00\x86"
89 | b"\x05\x00\x86\xbbm\x1d",
90 | )
91 |
92 | obj = ZpiObject.from_unpi_frame(frame)
93 |
94 | assert (
95 | "AREQ AF incomingMsg tsn: None {'groupid': 0, 'clusterid': 1, "
96 | "'srcaddr': 0x6DBB, 'srcendpoint': 1, 'dstendpoint': 1, 'wasbroadcast': 0,"
97 | " 'linkquality': 115, 'securityuse': 0, 'timestamp': 3359577, "
98 | "'transseqnumber': 0, 'len': 9, "
99 | "'data': b'\\x18\\x01\\x01\\x04\\x00\\x86\\x05\\x00\\x86'}" == str(obj)
100 | )
101 |
102 |
103 | """
104 | zigbee-herdsman:adapter:zStack:znp:SREQ --> AF - dataRequest
105 | {
106 | "dstaddr":44052,
107 | "destendpoint":1,
108 | "srcendpoint":1,
109 | "clusterid":0,
110 | "transid":1,
111 | "options":0,
112 | "radius":30,
113 | "len":9,
114 | "data":{
115 | "type":"Buffer",
116 | "data":[16,2,0,5,0,4,0,7,0]
117 | }
118 | }
119 |
120 | zigbee-herdsman:adapter:zStack:znp:SRSP <-- AF - dataRequest
121 | {"status":0} +135ms
122 |
123 | zigbee-herdsman:adapter:zStack:znp:AREQ <-- AF - dataConfirm
124 | {"status":0,"endpoint":1,"transid":1} +62ms
125 |
126 | zigbee-herdsman:adapter:zStack:znp:AREQ <-- AF - incomingMsg
127 | {
128 | "groupid":0,
129 | "clusterid":0,
130 | "srcaddr":44052,
131 | "srcendpoint":1,
132 | "dstendpoint":1,
133 | "wasbroadcast":0,
134 | "linkquality":78,
135 | "securityuse":0,
136 | "timestamp":2206697,
137 | "transseqnumber":0,
138 | "len":55,
139 | "data":{
140 | "type":"Buffer",
141 | "data":[24,2,1,5,0,0,66,23,84,82,65,68,70,82,73,32,119,105,114,101,108,101,115,
142 | 115,32,100,105,109,109,101,114,4,0,0,66,14,73,75,69,65,32,111,102,32,83,
143 | 119,101,100,101,110,7,0,0,48,3]
144 | }
145 | }
146 |
147 | zigbee-herdsman:controller:log Received 'zcl' data '
148 | {
149 | "frame":{
150 | "Header":{
151 | "frameControl":{"frameType":0,"manufacturerSpecific":false,"direction":1,
152 | "disableDefaultResponse":true},
153 | "transactionSequenceNumber":2,
154 | "manufacturerCode":null,
155 | "commandIdentifier":1
156 | },
157 | "Payload":[
158 | {"attrId":5,"status":0,"dataType":66,"attrData":"TRADFRI wireless dimmer"},
159 | {"attrId":4,"status":0,"dataType":66,"attrData":"IKEA of Sweden"},
160 | {"attrId":7,"status":0,"dataType":48,"attrData":3}
161 | ],
162 | "Cluster":{
163 | "ID":0,
164 | "attributes":{
165 | "zclVersion":{"ID":0,"type":32,"name":"zclVersion"},
166 | "appVersion":{"ID":1,"type":32,"name":"appVersion"},
167 | "stackVersion":{"ID":2,"type":32,"name":"stackVersion"},
168 | "hwVersion":{"ID":3,"type":32,"name":"hwVersion"},
169 | "manufacturerName":{"ID":4,"type":66,"name":"manufacturerName"},
170 | "modelId":{"ID":5,"type":66,"name":"modelId"},
171 | "dateCode":{"ID":6,"type":66,"name":"dateCode"},
172 | "powerSource":{"ID":7,"type":48,"name":"powerSource"},
173 | "appProfileVersion":{"ID":8,"type":48,"name":"appProfileVersion"},
174 | "swBuildId":{"ID":16384,"type":66,"name":"swBuildId"},
175 | "locationDesc":{"ID":16,"type":66,"name":"locationDesc"},
176 | "physicalEnv":{"ID":17,"type":48,"name":"physicalEnv"},
177 | "deviceEnabled":{"ID":18,"type":16,"name":"deviceEnabled"},
178 | "alarmMask":{"ID":19,"type":24,"name":"alarmMask"},
179 | "disableLocalConfig":{"ID":20,"type":24,"name":"disableLocalConfig"}
180 | },
181 | "name":"genBasic",
182 | "commands":{
183 | "resetFactDefault":{"ID":0,"parameters":[],"name":"resetFactDefault"}
184 | },
185 | "commandsResponse":{}
186 | }
187 | },
188 | "address":44052,
189 | "endpoint":1,
190 | "linkquality":78,
191 | "groupID":0
192 | }
193 | """
194 |
195 |
196 | def test_from_unpi_frame3():
197 | payload = {
198 | "groupid": 0,
199 | "clusterid": 0,
200 | "srcaddr": 44052,
201 | "srcendpoint": 1,
202 | "dstendpoint": 1,
203 | "wasbroadcast": 0,
204 | "linkquality": 78,
205 | "securityuse": 0,
206 | "timestamp": 2206697,
207 | "transseqnumber": 0,
208 | "len": 55,
209 | "data": bytes(
210 | [
211 | 24,
212 | 2,
213 | 1,
214 | 5,
215 | 0,
216 | 0,
217 | 66,
218 | 23,
219 | 84,
220 | 82,
221 | 65,
222 | 68,
223 | 70,
224 | 82,
225 | 73,
226 | 32,
227 | 119,
228 | 105,
229 | 114,
230 | 101,
231 | 108,
232 | 101,
233 | 115,
234 | 115,
235 | 32,
236 | 100,
237 | 105,
238 | 109,
239 | 109,
240 | 101,
241 | 114,
242 | 4,
243 | 0,
244 | 0,
245 | 66,
246 | 14,
247 | 73,
248 | 75,
249 | 69,
250 | 65,
251 | 32,
252 | 111,
253 | 102,
254 | 32,
255 | 83,
256 | 119,
257 | 101,
258 | 100,
259 | 101,
260 | 110,
261 | 7,
262 | 0,
263 | 0,
264 | 48,
265 | 3,
266 | ]
267 | ),
268 | }
269 | obj = ZpiObject.from_command(t.Subsystem.AF, "incomingMsg", payload)
270 |
271 | assert (
272 | "AREQ AF incomingMsg tsn: None {'groupid': 0, 'clusterid': 0, "
273 | "'srcaddr': 44052, 'srcendpoint': 1, 'dstendpoint': 1, 'wasbroadcast': 0, "
274 | "'linkquality': 78, 'securityuse': 0, 'timestamp': 2206697, "
275 | "'transseqnumber': 0, 'len': 55, "
276 | "'data': b'\\x18\\x02\\x01\\x05\\x00\\x00B\\x17TRADFRI wireless dimmer"
277 | "\\x04\\x00\\x00B\\x0eIKEA of Sweden\\x07\\x00\\x000\\x03'}" == str(obj)
278 | )
279 |
280 |
281 | def test_ieee_addr():
282 | frame = uart.UnpiFrame(
283 | 3, 7, 0, b"\x00\x0c%\xed\x18\x00K\x12\x00\x00\x00\x07\t\x02J\xd0]\x97"
284 | )
285 | obj = ZpiObject.from_unpi_frame(frame)
286 |
287 | out = obj.to_unpi_frame()
288 | assert b"\x00\x0c%\xed\x18\x00K\x12\x00\x00\x00\x07\t\x02J\xd0]\x97" == out.data
289 |
290 |
291 | """
292 | zigpy_cc.zigbee.application INFO New device joined: 53322, 00:15:8d:00:02:4b:e5:41
293 | zigpy.application INFO Device 0xd04a (00:15:8d:00:02:4b:e5:41) joined the network
294 | zigpy.zdo DEBUG [0xd04a:zdo] ZDO request ZDOCmd.Device_annce: [0xd04a, 41:e5:4b:02:00:8d:15:00, 132]
295 | zigpy.device INFO [0xd04a] Requesting 'Node Descriptor'
296 | Tries remaining: 2
297 | zigpy.device DEBUG [0xd04a] Extending timeout for 0x03 request
298 | zigpy_cc.zigbee.application DEBUG Sending Zigbee request with tsn 3 under 4 request id, data: b'034ad0'
299 | zigpy_cc.api DEBUG <-- SREQ ZDO nodeDescReq {'dstaddr': 53322, 'nwkaddrofinterest': 0}
300 | zigpy_cc.api DEBUG --> SRSP ZDO nodeDescReq {'status': 0}
301 | zigpy_cc.api DEBUG --> AREQ ZDO nodeDescRsp {'srcaddr': 53322, 'status': 128, 'nwkaddr': 0, 'logicaltype_cmplxdescavai_userdescavai': 0, 'apsflags_freqband': 0, 'maccapflags': 0, 'manufacturercode': 0, 'maxbuffersize': 0, 'maxintransfersize': 0, 'servermask': 0, 'maxouttransfersize': 0, 'descriptorcap': 0}
302 | """
303 |
304 |
305 | def test_from_cluster_id():
306 | profile = 0
307 | obj = ZpiObject.from_cluster(
308 | NWK(53322), profile, ZDOCmd.Node_Desc_req, 0, 0, 3, b"\x03\x4a\xd0"
309 | )
310 |
311 | assert (
312 | "SREQ ZDO nodeDescReq tsn: 3 {'dstaddr': 0xD04A, 'nwkaddrofinterest': 0xD04A}"
313 | == str(obj)
314 | )
315 |
316 |
317 | """
318 | profile 260
319 | cluster 0
320 | src_ep 1
321 | dst_ep 1
322 | sequence 1
323 | data b'\x00\x0b\x00\x04\x00\x05\x00'
324 | """
325 |
326 |
327 | def test_from_cluster_id_ZCL():
328 | profile = 260
329 | obj = ZpiObject.from_cluster(
330 | NWK(53322), profile, 0, 1, 1, 123, b"\x00\x0b\x00\x04\x00\x05\x00"
331 | )
332 |
333 | assert (
334 | "SREQ AF dataRequest tsn: 123 {'dstaddr': 53322, 'destendpoint': 1, "
335 | "'srcendpoint': 1, 'clusterid': 0, 'transid': 123, 'options': 0, 'radius': 30, "
336 | "'len': 7, 'data': b'\\x00\\x0b\\x00\\x04\\x00\\x05\\x00'}" == str(obj)
337 | )
338 |
339 |
340 | def test_deser():
341 | endp = mock.MagicMock()
342 | power_configuration = PowerConfiguration(endp)
343 | data = bytes([16, 5, 6, 0, 33, 0, 32, 16, 14, 48, 242, 0])
344 | hdr, value = power_configuration.deserialize(data)
345 |
346 | assert (
347 | " "
349 | "manufacturer=None "
350 | "tsn=5 "
351 | "command_id=Command.Configure_Reporting>" == str(hdr)
352 | )
353 | assert 1 == len(value)
354 | assert {
355 | "direction": False,
356 | "attrid": 33,
357 | "datatype": 32,
358 | "min_interval": 3600,
359 | "max_interval": 62000,
360 | "reportable_change": 0,
361 | } == value[0][0].__dict__
362 |
363 |
364 | def test_bind_req():
365 | """
366 | zigpy_cc.zigbee.application DEBUG request (
367 | 0xbd8b, 0, , 0, 0, 1,
368 | b"\x01 SREQ ZDO bindReq tsn: 1 {
371 | 'dstaddr': 0xbd8b, 'srcaddr': 00:0b:57:ff:fe:27:78:3c, 'srcendpoint': 1, 'clusterid': 8,
372 | 'dstaddrmode': 3, 'dstaddress': 00:12:4b:00:18:ed:25:0c, 'dstendpoint': 1}
373 | zigpy_cc.uart DEBUG Send:
374 | b"\xfe\x17%!\x8b\xbd, "
389 | "'dstaddress': 00:12:4b:00:18:ed:25:0c, "
390 | "'dstendpoint': 1}" == str(obj)
391 | )
392 | assert (
393 | bytes(
394 | [
395 | 254,
396 | 23,
397 | 37,
398 | 33,
399 | 146,
400 | 98,
401 | 60,
402 | 120,
403 | 39,
404 | 254,
405 | 255,
406 | 87,
407 | 11,
408 | 0,
409 | 1,
410 | 8,
411 | 0,
412 | 3,
413 | 12,
414 | 37,
415 | 237,
416 | 24,
417 | 0,
418 | 75,
419 | 18,
420 | 0,
421 | 1,
422 | 83,
423 | ]
424 | )
425 | == obj.to_unpi_frame().to_buffer()
426 | )
427 |
428 |
429 | def test_bind_req_serialize():
430 | payload = {
431 | "dstaddr": NWK(25234),
432 | "srcaddr": EUI64(reversed(b"\x00\x0b\x57\xff\xfe\x27\x78\x3c")),
433 | "srcendpoint": 1,
434 | "clusterid": 8,
435 | "dstaddrmode": t.AddressMode.ADDR_64BIT,
436 | "dstaddress": EUI64(reversed(b"\x00\x12\x4b\x00\x18\xed\x25\x0c")),
437 | "dstendpoint": 1,
438 | }
439 | obj = ZpiObject.from_command(t.Subsystem.ZDO, "bindReq", payload)
440 | assert (
441 | "SREQ ZDO bindReq tsn: None {"
442 | "'dstaddr': 0x6292, "
443 | "'srcaddr': 00:0b:57:ff:fe:27:78:3c, "
444 | "'srcendpoint': 1, "
445 | "'clusterid': 8, "
446 | "'dstaddrmode': , "
447 | "'dstaddress': 00:12:4b:00:18:ed:25:0c, "
448 | "'dstendpoint': 1}" == str(obj)
449 | )
450 | assert (
451 | bytes(
452 | [
453 | 254,
454 | 23,
455 | 37,
456 | 33,
457 | 146,
458 | 98,
459 | 60,
460 | 120,
461 | 39,
462 | 254,
463 | 255,
464 | 87,
465 | 11,
466 | 0,
467 | 1,
468 | 8,
469 | 0,
470 | 3,
471 | 12,
472 | 37,
473 | 237,
474 | 24,
475 | 0,
476 | 75,
477 | 18,
478 | 0,
479 | 1,
480 | 83,
481 | ]
482 | )
483 | == obj.to_unpi_frame().to_buffer()
484 | )
485 |
486 |
487 | # https://github.com/zigpy/zigpy-cc/issues/21
488 | def test_mgmt_lqi_rsp():
489 | frame = uart.UnpiFrame(
490 | 2,
491 | 5,
492 | 177,
493 | b"\x00\x00\x00\x14\x00\x03\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\x1d$&\xfe\xffW\xb4\x14\xef>\x15\x02\x01\x00\xdd"
494 | b"\xdd\xdd\xdd\xdd\xdd\xdd\xdd\x9atk\x03\x00\x8d\x15\x00}0\x12\x02\x01`\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\x8d(,"
495 | b"\x03\x00\x8d\x15\x00}\xcc\x12\x02\x017",
496 | 72,
497 | 34,
498 | )
499 | obj = ZpiObject.from_unpi_frame(frame)
500 | assert (
501 | "AREQ ZDO mgmtLqiRsp tsn: None {"
502 | "'srcaddr': 0x0000, "
503 | "'status': 0, "
504 | "'neighbortableentries': 20, "
505 | "'startindex': 0, "
506 | "'neighborlqilistcount': 3, "
507 | "'neighborlqilist': ["
508 | "{'extPanId': dd:dd:dd:dd:dd:dd:dd:dd, 'extAddr': 14:b4:57:ff:fe:26:24:1d, 'nwkAddr': 0x3EEF, "
509 | "'deviceType': 1, 'rxOnWhenIdle': 1, 'relationship': 1, 'permitJoin': 2, 'depth': 1, 'lqi': 0}, "
510 | "{'extPanId': dd:dd:dd:dd:dd:dd:dd:dd, 'extAddr': 00:15:8d:00:03:6b:74:9a, 'nwkAddr': 0x307D, "
511 | "'deviceType': 2, 'rxOnWhenIdle': 0, 'relationship': 1, 'permitJoin': 2, 'depth': 1, 'lqi': 96}, "
512 | "{'extPanId': dd:dd:dd:dd:dd:dd:dd:dd, 'extAddr': 00:15:8d:00:03:2c:28:8d, 'nwkAddr': 0xCC7D, "
513 | "'deviceType': 2, 'rxOnWhenIdle': 0, 'relationship': 1, 'permitJoin': 2, 'depth': 1, 'lqi': 55}"
514 | "]}" == str(obj)
515 | )
516 |
517 |
518 | def test_mgmt_nwk_update_notify():
519 | frame = uart.UnpiFrame(
520 | 2,
521 | 5,
522 | 184,
523 | b"\xe9\xc0\x00\x00\xf8\xff\x07\x14\x00\x0f\x00\x10\xd6\xac"
524 | b"\xcc\xb0\xb5\xa2\xb2\xa5\xb3\xa5\xa2\xa9\xa1\xa1\xa5\xae",
525 | 28,
526 | 211,
527 | )
528 | obj = ZpiObject.from_unpi_frame(frame)
529 | assert (
530 | "AREQ ZDO mgmtNwkUpdateNotify tsn: None {'srcaddr': 0xC0E9, 'status': 0, "
531 | "'scanchannels': 134215680, 'totaltransmissions': 20, 'transmissionfailures': "
532 | "15, 'channelcount': 16, 'energyvalues': [214, 172, 204, 176, 181, 162, 178, "
533 | "165, 179, 165, 162, 169, 161, 161, 165, 174]}" == str(obj)
534 | )
535 |
--------------------------------------------------------------------------------
/tests/test_uart.py:
--------------------------------------------------------------------------------
1 | from asynctest import mock
2 |
3 | import pytest
4 | import serial_asyncio
5 |
6 | from zigpy_cc import uart
7 | import zigpy_cc.config
8 |
9 | DEVICE_CONFIG = zigpy_cc.config.SCHEMA_DEVICE(
10 | {zigpy_cc.config.CONF_DEVICE_PATH: "/dev/null"}
11 | )
12 |
13 |
14 | def eq(a, b):
15 | assert str(a) == str(b)
16 |
17 |
18 | @pytest.fixture(scope="function")
19 | def gw():
20 | gw = uart.Gateway(mock.MagicMock())
21 | gw._transport = mock.MagicMock()
22 | return gw
23 |
24 |
25 | @pytest.mark.asyncio
26 | async def test_connect(monkeypatch):
27 | api = mock.MagicMock()
28 | transport = mock.MagicMock()
29 |
30 | async def mock_conn(loop, protocol_factory, **kwargs):
31 | protocol = protocol_factory()
32 | loop.call_soon(protocol.connection_made, transport)
33 | return None, protocol
34 |
35 | monkeypatch.setattr(serial_asyncio, "create_serial_connection", mock_conn)
36 |
37 | await uart.connect(DEVICE_CONFIG, api)
38 |
39 |
40 | def test_write(gw):
41 | data = b"\x00"
42 | gw.write(data)
43 | assert gw._transport.write.call_count == 1
44 | assert gw._transport.write.called_once_with(data)
45 |
46 |
47 | def test_close(gw):
48 | gw.close()
49 | assert gw._transport.close.call_count == 1
50 |
51 |
52 | def test_data_received_chunk_frame(gw):
53 | data = b"\xfe\x0ea\x02\x02\x00\x02\x06\x03\x90\x154\x01\x02\x00\x00\x00\x00\xda"
54 | gw.data_received(data[:-4])
55 | assert gw._api.data_received.call_count == 0
56 | gw.data_received(data[-4:])
57 | assert gw._api.data_received.call_count == 1
58 | eq(
59 | gw._api.data_received.call_args[0][0],
60 | uart.UnpiFrame(3, 1, 2, data[4:-1], 14, 218),
61 | )
62 |
63 |
64 | def test_data_received_full_frame(gw):
65 | data = b"\xfe\x0ea\x02\x02\x00\x02\x06\x03\x90\x154\x01\x02\x01\x00\x00\x00\xdb"
66 | gw.data_received(data)
67 | assert gw._api.data_received.call_count == 1
68 | eq(
69 | gw._api.data_received.call_args[0][0],
70 | uart.UnpiFrame(3, 1, 2, data[4:-1], 14, 219),
71 | )
72 |
73 |
74 | def test_data_received_incomplete_frame(gw):
75 | data = b"~\x00\x00"
76 | gw.data_received(data)
77 | assert gw._api.data_received.call_count == 0
78 |
79 |
80 | def test_data_received_runt_frame(gw):
81 | data = b"\x02\x44\xC0"
82 | gw.data_received(data)
83 | assert gw._api.data_received.call_count == 0
84 |
85 |
86 | def test_data_received_extra(gw):
87 | data = (
88 | b"\xfe\x0ea\x02\x02\x00\x02\x06\x03\x90\x154\x01\x02\x01\x00\x00\x00\xdb"
89 | b"\xfe\x00"
90 | )
91 | gw.data_received(data)
92 | assert gw._api.data_received.call_count == 1
93 | assert gw._parser.buffer == b"\xfe\x00"
94 |
95 |
96 | def test_data_received_wrong_checksum(gw):
97 | data = b"\xfe\x0ea\x02\x02\x00\x02\x06\x03\x90\x154\x01\x02\x01\x00\x00\x00\xdc"
98 | gw.data_received(data)
99 | assert gw._api.data_received.call_count == 0
100 |
101 |
102 | @pytest.mark.skip("TODO")
103 | def test_unescape(gw):
104 | data = b"\x00\xDB\xDC\x00\xDB\xDD\x00\x00\x00"
105 | data_unescaped = b"\x00\xC0\x00\xDB\x00\x00\x00"
106 | r = gw._unescape(data)
107 | assert r == data_unescaped
108 |
109 |
110 | @pytest.mark.skip("TODO")
111 | def test_unescape_error(gw):
112 | data = b"\x00\xDB\xDC\x00\xDB\xDD\x00\x00\x00\xDB"
113 | r = gw._unescape(data)
114 | assert r is None
115 |
116 |
117 | @pytest.mark.skip("TODO")
118 | def test_escape(gw):
119 | data = b"\x00\xC0\x00\xDB\x00\x00\x00"
120 | data_escaped = b"\x00\xDB\xDC\x00\xDB\xDD\x00\x00\x00"
121 | r = gw._escape(data)
122 | assert r == data_escaped
123 |
124 |
125 | def test_checksum():
126 | data = b"\x07\x01\x00\x08\x00\xaa\x00\x02"
127 | checksum = 166
128 | r = uart.UnpiFrame.calculate_checksum(data)
129 | assert r == checksum
130 |
131 |
132 | @pytest.mark.asyncio
133 | @pytest.mark.parametrize(
134 | "control, xonxoff, rtscts",
135 | (("software", True, False), ("hardware", False, True), (None, False, False)),
136 | )
137 | @mock.patch.object(serial_asyncio, "create_serial_connection")
138 | async def test_flow_control(conn_mock, control, xonxoff, rtscts):
139 | async def set_connected(loop, proto_factory, **kwargs):
140 | proto_factory()._connected_future.set_result(True)
141 | return mock.sentinel.a, mock.MagicMock()
142 |
143 | conn_mock.side_effect = set_connected
144 | await uart.connect(
145 | {**DEVICE_CONFIG, zigpy_cc.config.CONF_FLOW_CONTROL: control}, mock.MagicMock()
146 | )
147 | assert conn_mock.call_args[1]["xonxoff"] == xonxoff
148 | assert conn_mock.call_args[1]["rtscts"] == rtscts
149 |
--------------------------------------------------------------------------------
/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 = py36, py37, 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 | coveralls
17 | pytest
18 | pytest-cov
19 | pytest-asyncio
20 |
21 | [testenv:lint]
22 | basepython = python3
23 | deps = flake8
24 | commands = flake8
25 |
26 | [testenv:black]
27 | deps=black
28 | setenv =
29 | LC_ALL=C.UTF-8
30 | LANG=C.UTF-8
31 | commands=
32 | black --check --fast {toxinidir}
33 |
--------------------------------------------------------------------------------
/version.py:
--------------------------------------------------------------------------------
1 | import fileinput
2 | import os
3 | import re
4 | import sys
5 |
6 | parts = re.sub(r"^.*/v?", "", sys.argv[1]).split(".")
7 | dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | with fileinput.FileInput(dir + "/zigpy_cc/__init__.py", inplace=True) as file:
10 | for line in file:
11 | line = re.sub(r"(MAJOR_VERSION =).*", "\\1 " + parts[0], line)
12 | line = re.sub(r"(MINOR_VERSION =).*", "\\1 " + parts[1], line)
13 | line = re.sub(r"(PATCH_VERSION =).*", '\\1 "' + parts[2] + '"', line)
14 | print(line, end="")
15 |
--------------------------------------------------------------------------------
/zigpy_cc/__init__.py:
--------------------------------------------------------------------------------
1 | # This file updated automatically before PyPI release was created
2 | MAJOR_VERSION = 0
3 | MINOR_VERSION = 5
4 | PATCH_VERSION = "2"
5 | __short_version__ = "{}.{}".format(MAJOR_VERSION, MINOR_VERSION)
6 | __version__ = "{}.{}".format(__short_version__, PATCH_VERSION)
7 |
--------------------------------------------------------------------------------
/zigpy_cc/api.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | from typing import Any, Dict, Optional
4 |
5 | import serial
6 | import zigpy.exceptions
7 |
8 | from zigpy_cc import uart
9 | from zigpy_cc.config import CONF_DEVICE_PATH, SCHEMA_DEVICE
10 | from zigpy_cc.definition import Definition
11 | from zigpy_cc.exception import CommandError
12 | from zigpy_cc.types import CommandType, Repr, Subsystem, Timeouts
13 | from zigpy_cc.uart import Gateway
14 | from zigpy_cc.zpi_object import ZpiObject
15 |
16 | LOGGER = logging.getLogger(__name__)
17 |
18 | COMMAND_TIMEOUT = 2
19 |
20 |
21 | class Matcher(Repr):
22 | def __init__(self, command_type, subsystem, command, payload):
23 | self.command_type = command_type
24 | self.subsystem = subsystem
25 | self.command = command
26 | self.payload = payload
27 |
28 |
29 | class Waiter(Repr):
30 | def __init__(
31 | self,
32 | waiter_id: int,
33 | command_type: int,
34 | subsystem: int,
35 | command: str,
36 | payload,
37 | timeout: int,
38 | sequence,
39 | ):
40 | self.id = waiter_id
41 | self.matcher = Matcher(command_type, subsystem, command, payload)
42 | self.future = asyncio.get_event_loop().create_future()
43 | self.timeout = timeout
44 | self.sequence = sequence
45 |
46 | async def wait(self):
47 | return await asyncio.wait_for(self.future, self.timeout / 1000)
48 |
49 | def set_result(self, result) -> None:
50 | if self.future.cancelled():
51 | LOGGER.warning("Waiter already cancelled: %s", self)
52 | elif self.future.done():
53 | LOGGER.warning("Waiter already done: %s", self)
54 | else:
55 | self.future.set_result(result)
56 |
57 | def match(self, obj: ZpiObject):
58 | matcher = self.matcher
59 | if (
60 | matcher.command_type != obj.command_type
61 | or matcher.subsystem != obj.subsystem
62 | or matcher.command != obj.command
63 | ):
64 | return False
65 |
66 | if matcher.payload:
67 | for f, v in matcher.payload.items():
68 | if v != obj.payload[f]:
69 | return False
70 |
71 | return True
72 |
73 |
74 | class API:
75 | _uart: Optional[Gateway]
76 |
77 | def __init__(self, device_config: Dict[str, Any]):
78 | self._config = device_config
79 | self._lock = asyncio.Lock()
80 | self._waiter_id = 0
81 | self._waiters: Dict[int, Waiter] = {}
82 | self._app = None
83 | self._proto_ver = None
84 | self._uart = None
85 |
86 | @property
87 | def protocol_version(self):
88 | """Protocol Version."""
89 | return self._proto_ver
90 |
91 | @classmethod
92 | async def new(cls, application, config: Dict[str, Any]) -> "API":
93 | api = cls(config)
94 | await api.connect()
95 | api.set_application(application)
96 | return api
97 |
98 | def set_application(self, app):
99 | self._app = app
100 |
101 | async def connect(self):
102 | assert self._uart is None
103 | self._uart = await uart.connect(self._config, self)
104 |
105 | def close(self):
106 | if self._uart:
107 | self._uart.close()
108 | self._uart = None
109 |
110 | def connection_lost(self):
111 | self._app.connection_lost()
112 |
113 | async def request(
114 | self, subsystem, command, payload, waiter_id=None, expected_status=None
115 | ):
116 | obj = ZpiObject.from_command(subsystem, command, payload)
117 | return await self.request_raw(obj, waiter_id, expected_status)
118 |
119 | async def request_raw(self, obj: ZpiObject, waiter_id=None, expected_status=None):
120 | async with self._lock:
121 | return await self._request_raw(obj, waiter_id, expected_status)
122 |
123 | async def _request_raw(self, obj: ZpiObject, waiter_id=None, expected_status=None):
124 | if expected_status is None:
125 | expected_status = [0]
126 |
127 | LOGGER.debug("--> %s", obj)
128 | frame = obj.to_unpi_frame()
129 |
130 | if obj.command_type == CommandType.SREQ:
131 | timeout = (
132 | 20000
133 | if obj.command == "bdbStartCommissioning"
134 | or obj.command == "startupFromApp"
135 | else Timeouts.SREQ
136 | )
137 | waiter = self.wait_for(
138 | CommandType.SRSP, obj.subsystem, obj.command, {}, timeout
139 | )
140 | self._uart.send(frame)
141 | result = await waiter.wait()
142 | if (
143 | result
144 | and "status" in result.payload
145 | and result.payload["status"] not in expected_status
146 | ):
147 | if waiter_id is not None:
148 | self._waiters.pop(waiter_id).set_result(result)
149 |
150 | raise CommandError(
151 | result.payload["status"],
152 | "SREQ '{}' failed with status '{}' (expected '{}')".format(
153 | obj.command, result.payload["status"], expected_status
154 | ),
155 | )
156 | else:
157 | return result
158 | elif obj.command_type == CommandType.AREQ and obj.is_reset_command():
159 | waiter = self.wait_for(
160 | CommandType.AREQ, Subsystem.SYS, "resetInd", {}, Timeouts.reset
161 | )
162 | # TODO clear queue, requests waiting for lock
163 | self._uart.send(frame)
164 | return await waiter.wait()
165 | else:
166 | if obj.command_type == CommandType.AREQ:
167 | self._uart.send(frame)
168 | return None
169 | else:
170 | LOGGER.warning("Unknown type '%s'", obj.command_type)
171 | raise Exception("Unknown type '{}'".format(obj.command_type))
172 |
173 | def create_response_waiter(self, obj: ZpiObject, sequence=None):
174 | if obj.command_type == CommandType.SREQ and obj.command.startswith(
175 | "dataRequest"
176 | ):
177 | payload = {
178 | "transid": obj.payload["transid"],
179 | }
180 | return self.wait_for(CommandType.AREQ, Subsystem.AF, "dataConfirm", payload)
181 |
182 | if obj.command_type == CommandType.SREQ and obj.command.endswith("Req"):
183 | rsp = obj.command.replace("Req", "Rsp")
184 | for cmd in Definition[obj.subsystem]:
185 | if rsp == cmd["name"]:
186 | payload = {"srcaddr": obj.payload["dstaddr"]}
187 | return self.wait_for(
188 | CommandType.AREQ, Subsystem.ZDO, rsp, payload, sequence=sequence
189 | )
190 |
191 | LOGGER.warning("no response cmd configured for %s", obj.command)
192 | return None
193 |
194 | def wait_for(
195 | self,
196 | command_type: CommandType,
197 | subsystem: Subsystem,
198 | command: str,
199 | payload=None,
200 | timeout=Timeouts.default,
201 | sequence=None,
202 | ):
203 | waiter = Waiter(
204 | self._waiter_id,
205 | command_type,
206 | subsystem,
207 | command,
208 | payload,
209 | timeout,
210 | sequence,
211 | )
212 | self._waiters[waiter.id] = waiter
213 | self._waiter_id += 1
214 |
215 | def callback():
216 | if not waiter.future.done() or waiter.future.cancelled():
217 | LOGGER.warning(
218 | "No response for: %s %s %s %s",
219 | command_type.name,
220 | subsystem.name,
221 | command,
222 | payload,
223 | )
224 | try:
225 | self._waiters.pop(waiter.id)
226 | except KeyError:
227 | LOGGER.warning("Waiter not found: %s", waiter)
228 |
229 | asyncio.get_event_loop().call_later(timeout / 1000 + 0.1, callback)
230 |
231 | return waiter
232 |
233 | def data_received(self, frame):
234 | try:
235 | obj = ZpiObject.from_unpi_frame(frame)
236 | except Exception as e:
237 | LOGGER.error("Error while parsing frame: %s", frame)
238 | raise e
239 |
240 | for waiter_id in list(self._waiters):
241 | waiter = self._waiters.get(waiter_id)
242 | if waiter.match(obj):
243 | self._waiters.pop(waiter_id)
244 | waiter.set_result(obj)
245 | if waiter.sequence:
246 | obj.sequence = waiter.sequence
247 | break
248 |
249 | LOGGER.debug("<-- %s", obj)
250 |
251 | if self._app is not None:
252 | self._app.handle_znp(obj)
253 |
254 | try:
255 | getattr(self, "_handle_%s" % (obj.command,))(obj)
256 | except AttributeError:
257 | pass
258 |
259 | async def version(self):
260 | version = await self.request(Subsystem.SYS, "version", {})
261 | # todo check version
262 | self._proto_ver = version.payload
263 | return version.payload
264 |
265 | def _handle_version(self, data):
266 | LOGGER.debug("Version response: %s", data.payload)
267 |
268 | def _handle_getDeviceInfo(self, data):
269 | LOGGER.info("Device info: %s", data.payload)
270 |
271 | def _handle_srcRtgInd(self, data):
272 | pass
273 |
274 | @classmethod
275 | async def probe(cls, device_config: Dict[str, Any]) -> bool:
276 | """Probe port for the device presence."""
277 | api = cls(SCHEMA_DEVICE(device_config))
278 | try:
279 | await asyncio.wait_for(api._probe(), timeout=COMMAND_TIMEOUT)
280 | return True
281 | except (
282 | asyncio.TimeoutError,
283 | serial.SerialException,
284 | zigpy.exceptions.ZigbeeException,
285 | ) as exc:
286 | LOGGER.debug(
287 | "Unsuccessful radio probe of '%s' port",
288 | device_config[CONF_DEVICE_PATH],
289 | exc_info=exc,
290 | )
291 | finally:
292 | api.close()
293 |
294 | return False
295 |
296 | async def _probe(self) -> None:
297 | """Open port and try sending a command"""
298 | await self.connect()
299 | await self.version()
300 |
--------------------------------------------------------------------------------
/zigpy_cc/buffalo.py:
--------------------------------------------------------------------------------
1 | from collections.abc import Iterable
2 |
3 | import zigpy.types
4 | from zigpy_cc.exception import TODO
5 | from zigpy_cc.types import AddressMode, ParameterType
6 |
7 |
8 | class BuffaloOptions:
9 | def __init__(self) -> None:
10 | self.startIndex = None
11 | self.length = None
12 |
13 |
14 | class Buffalo:
15 | def __init__(self, buffer, position=0) -> None:
16 | self.position = position
17 | self.buffer = buffer
18 | self._len = len(buffer)
19 |
20 | def __len__(self) -> int:
21 | return len(self.buffer)
22 |
23 | def write_parameter(self, type, value, options):
24 | if type == ParameterType.UINT8:
25 | self.write(value)
26 | elif type == ParameterType.UINT16:
27 | self.write(value, 2)
28 | elif type == ParameterType.UINT32:
29 | self.write(value, 4)
30 | elif type == ParameterType.IEEEADDR:
31 | if isinstance(value, Iterable):
32 | for i in value:
33 | self.write(i)
34 | else:
35 | self.write(value, 8)
36 | elif type == ParameterType.BUFFER:
37 | self.buffer += value
38 | elif type == ParameterType.LIST_UINT8:
39 | for v in value:
40 | self.write(v)
41 | elif type == ParameterType.LIST_UINT16:
42 | for v in value:
43 | self.write(v, 2)
44 | elif type == ParameterType.LIST_NEIGHBOR_LQI:
45 | for v in value:
46 | self.write_neighbor_lqi(v)
47 | else:
48 | raise TODO(
49 | "write %s, value: %s, options: %s", ParameterType(type), value, options
50 | )
51 |
52 | def write(self, value, length=1, signed=False):
53 | self.buffer += value.to_bytes(length, "little", signed=signed)
54 |
55 | def write_neighbor_lqi(self, value):
56 | for i in value["extPanId"]:
57 | self.write(i)
58 | for i in value["extAddr"]:
59 | self.write(i)
60 | self.write(value["nwkAddr"], 2)
61 | self.write(
62 | value["deviceType"]
63 | | (value["rxOnWhenIdle"] * 4)
64 | | (value["relationship"] * 16)
65 | )
66 | self.write(value["permitJoin"])
67 | self.write(value["depth"])
68 | self.write(value["lqi"])
69 |
70 | def read_parameter(self, name, type, options):
71 |
72 | if type == ParameterType.UINT8:
73 | res = self.read_int()
74 | if name.endswith("addrmode"):
75 | res = AddressMode(res)
76 | elif type == ParameterType.UINT16:
77 | res = self.read_int(2)
78 | if (
79 | name.endswith("addr")
80 | or name.endswith("address")
81 | or name.endswith("addrofinterest")
82 | ):
83 | res = zigpy.types.NWK(res)
84 | elif type == ParameterType.UINT32:
85 | res = self.read_int(4)
86 | elif type == ParameterType.IEEEADDR:
87 | res = self.read_ieee_addr()
88 | elif ParameterType.is_buffer(type):
89 | type_name = ParameterType(type).name
90 | length = int(type_name.replace("BUFFER", "") or options.length)
91 | res = self.read(length)
92 | elif type == ParameterType.INT8:
93 | res = self.read_int(signed=True)
94 | else:
95 | # list types
96 | res = []
97 | if type == ParameterType.LIST_UINT8:
98 | for i in range(0, options.length):
99 | res.append(self.read_int())
100 | elif type == ParameterType.LIST_UINT16:
101 | for i in range(0, options.length):
102 | res.append(self.read_int(2))
103 | elif type == ParameterType.LIST_NEIGHBOR_LQI:
104 | for i in range(0, options.length):
105 | res.append(self.read_neighbor_lqi())
106 | else:
107 | raise TODO("read type %d", type)
108 |
109 | return res
110 |
111 | def read_int(self, length=1, signed=False):
112 | return int.from_bytes(self.read(length), "little", signed=signed)
113 |
114 | def read(self, length=1):
115 | if self.position + length > self._len:
116 | raise OverflowError
117 | res = self.buffer[self.position : self.position + length]
118 | self.position += length
119 | return res
120 |
121 | def read_ieee_addr(self):
122 | return zigpy.types.EUI64(self.read(8))
123 |
124 | def read_neighbor_lqi(self):
125 | item = dict()
126 | item["extPanId"] = self.read_ieee_addr()
127 | item["extAddr"] = self.read_ieee_addr()
128 | item["nwkAddr"] = zigpy.types.NWK(self.read_int(2))
129 |
130 | value1 = self.read_int()
131 | item["deviceType"] = value1 & 0x03
132 | item["rxOnWhenIdle"] = (value1 & 0x0C) >> 2
133 | item["relationship"] = (value1 & 0x70) >> 4
134 |
135 | item["permitJoin"] = self.read_int() & 0x03
136 | item["depth"] = self.read_int()
137 | item["lqi"] = self.read_int()
138 |
139 | return item
140 |
--------------------------------------------------------------------------------
/zigpy_cc/config.py:
--------------------------------------------------------------------------------
1 | import voluptuous as vol
2 | from zigpy.config import ( # noqa: F401 pylint: disable=unused-import
3 | CONF_DATABASE,
4 | CONF_DEVICE,
5 | CONF_DEVICE_PATH,
6 | CONFIG_SCHEMA,
7 | cv_boolean,
8 | )
9 |
10 | CONF_DEVICE_BAUDRATE = "baudrate"
11 | CONF_DEVICE_BAUDRATE_DEFAULT = 115200
12 | CONF_FLOW_CONTROL = "flow_control"
13 | CONF_FLOW_CONTROL_DEFAULT = None
14 |
15 | SCHEMA_DEVICE = vol.Schema(
16 | {
17 | vol.Required(CONF_DEVICE_PATH): vol.Any(vol.PathExists(), "auto"),
18 | vol.Optional(CONF_DEVICE_BAUDRATE, default=CONF_DEVICE_BAUDRATE_DEFAULT): int,
19 | vol.Optional(CONF_FLOW_CONTROL, default=CONF_FLOW_CONTROL_DEFAULT): vol.In(
20 | ("hardware", "software", None)
21 | ),
22 | }
23 | )
24 |
25 | CONFIG_SCHEMA = CONFIG_SCHEMA.extend({vol.Required(CONF_DEVICE): SCHEMA_DEVICE})
26 |
--------------------------------------------------------------------------------
/zigpy_cc/const.py:
--------------------------------------------------------------------------------
1 | import enum
2 |
3 |
4 | class ResetType(enum.IntEnum):
5 | HARD = 0
6 | SOFT = 1
7 |
8 |
9 | class System:
10 | resetType = ResetType
11 |
12 |
13 | class DeviceLogicalType(enum.IntEnum):
14 | COORDINATOR = 0
15 | ROUTER = 1
16 | ENDDEVICE = 2
17 | COMPLEX_DESC_AVAIL = 4
18 | USER_DESC_AVAIL = 8
19 | RESERVED1 = 16
20 | RESERVED2 = 32
21 | RESERVED3 = 64
22 | RESERVED4 = 128
23 |
24 |
25 | class ZDO:
26 | deviceLogicalType = DeviceLogicalType
27 |
28 |
29 | class networkLatencyReq(enum.IntEnum):
30 | NO_LATENCY_REQS = 0
31 | FAST_BEACONS = 1
32 | SLOW_BEACONS = 2
33 |
34 |
35 | class AF:
36 | networkLatencyReq = networkLatencyReq
37 |
38 |
39 | class Constants:
40 | AF = AF
41 | SYS = System
42 | ZDO = ZDO
43 |
--------------------------------------------------------------------------------
/zigpy_cc/exception.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | from zigpy.exceptions import ZigbeeException
4 |
5 | LOGGER = logging.getLogger(__name__)
6 |
7 |
8 | class TODO(Exception):
9 | def __init__(self, msg, *args, **kwargs):
10 | super().__init__(msg, *args, **kwargs)
11 | LOGGER.warning("Not implemented: " + msg, *args)
12 |
13 |
14 | class CommandError(ZigbeeException):
15 | def __init__(self, status, *args, **kwargs):
16 | self._status = status
17 | super().__init__(*args, **kwargs)
18 |
19 | @property
20 | def status(self):
21 | return self._status
22 |
--------------------------------------------------------------------------------
/zigpy_cc/ha.log:
--------------------------------------------------------------------------------
1 | 020-01-02 21:27:50 INFO (MainThread) [zigpy.device] [0x2e80] Discovered endpoints: [1]
2 | 2020-01-02 21:27:50 INFO (MainThread) [zigpy.endpoint] [0x2e80:1] Discovering endpoint information
3 | Tries remaining: 3
4 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x1d request
5 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 29 under 30 request id, data: b'\x1d\x80.\x01'
6 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.api] waiting for 29 simpleDescReq
7 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.api] <-- SREQ ZDO simpleDescReq tsn: 29 {'dstaddr': 0x2e80, 'nwkaddrofinterest': 0x2e80, 'endpoint': 1}
8 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.uart] Send:
9 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
10 | 2020-01-02 21:27:50 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO simpleDescReq tsn: None {'status': 0}
11 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
12 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO simpleDescRsp tsn: None {'srcaddr': 0x2e80, 'status': 0, 'nwkaddr': 0x2e80, 'len': 32, 'endpoint': 1, 'profileid': 49246, 'deviceid': 2064, 'deviceversion': 2, 'numinclusters': 6, 'inclusterlist': [0, 1, 3, 9, 2821, 4096], 'numoutclusters': 6, 'outclusterlist': [3, 4, 6, 8, 25, 4096]}
13 | 2020-01-02 21:27:51 INFO (MainThread) [zigpy_cc.zigbee.application] REPLY for 29 simpleDescRsp
14 | 2020-01-02 21:27:51 INFO (MainThread) [zigpy_cc.zigbee.application] handle_message simpleDescRsp
15 | 2020-01-02 21:27:51 INFO (MainThread) [zigpy.endpoint] [0x2e80:1] Discovered endpoint information:
16 |
17 |
18 | 2020-01-02 21:27:51 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:ZDO](TRADFRI wireless dimmer): channel: 'async_configure' stage succeeded
19 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x21 request
20 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 33 under 34 request id, data: b"!
24 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x23 request
25 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 35 under 36 request id, data: b"#
29 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x25 request
30 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 37 under 38 request id, data: b"%
34 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
35 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO bindReq tsn: None {'status': 0}
36 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
37 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO bindReq tsn: None {'status': 0}
38 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
39 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO bindReq tsn: None {'status': 0}
40 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
41 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
42 | 2020-01-02 21:27:51 INFO (MainThread) [zigpy_cc.zigbee.application] REPLY for 37 bindRsp
43 | 2020-01-02 21:27:51 INFO (MainThread) [zigpy_cc.zigbee.application] handle_message bindRsp
44 | 2020-01-02 21:27:51 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0006]: bound 'on_off' cluster: Status.NOT_SUPPORTED
45 | 2020-01-02 21:27:51 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0006]: finished channel configuration
46 | 2020-01-02 21:27:51 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0006]: channel: 'async_configure' stage succeeded
47 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x27 request
48 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 39 under 40 request id, data: b"'
52 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
53 | 2020-01-02 21:27:51 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO bindReq tsn: None {'status': 0}
54 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
55 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
56 | 2020-01-02 21:27:52 INFO (MainThread) [zigpy_cc.zigbee.application] REPLY for 39 bindRsp
57 | 2020-01-02 21:27:52 INFO (MainThread) [zigpy_cc.zigbee.application] handle_message bindRsp
58 | 2020-01-02 21:27:52 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0008]: bound 'level' cluster: Status.NOT_SUPPORTED
59 | 2020-01-02 21:27:52 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0008]: finished channel configuration
60 | 2020-01-02 21:27:52 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0008]: channel: 'async_configure' stage succeeded
61 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x29 request
62 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 41 under 42 request id, data: b")
66 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
67 | 2020-01-02 21:27:52 DEBUG (MainThread) [zigpy_cc.api] --> SRSP ZDO bindReq tsn: None {'status': 0}
68 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
69 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
70 | 2020-01-02 21:27:53 INFO (MainThread) [zigpy_cc.zigbee.application] REPLY for 41 bindRsp
71 | 2020-01-02 21:27:53 INFO (MainThread) [zigpy_cc.zigbee.application] handle_message bindRsp
72 | 2020-01-02 21:27:53 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0000]: bound 'basic' cluster: Status.NOT_SUPPORTED
73 | 2020-01-02 21:27:53 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0000]: finished channel configuration
74 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x2b request
75 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 43 under 44 request id, data: b'\x00+\x00\x07\x00'
76 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.api] <-- SREQ AF dataRequest tsn: 43 {'dstaddr': 11904, 'destendpoint': 1, 'srcendpoint': 1, 'clusterid': 0, 'transid': 44, 'options': 0, 'radius': 30, 'len': 5, 'data': b'\x00+\x00\x07\x00'}
77 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.uart] Send:
78 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
79 | 2020-01-02 21:27:53 DEBUG (MainThread) [zigpy_cc.api] --> SRSP AF dataRequest tsn: None {'status': 0}
80 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
81 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
82 | 2020-01-02 21:27:54 WARNING (MainThread) [zigpy_cc.zigbee.application] missing tsn from bindRsp, maybe not a reply
83 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
84 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.api] --> AREQ AF dataConfirm tsn: None {'status': 240, 'endpoint': 1, 'transid': 44}
85 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
86 | 2020-01-02 21:27:54 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
87 | 2020-01-02 21:27:54 WARNING (MainThread) [zigpy_cc.zigbee.application] missing tsn from bindRsp, maybe not a reply
88 | 2020-01-02 21:27:56 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
89 | 2020-01-02 21:27:56 DEBUG (MainThread) [zigpy_cc.api] --> AREQ ZDO bindRsp tsn: None {'srcaddr': 0x2e80, 'status': 132}
90 | 2020-01-02 21:27:56 WARNING (MainThread) [zigpy_cc.zigbee.application] missing tsn from bindRsp, maybe not a reply
91 | 2020-01-02 21:28:02 DEBUG (SyncWorker_14) [homeassistant.helpers.storage] Writing data for core.device_registry
92 | 2020-01-02 21:28:11 DEBUG (MainThread) [zigpy_cc.uart] Frame received:
93 | 2020-01-02 21:28:11 DEBUG (MainThread) [zigpy_cc.api] --> AREQ AF incomingMsg tsn: None {'groupid': 49164, 'clusterid': 10, 'srcaddr': 0x19c3, 'srcendpoint': 1, 'dstendpoint': 1, 'wasbroadcast': 0, 'linkquality': 34, 'securityuse': 0, 'timestamp': 262979, 'transseqnumber': 0, 'len': 7, 'data': b'\x1c_\x11\xc7\x00\x00\x00'}
94 | 2020-01-02 21:28:11 DEBUG (MainThread) [zigpy_cc.zigbee.application] Received frame from unknown device: 0x19c3
95 | 2020-01-02 21:28:19 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x0001]: Failed to bind 'power' cluster:
96 | 2020-01-02 21:28:19 DEBUG (MainThread) [zigpy.device] [0x2e80] Extending timeout for 0x2d request
97 | 2020-01-02 21:28:19 DEBUG (MainThread) [zigpy_cc.zigbee.application] Sending Zigbee request with tsn 45 under 46 request id, data: b'\x00-\x06\x00 \x00 \x10\x0e0*\x01'
98 | 2020-01-02 21:28:19 DEBUG (MainThread) [zigpy_cc.api] <-- SREQ AF dataRequest tsn: 45 {'dstaddr': 11904, 'destendpoint': 1, 'srcendpoint': 1, 'clusterid': 0, 'transid': 46, 'options': 0, 'radius': 30, 'len': 12, 'data': b'\x00-\x06\x00 \x00 \x10\x0e0*\x01'}
99 | 2020-01-02 21:28:19 DEBUG (MainThread) [zigpy_cc.uart] Send:
100 | 2020-01-02 21:28:19 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x1000]: Failed to bind 'lightlink' cluster:
101 | 2020-01-02 21:28:19 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x1000]: finished channel configuration
102 | 2020-01-02 21:28:19 DEBUG (MainThread) [homeassistant.components.zha.core.channels] [0x2e80:1:0x1000]: channel: 'async_configure' stage succeeded
103 |
--------------------------------------------------------------------------------
/zigpy_cc/types.py:
--------------------------------------------------------------------------------
1 | import enum
2 |
3 | import zigpy.config
4 | import zigpy.types as t
5 |
6 |
7 | class Repr:
8 | def __repr__(self) -> str:
9 | r = "<%s " % (self.__class__.__name__,)
10 | r += " ".join(["%s=%s" % (f, getattr(self, f, None)) for f in vars(self)])
11 | r += ">"
12 | return r
13 |
14 |
15 | class Timeouts:
16 | SREQ = 6000
17 | reset = 30000
18 | default = 10000
19 |
20 |
21 | class AddressMode(t.uint8_t, enum.Enum):
22 | ADDR_NOT_PRESENT = 0
23 | ADDR_GROUP = 1
24 | ADDR_16BIT = 2
25 | ADDR_64BIT = 3
26 | ADDR_BROADCAST = 15
27 |
28 |
29 | class LedMode(t.uint8_t, enum.Enum):
30 | Off = 0
31 | On = 1
32 | Blink = 2
33 | Flash = 3
34 | Toggle = 4
35 |
36 |
37 | class ZnpVersion(t.uint8_t, enum.Enum):
38 | zStack12 = 0
39 | zStack3x0 = 1
40 | zStack30x = 2
41 |
42 |
43 | class CommandType(t.uint8_t, enum.Enum):
44 | POLL = 0
45 | SREQ = 1
46 | AREQ = 2
47 | SRSP = 3
48 |
49 |
50 | class Subsystem(t.uint8_t, enum.Enum):
51 | RESERVED = 0
52 | SYS = 1
53 | MAC = 2
54 | NWK = 3
55 | AF = 4
56 | ZDO = 5
57 | SAPI = 6
58 | UTIL = 7
59 | DEBUG = 8
60 | APP = 9
61 | APP_CNF = 15
62 | GREENPOWER = 21
63 |
64 |
65 | class ParameterType(t.uint8_t, enum.Enum):
66 | UINT8 = 0
67 | UINT16 = 1
68 | UINT32 = 2
69 | IEEEADDR = 3
70 |
71 | BUFFER = 4
72 | BUFFER8 = 5
73 | BUFFER16 = 6
74 | BUFFER18 = 7
75 | BUFFER32 = 8
76 | BUFFER42 = 9
77 | BUFFER100 = 10
78 |
79 | LIST_UINT8 = 11
80 | LIST_UINT16 = 12
81 | LIST_ROUTING_TABLE = 13
82 | LIST_BIND_TABLE = 14
83 | LIST_NEIGHBOR_LQI = 15
84 | LIST_NETWORK = 16
85 | LIST_ASSOC_DEV = 17
86 |
87 | INT8 = 18
88 |
89 | def is_buffer(type):
90 | return (
91 | type == ParameterType.BUFFER
92 | or type == ParameterType.BUFFER8
93 | or type == ParameterType.BUFFER16
94 | or type == ParameterType.BUFFER18
95 | or type == ParameterType.BUFFER32
96 | or type == ParameterType.BUFFER42
97 | or type == ParameterType.BUFFER100
98 | )
99 |
100 |
101 | class NetworkOptions(Repr):
102 | networkKey: t.KeyData
103 | panID: t.PanId
104 | extendedPanID: t.ExtendedPanId
105 | channelList: t.Channels
106 |
107 | def __init__(self, config: zigpy.config.SCHEMA_NETWORK) -> None:
108 | self.networkKeyDistribute = False
109 | self.networkKey = config[zigpy.config.CONF_NWK_KEY] or (
110 | zigpy.config.cv_key([1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13])
111 | )
112 | self.panID = config[zigpy.config.CONF_NWK_PAN_ID] or t.PanId(0x1A62)
113 | self.extendedPanID = config[zigpy.config.CONF_NWK_EXTENDED_PAN_ID] or (
114 | t.ExtendedPanId([0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD])
115 | )
116 | self.channelList = (
117 | config[zigpy.config.CONF_NWK_CHANNELS] or t.Channels.from_channel_list([11])
118 | )
119 |
--------------------------------------------------------------------------------
/zigpy_cc/uart.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | from typing import Any, Dict
4 |
5 | import serial
6 | import serial.tools.list_ports
7 | import serial_asyncio
8 | from serial.tools.list_ports_common import ListPortInfo
9 |
10 | from zigpy_cc.config import CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH, CONF_FLOW_CONTROL
11 | import zigpy_cc.types as t
12 |
13 | LOGGER = logging.getLogger(__name__)
14 |
15 | DataStart = 4
16 | SOF = 0xFE
17 |
18 | PositionDataLength = 1
19 | PositionCmd0 = 2
20 | PositionCmd1 = 3
21 |
22 | MinMessageLength = 5
23 | MaxDataSize = 250
24 |
25 | """
26 | 0451: Texas Instruments
27 | 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
28 | used in zzh - https://electrolama.com/projects/zig-a-zig-ah/
29 | """
30 | usb_regexp = "0451:|1a86:7523"
31 |
32 |
33 | class Parser:
34 | def __init__(self) -> None:
35 | self.buffer = b""
36 |
37 | def write(self, b: int):
38 | self.buffer += bytes([b])
39 | if SOF == self.buffer[0]:
40 | if len(self.buffer) > MinMessageLength:
41 | dataLength = self.buffer[PositionDataLength]
42 |
43 | fcsPosition = DataStart + dataLength
44 | frameLength = fcsPosition + 1
45 |
46 | if len(self.buffer) >= frameLength:
47 | frameBuffer = self.buffer[0:frameLength]
48 | self.buffer = self.buffer[frameLength:]
49 |
50 | frame = UnpiFrame.from_buffer(dataLength, fcsPosition, frameBuffer)
51 |
52 | return frame
53 | else:
54 | LOGGER.debug("drop char")
55 | self.buffer = b""
56 |
57 | return None
58 |
59 |
60 | class UnpiFrame(t.Repr):
61 | def __init__(
62 | self,
63 | command_type: int,
64 | subsystem: int,
65 | command_id: int,
66 | data: bytes,
67 | length=None,
68 | fcs=None,
69 | ):
70 | self.command_type = t.CommandType(command_type)
71 | self.subsystem = t.Subsystem(subsystem)
72 | self.command_id = command_id
73 | self.data = data
74 | self.length = length
75 | self.fcs = fcs
76 |
77 | @classmethod
78 | def from_buffer(cls, length, fcs_position, buffer):
79 | subsystem = buffer[PositionCmd0] & 0x1F
80 | command_type = (buffer[PositionCmd0] & 0xE0) >> 5
81 | command_id = buffer[PositionCmd1]
82 | data = buffer[DataStart:fcs_position]
83 | fcs = buffer[fcs_position]
84 |
85 | checksum = cls.calculate_checksum(buffer[1:fcs_position])
86 | if checksum == fcs:
87 | return cls(command_type, subsystem, command_id, data, length, fcs)
88 | else:
89 | LOGGER.warning("Invalid checksum: 0x%s, data: 0x%s", checksum, buffer)
90 | return None
91 |
92 | @staticmethod
93 | def calculate_checksum(values):
94 | checksum = 0
95 |
96 | for value in values:
97 | checksum ^= value
98 |
99 | return checksum
100 |
101 | def to_buffer(self):
102 | length = len(self.data)
103 | cmd0 = ((self.command_type << 5) & 0xE0) | (self.subsystem & 0x1F)
104 |
105 | res = bytes([SOF, length, cmd0, self.command_id])
106 | res += self.data
107 | fcs = self.calculate_checksum(res[1:])
108 |
109 | return res + bytes([fcs])
110 |
111 |
112 | class Gateway(asyncio.Protocol):
113 | _transport: serial_asyncio.SerialTransport
114 |
115 | def __init__(self, api, connected_future=None):
116 | self._parser = Parser()
117 | self._connected_future = connected_future
118 | self._api = api
119 | self._transport = None
120 | self._open = False
121 |
122 | def connection_made(self, transport: serial_asyncio.SerialTransport):
123 | """Callback when the uart is connected"""
124 | LOGGER.debug("Connection made")
125 | self._open = True
126 | self._transport = transport
127 | if self._connected_future:
128 | self._connected_future.set_result(True)
129 |
130 | def close(self):
131 | self._open = False
132 | self._transport.close()
133 |
134 | def write(self, data):
135 | self._transport.write(data)
136 |
137 | def send(self, frame: UnpiFrame):
138 | """Send data, taking care of escaping and framing"""
139 | data = frame.to_buffer()
140 | LOGGER.debug("Send: %s", data)
141 | self._transport.write(data)
142 |
143 | def data_received(self, data):
144 | """Callback when there is data received from the uart"""
145 |
146 | found = False
147 | for b in data:
148 | frame = self._parser.write(b)
149 | if frame is not None:
150 | found = True
151 | LOGGER.debug("Frame received: %s", frame)
152 | self._api.data_received(frame)
153 |
154 | if not found:
155 | LOGGER.info("Bytes received: %s", data)
156 |
157 | def connection_lost(self, exc):
158 | if self._open:
159 | LOGGER.error("Serial port closed unexpectedly: %s", exc)
160 | self._api.connection_lost()
161 |
162 |
163 | def detect_port() -> ListPortInfo:
164 | devices = list(serial.tools.list_ports.grep(usb_regexp))
165 | if len(devices) < 1:
166 | raise serial.SerialException("Unable to find TI CC device using auto mode")
167 | if len(devices) > 1:
168 | raise serial.SerialException(
169 | "Unable to select TI CC device, multiple devices found: {}".format(
170 | ", ".join(map(lambda d: str(d), devices))
171 | )
172 | )
173 | return devices[0]
174 |
175 |
176 | async def connect(config: Dict[str, Any], api, loop=None) -> Gateway:
177 | if loop is None:
178 | loop = asyncio.get_event_loop()
179 |
180 | connected_future = loop.create_future()
181 | protocol = Gateway(api, connected_future)
182 |
183 | port, baudrate = config[CONF_DEVICE_PATH], config[CONF_DEVICE_BAUDRATE]
184 | if port == "auto":
185 | device = detect_port()
186 | LOGGER.info("Auto select TI CC device: %s", device)
187 | port = device.device
188 |
189 | xonxoff, rtscts = False, False
190 | if config[CONF_FLOW_CONTROL] == "hardware":
191 | xonxoff, rtscts = False, True
192 | elif config[CONF_FLOW_CONTROL] == "software":
193 | xonxoff, rtscts = True, False
194 |
195 | LOGGER.debug("Connecting on port %s with boudrate %d", port, baudrate)
196 | _, protocol = await serial_asyncio.create_serial_connection(
197 | loop,
198 | lambda: protocol,
199 | url=port,
200 | baudrate=baudrate,
201 | parity=serial.PARITY_NONE,
202 | stopbits=serial.STOPBITS_ONE,
203 | xonxoff=xonxoff,
204 | rtscts=rtscts,
205 | )
206 |
207 | await connected_future
208 |
209 | protocol.write(b"\xef")
210 | await asyncio.sleep(1)
211 |
212 | return protocol
213 |
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zigpy/zigpy-cc/e75d1fccfcd225abf6ac93a1e215ea16b2018897/zigpy_cc/zigbee/__init__.py
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/application.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | from asyncio.locks import Semaphore
4 | from typing import Any, Dict, Optional
5 |
6 | import zigpy.application
7 | import zigpy.config
8 | import zigpy.device
9 | import zigpy.types
10 | import zigpy.util
11 | from zigpy.profiles import zha
12 | from zigpy.types import BroadcastAddress
13 | from zigpy.zdo.types import ZDOCmd
14 |
15 | from zigpy_cc import __version__, types as t
16 | from zigpy_cc.api import API
17 | from zigpy_cc.config import CONF_DEVICE, CONFIG_SCHEMA, SCHEMA_DEVICE
18 | from zigpy_cc.exception import TODO, CommandError
19 | from zigpy_cc.types import NetworkOptions, Subsystem, ZnpVersion, LedMode, AddressMode
20 | from zigpy_cc.zigbee.start_znp import start_znp
21 | from zigpy_cc.zpi_object import ZpiObject
22 |
23 | LOGGER = logging.getLogger(__name__)
24 |
25 | CHANGE_NETWORK_WAIT = 1
26 | SEND_CONFIRM_TIMEOUT = 60
27 | PROTO_VER_WATCHDOG = 0x0108
28 |
29 | REQUESTS = {
30 | "nwkAddrReq": (ZDOCmd.NWK_addr_req, 0),
31 | "ieeeAddrReq": (ZDOCmd.IEEE_addr_req, 0),
32 | "matchDescReq": (ZDOCmd.Match_Desc_req, 2),
33 | "endDeviceAnnceInd": (ZDOCmd.Device_annce, 2),
34 | "mgmtLqiRsp": (ZDOCmd.Mgmt_Lqi_rsp, 2),
35 | "mgmtPermitJoinReq": (ZDOCmd.Mgmt_Permit_Joining_req, 3),
36 | "mgmtPermitJoinRsp": (ZDOCmd.Mgmt_Permit_Joining_rsp, 2),
37 | "nodeDescRsp": (ZDOCmd.Node_Desc_rsp, 2),
38 | "activeEpRsp": (ZDOCmd.Active_EP_rsp, 2),
39 | "simpleDescRsp": (ZDOCmd.Simple_Desc_rsp, 2),
40 | "bindRsp": (ZDOCmd.Bind_rsp, 2),
41 | }
42 |
43 | IGNORED = (
44 | "bdbComissioningNotifcation",
45 | "dataConfirm",
46 | "leaveInd",
47 | "resetInd",
48 | "srcRtgInd",
49 | "stateChangeInd",
50 | "tcDeviceInd",
51 | )
52 |
53 |
54 | class ControllerApplication(zigpy.application.ControllerApplication):
55 | _semaphore: Semaphore
56 | _api: Optional[API]
57 | SCHEMA = CONFIG_SCHEMA
58 | SCHEMA_DEVICE = SCHEMA_DEVICE
59 |
60 | probe = API.probe
61 |
62 | def __init__(self, config: Dict[str, Any]):
63 | super().__init__(config=zigpy.config.ZIGPY_SCHEMA(config))
64 | self._api = None
65 |
66 | self.discovering = False
67 | self.version = {}
68 |
69 | async def shutdown(self):
70 | """Shutdown application."""
71 | self._api.close()
72 |
73 | def connection_lost(self):
74 | asyncio.create_task(self.reconnect())
75 |
76 | async def reconnect(self):
77 | while True:
78 | if self._api is not None:
79 | self._api.close()
80 | await asyncio.sleep(5)
81 | try:
82 | await self.startup(True)
83 | break
84 | except Exception as e:
85 | LOGGER.info("Failed to reconnect: %s", e)
86 | pass
87 |
88 | async def startup(self, auto_form=False):
89 | """Perform a complete application startup"""
90 |
91 | LOGGER.info("Starting zigpy-cc version: %s", __version__)
92 | self._api = await API.new(self, self._config[CONF_DEVICE])
93 |
94 | try:
95 | await self._api.request(Subsystem.SYS, "ping", {"capabilities": 1})
96 | except CommandError as e:
97 | raise Exception("Failed to connect to the adapter(%s)", e)
98 |
99 | self.version = await self._api.version()
100 |
101 | concurrent = 16 if self.version["product"] == ZnpVersion.zStack3x0 else 2
102 | LOGGER.debug("Adapter concurrent: %d", concurrent)
103 |
104 | self._semaphore = asyncio.Semaphore(concurrent)
105 |
106 | ver = ZnpVersion(self.version["product"]).name
107 | LOGGER.info("Detected znp version '%s' (%s)", ver, self.version)
108 |
109 | if auto_form:
110 | await self.form_network()
111 |
112 | data = await self._api.request(Subsystem.UTIL, "getDeviceInfo", {})
113 | self._ieee = data.payload["ieeeaddr"]
114 | self._nwk = data.payload["shortaddr"]
115 |
116 | # add coordinator
117 | self.devices[self._ieee] = Coordinator(self, self._ieee, self._nwk)
118 |
119 | async def permit_with_key(self, node, code, time_s=60):
120 | raise TODO("permit_with_key")
121 |
122 | async def force_remove(self, dev: zigpy.device.Device):
123 | """Forcibly remove device from NCP."""
124 | LOGGER.warning("FORCE REMOVE %s", dev)
125 |
126 | async def form_network(self, channel=15, pan_id=None, extended_pan_id=None):
127 | LOGGER.info("Forming network")
128 | LOGGER.debug("Config: %s", self.config)
129 | options = NetworkOptions(self.config[zigpy.config.CONF_NWK])
130 | LOGGER.debug("NetworkOptions: %s", options)
131 | backupPath = ""
132 | status = await start_znp(
133 | self._api, self.version["product"], options, 0x0B84, backupPath
134 | )
135 | LOGGER.info("ZNP started, status: %s", status)
136 |
137 | self.set_led(LedMode.Off)
138 |
139 | async def mrequest(
140 | self,
141 | group_id,
142 | profile,
143 | cluster,
144 | src_ep,
145 | sequence,
146 | data,
147 | *,
148 | hops=0,
149 | non_member_radius=3
150 | ):
151 | """Submit and send data out as a multicast transmission.
152 |
153 | :param group_id: destination multicast address
154 | :param profile: Zigbee Profile ID to use for outgoing message
155 | :param cluster: cluster id where the message is being sent
156 | :param src_ep: source endpoint id
157 | :param sequence: transaction sequence number of the message
158 | :param data: Zigbee message payload
159 | :param hops: the message will be delivered to all nodes within this number of
160 | hops of the sender. A value of zero is converted to MAX_HOPS
161 | :param non_member_radius: the number of hops that the message will be forwarded
162 | by devices that are not members of the group. A value
163 | of 7 or greater is treated as infinite
164 | :returns: return a tuple of a status and an error_message. Original requestor
165 | has more context to provide a more meaningful error message
166 | """
167 | LOGGER.debug(
168 | "multicast %s",
169 | (
170 | group_id,
171 | profile,
172 | cluster,
173 | src_ep,
174 | sequence,
175 | data,
176 | hops,
177 | non_member_radius,
178 | ),
179 | )
180 | try:
181 | obj = ZpiObject.from_cluster(
182 | group_id,
183 | profile,
184 | cluster,
185 | src_ep or 1,
186 | 0xFF,
187 | sequence,
188 | data,
189 | addr_mode=AddressMode.ADDR_GROUP,
190 | )
191 | waiter_id = None
192 | waiter = self._api.create_response_waiter(obj, sequence)
193 | if waiter:
194 | waiter_id = waiter.id
195 |
196 | async with self._semaphore:
197 | await self._api.request_raw(obj, waiter_id)
198 | """
199 | As a group command is not confirmed and thus immediately returns
200 | (contrary to network address requests) we will give the
201 | command some time to 'settle' in the network.
202 | """
203 | await asyncio.sleep(0.2)
204 |
205 | except CommandError as ex:
206 | return ex.status, "Couldn't enqueue send data multicast: {}".format(ex)
207 |
208 | return 0, "message send success"
209 |
210 | @zigpy.util.retryable_request
211 | async def request(
212 | self,
213 | device,
214 | profile,
215 | cluster,
216 | src_ep,
217 | dst_ep,
218 | sequence,
219 | data,
220 | expect_reply=True,
221 | use_ieee=False,
222 | ):
223 | LOGGER.debug(
224 | "request %s",
225 | (
226 | device.nwk,
227 | profile,
228 | cluster,
229 | src_ep,
230 | dst_ep,
231 | sequence,
232 | data,
233 | expect_reply,
234 | use_ieee,
235 | ),
236 | )
237 |
238 | try:
239 | obj = ZpiObject.from_cluster(
240 | device.nwk, profile, cluster, src_ep, dst_ep, sequence, data
241 | )
242 | waiter_id = None
243 | if expect_reply:
244 | waiter = self._api.create_response_waiter(obj, sequence)
245 | if waiter:
246 | waiter_id = waiter.id
247 |
248 | async with self._semaphore:
249 | await self._api.request_raw(obj, waiter_id)
250 |
251 | except CommandError as ex:
252 | return ex.status, "Couldn't enqueue send data request: {}".format(ex)
253 |
254 | return 0, "message send success"
255 |
256 | async def broadcast(
257 | self,
258 | profile,
259 | cluster,
260 | src_ep,
261 | dst_ep,
262 | grpid,
263 | radius,
264 | sequence,
265 | data,
266 | broadcast_address=zigpy.types.BroadcastAddress.RX_ON_WHEN_IDLE,
267 | ):
268 | LOGGER.debug(
269 | "broadcast %s",
270 | (
271 | profile,
272 | cluster,
273 | src_ep,
274 | dst_ep,
275 | grpid,
276 | radius,
277 | sequence,
278 | data,
279 | broadcast_address,
280 | ),
281 | )
282 | try:
283 | obj = ZpiObject.from_cluster(
284 | broadcast_address,
285 | profile,
286 | cluster,
287 | src_ep,
288 | dst_ep,
289 | sequence,
290 | data,
291 | radius=radius,
292 | addr_mode=AddressMode.ADDR_16BIT,
293 | )
294 |
295 | async with self._semaphore:
296 | await self._api.request_raw(obj)
297 | """
298 | As a broadcast command is not confirmed and thus immediately returns
299 | (contrary to network address requests) we will give the
300 | command some time to 'settle' in the network.
301 | """
302 | await asyncio.sleep(0.2)
303 |
304 | except CommandError as ex:
305 | return (
306 | ex.status,
307 | "Couldn't enqueue send data request for broadcast: {}".format(ex),
308 | )
309 |
310 | return 0, "broadcast send success"
311 |
312 | async def permit_ncp(self, time_s=60):
313 | assert 0 <= time_s <= 254
314 | payload = {
315 | "addrmode": AddressMode.ADDR_BROADCAST,
316 | "dstaddr": BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR,
317 | "duration": time_s,
318 | "tcsignificance": 0,
319 | }
320 | async with self._semaphore:
321 | await self._api.request(Subsystem.ZDO, "mgmtPermitJoinReq", payload)
322 |
323 | def handle_znp(self, obj: ZpiObject):
324 | if obj.command_type != t.CommandType.AREQ:
325 | return
326 |
327 | frame = obj.to_unpi_frame()
328 |
329 | nwk = obj.payload["srcaddr"] if "srcaddr" in obj.payload else None
330 | ieee = obj.payload["ieeeaddr"] if "ieeeaddr" in obj.payload else None
331 | profile_id = zha.PROFILE_ID
332 | src_ep = 0
333 | dst_ep = 0
334 | lqi = 0
335 | rssi = 0
336 |
337 | if obj.subsystem == t.Subsystem.ZDO and obj.command == "endDeviceAnnceInd":
338 | nwk = obj.payload["nwkaddr"]
339 | LOGGER.info("New device joined: 0x%04x, %s", nwk, ieee)
340 | self.handle_join(nwk, ieee, 0)
341 | obj.sequence = 0
342 |
343 | if obj.command in IGNORED:
344 | return
345 |
346 | if obj.subsystem == t.Subsystem.ZDO and obj.command == "mgmtPermitJoinRsp":
347 | self.set_led(LedMode.On)
348 |
349 | if obj.subsystem == t.Subsystem.ZDO and obj.command == "permitJoinInd":
350 | self.set_led(LedMode.Off if obj.payload["duration"] == 0 else LedMode.On)
351 | return
352 |
353 | if obj.subsystem == t.Subsystem.ZDO and obj.command in REQUESTS:
354 | if obj.sequence is None:
355 | return
356 | LOGGER.debug("REPLY for %d %s", obj.sequence, obj.command)
357 | cluster_id, prefix_length = REQUESTS[obj.command]
358 | tsn = bytes([obj.sequence])
359 | data = tsn + frame.data[prefix_length:]
360 |
361 | elif obj.subsystem == t.Subsystem.AF and (
362 | obj.command == "incomingMsg" or obj.command == "incomingMsgExt"
363 | ):
364 | # ZCL commands
365 | cluster_id = obj.payload["clusterid"]
366 | src_ep = obj.payload["srcendpoint"]
367 | dst_ep = obj.payload["dstendpoint"]
368 | data = obj.payload["data"]
369 | lqi = obj.payload["linkquality"]
370 |
371 | else:
372 | LOGGER.warning(
373 | "Unhandled message: %s %s %s",
374 | t.CommandType(obj.command_type),
375 | t.Subsystem(obj.subsystem),
376 | obj.command,
377 | )
378 | return
379 |
380 | try:
381 | if ieee:
382 | device = self.get_device(ieee=ieee)
383 | else:
384 | device = self.get_device(nwk=nwk)
385 | except KeyError:
386 | LOGGER.warning(
387 | "Received frame from unknown device: %s", ieee if ieee else nwk
388 | )
389 | return
390 |
391 | device.radio_details(lqi, rssi)
392 |
393 | LOGGER.info("handle_message %s", obj.command)
394 | self.handle_message(device, profile_id, cluster_id, src_ep, dst_ep, data)
395 |
396 | def set_led(self, mode: LedMode):
397 | if self.version["product"] != ZnpVersion.zStack3x0:
398 | try:
399 | loop = asyncio.get_event_loop()
400 | loop.create_task(
401 | self._api.request(
402 | Subsystem.UTIL, "ledControl", {"ledid": 3, "mode": mode}
403 | )
404 | )
405 | except Exception as ex:
406 | LOGGER.warning("Can't set LED: %s", ex)
407 |
408 |
409 | class Coordinator(zigpy.device.Device):
410 | """
411 | todo add endpoints?
412 | @see zStackAdapter.ts - getCoordinator
413 | """
414 |
415 | @property
416 | def manufacturer(self):
417 | return "Texas Instruments"
418 |
419 | @property
420 | def model(self):
421 | return "ZNP Coordinator"
422 |
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/backup.py:
--------------------------------------------------------------------------------
1 | from zigpy_cc.exception import TODO
2 |
3 |
4 | async def Restore(znp, backupPath, options):
5 | raise TODO("Restore")
6 |
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/common.py:
--------------------------------------------------------------------------------
1 | from zigpy.types import enum16
2 |
3 |
4 | class NvItemsIds(enum16):
5 | EXTADDR = 1
6 | BOOTCOUNTER = 2
7 | STARTUP_OPTION = 3
8 | START_DELAY = 4
9 | NIB = 33
10 | DEVICE_LIST = 34
11 | ADDRMGR = 35
12 | POLL_RATE = 36
13 | QUEUED_POLL_RATE = 37
14 | RESPONSE_POLL_RATE = 38
15 | REJOIN_POLL_RATE = 39
16 | DATA_RETRIES = 40
17 | POLL_FAILURE_RETRIES = 41
18 | STACK_PROFILE = 42
19 | INDIRECT_MSG_TIMEOUT = 43
20 | ROUTE_EXPIRY_TIME = 44
21 | EXTENDED_PAN_ID = 45
22 | BCAST_RETRIES = 46
23 | PASSIVE_ACK_TIMEOUT = 47
24 | BCAST_DELIVERY_TIME = 48
25 | NWK_MODE = 49
26 | CONCENTRATOR_ENABLE = 50
27 | CONCENTRATOR_DISCOVERY = 51
28 | CONCENTRATOR_RADIUS = 52
29 | CONCENTRATOR_RC = 54
30 | NWK_MGR_MODE = 55
31 | SRC_RTG_EXPIRY_TIME = 56
32 | ROUTE_DISCOVERY_TIME = 57
33 | NWK_ACTIVE_KEY_INFO = 58
34 | NWK_ALTERN_KEY_INFO = 59
35 | ROUTER_OFF_ASSOC_CLEANUP = 60
36 | NWK_LEAVE_REQ_ALLOWED = 61
37 | NWK_CHILD_AGE_ENABLE = 62
38 | DEVICE_LIST_KA_TIMEOUT = 63
39 | BINDING_TABLE = 65
40 | GROUP_TABLE = 66
41 | APS_FRAME_RETRIES = 67
42 | APS_ACK_WAIT_DURATION = 68
43 | APS_ACK_WAIT_MULTIPLIER = 69
44 | BINDING_TIME = 70
45 | APS_USE_EXT_PANID = 71
46 | APS_USE_INSECURE_JOIN = 72
47 | COMMISSIONED_NWK_ADDR = 73
48 | APS_NONMEMBER_RADIUS = 75
49 | APS_LINK_KEY_TABLE = 76
50 | APS_DUPREJ_TIMEOUT_INC = 77
51 | APS_DUPREJ_TIMEOUT_COUNT = 78
52 | APS_DUPREJ_TABLE_SIZE = 79
53 | DIAGNOSTIC_STATS = 80
54 | BDBNODEISONANETWORK = 85
55 | SECURITY_LEVEL = 97
56 | PRECFGKEY = 98
57 | PRECFGKEYS_ENABLE = 99
58 | SECURITY_MODE = 100
59 | SECURE_PERMIT_JOIN = 101
60 | APS_LINK_KEY_TYPE = 102
61 | APS_ALLOW_R19_SECURITY = 103
62 | IMPLICIT_CERTIFICATE = 105
63 | DEVICE_PRIVATE_KEY = 106
64 | CA_PUBLIC_KEY = 107
65 | KE_MAX_DEVICES = 108
66 | USE_DEFAULT_TCLK = 109
67 | RNG_COUNTER = 111
68 | RANDOM_SEED = 112
69 | TRUSTCENTER_ADDR = 113
70 | LEGACY_NWK_SEC_MATERIAL_TABLE_START = 117 # Valid for <= Z-Stack 3.0.x
71 | EX_NWK_SEC_MATERIAL_TABLE = 7 # Valid for >= Z-Stack 3.x.0
72 | USERDESC = 129
73 | NWKKEY = 130
74 | PANID = 131
75 | CHANLIST = 132
76 | LEAVE_CTRL = 133
77 | SCAN_DURATION = 134
78 | LOGICAL_TYPE = 135
79 | NWKMGR_MIN_TX = 136
80 | NWKMGR_ADDR = 137
81 | ZDO_DIRECT_CB = 143
82 | SCENE_TABLE = 145
83 | MIN_FREE_NWK_ADDR = 146
84 | MAX_FREE_NWK_ADDR = 147
85 | MIN_FREE_GRP_ID = 148
86 | MAX_FREE_GRP_ID = 149
87 | MIN_GRP_IDS = 150
88 | MAX_GRP_IDS = 151
89 | OTA_BLOCK_REQ_DELAY = 152
90 | SAPI_ENDPOINT = 161
91 | SAS_SHORT_ADDR = 177
92 | SAS_EXT_PANID = 178
93 | SAS_PANID = 179
94 | SAS_CHANNEL_MASK = 180
95 | SAS_PROTOCOL_VER = 181
96 | SAS_STACK_PROFILE = 182
97 | SAS_STARTUP_CTRL = 183
98 | SAS_TC_ADDR = 193
99 | SAS_TC_MASTER_KEY = 194
100 | SAS_NWK_KEY = 195
101 | SAS_USE_INSEC_JOIN = 196
102 | SAS_PRECFG_LINK_KEY = 197
103 | SAS_NWK_KEY_SEQ_NUM = 198
104 | SAS_NWK_KEY_TYPE = 199
105 | SAS_NWK_MGR_ADDR = 200
106 | SAS_CURR_TC_MASTER_KEY = 209
107 | SAS_CURR_NWK_KEY = 210
108 | SAS_CURR_PRECFG_LINK_KEY = 211
109 | LEGACY_TCLK_TABLE_START = 257 # Valid for <= Z-Stack 3.0.x
110 | LEGACY_TCLK_TABLE_END = 511 # Valid for <= Z-Stack 3.0.x
111 | EX_TCLK_TABLE = 4 # Valid for >= Z-Stack 3.0.x
112 | APS_LINK_KEY_DATA_START = 513
113 | APS_LINK_KEY_DATA_END = 767
114 | DUPLICATE_BINDING_TABLE = 768
115 | DUPLICATE_DEVICE_LIST = 769
116 | DUPLICATE_DEVICE_LIST_KA_TIMEOUT = 770
117 | ZNP_HAS_CONFIGURED_ZSTACK1 = 3840
118 | ZNP_HAS_CONFIGURED_ZSTACK3 = 96
119 |
120 |
121 | class Common:
122 | devStates = {
123 | "HOLD": 0,
124 | "INIT": 1,
125 | "NWK_DISC": 2,
126 | "NWK_JOINING": 3,
127 | "NWK_REJOIN": 4,
128 | "END_DEVICE_UNAUTH": 5,
129 | "END_DEVICE": 6,
130 | "ROUTER": 7,
131 | "COORD_STARTING": 8,
132 | "ZB_COORD": 9,
133 | "NWK_ORPHAN": 10,
134 | "INVALID_REQTYPE": 128,
135 | "DEVICE_NOT_FOUND": 129,
136 | "INVALID_EP": 130,
137 | "NOT_ACTIVE": 131,
138 | "NOT_SUPPORTED": 132,
139 | "TIMEOUT": 133,
140 | "NO_MATCH": 134,
141 | "NO_ENTRY": 136,
142 | "NO_DESCRIPTOR": 137,
143 | "INSUFFICIENT_SPACE": 138,
144 | "NOT_PERMITTED": 139,
145 | "TABLE_FULL": 140,
146 | "NOT_AUTHORIZED": 141,
147 | "BINDING_TABLE_FULL": 142,
148 | }
149 | logicalChannels = {
150 | "NONE": 0,
151 | "CH11": 11,
152 | "CH12": 12,
153 | "CH13": 13,
154 | "CH14": 14,
155 | "CH15": 15,
156 | "CH16": 16,
157 | "CH17": 17,
158 | "CH18": 18,
159 | "CH19": 19,
160 | "CH20": 20,
161 | "CH21": 21,
162 | "CH22": 22,
163 | "CH23": 23,
164 | "CH24": 24,
165 | "CH25": 25,
166 | "CH26": 26,
167 | }
168 | channelMask = {
169 | "CH11": 2048,
170 | "CH12": 4096,
171 | "CH13": 8192,
172 | "CH14": 16384,
173 | "CH15": 32768,
174 | "CH16": 65536,
175 | "CH17": 131072,
176 | "CH18": 262144,
177 | "CH19": 524288,
178 | "CH20": 1048576,
179 | "CH21": 2097152,
180 | "CH22": 4194304,
181 | "CH23": 8388608,
182 | "CH24": 16777216,
183 | "CH25": 33554432,
184 | "CH26": 67108864,
185 | "CH_ALL": 134215680,
186 | }
187 |
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/nv_items.py:
--------------------------------------------------------------------------------
1 | from zigpy.types import ExtendedPanId, Channels
2 |
3 | from zigpy_cc.types import ZnpVersion
4 | from zigpy_cc.zigbee.common import NvItemsIds
5 |
6 |
7 | class Items:
8 | @staticmethod
9 | def znpHasConfiguredInit(version):
10 | return {
11 | "id": NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK1
12 | if version == ZnpVersion.zStack12
13 | else NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK3,
14 | "len": 0x01,
15 | "initlen": 0x01,
16 | "initvalue": b"\x00",
17 | }
18 |
19 | @staticmethod
20 | def znpHasConfigured(version):
21 | return {
22 | "id": NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK1
23 | if version == ZnpVersion.zStack12
24 | else NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK3,
25 | "offset": 0x00,
26 | "len": 0x01,
27 | "value": b"\x55",
28 | }
29 |
30 | @staticmethod
31 | def panID(panID):
32 | return {
33 | "id": NvItemsIds.PANID,
34 | "len": 0x02,
35 | "offset": 0x00,
36 | "value": bytes([panID & 0xFF, (panID >> 8) & 0xFF]),
37 | }
38 |
39 | @staticmethod
40 | def extendedPanID(extendedPanID: ExtendedPanId):
41 | return {
42 | "id": NvItemsIds.EXTENDED_PAN_ID,
43 | "len": 0x08,
44 | "offset": 0x00,
45 | "value": extendedPanID.serialize(),
46 | }
47 |
48 | @staticmethod
49 | def channelList(channelList: Channels):
50 | return {
51 | "id": NvItemsIds.CHANLIST,
52 | "len": 0x04,
53 | "offset": 0x00,
54 | "value": channelList.serialize(),
55 | }
56 |
57 | @staticmethod
58 | def networkKeyDistribute(distribute):
59 | return {
60 | "id": NvItemsIds.PRECFGKEYS_ENABLE,
61 | "len": 0x01,
62 | "offset": 0x00,
63 | "value": b"\x01" if distribute else b"\x00",
64 | }
65 |
66 | @staticmethod
67 | def networkKey(key):
68 | return {
69 | # id/configid is used depending if SAPI or SYS command is executed
70 | "id": NvItemsIds.PRECFGKEY,
71 | "configid": NvItemsIds.PRECFGKEY,
72 | "len": 0x10,
73 | "offset": 0x00,
74 | "value": bytes(key),
75 | }
76 |
77 | @staticmethod
78 | def startupOption(value):
79 | return {
80 | "id": NvItemsIds.STARTUP_OPTION,
81 | "len": 0x01,
82 | "offset": 0x00,
83 | "value": bytes([value]),
84 | }
85 |
86 | @staticmethod
87 | def logicalType(value):
88 | return {
89 | "id": NvItemsIds.LOGICAL_TYPE,
90 | "len": 0x01,
91 | "offset": 0x00,
92 | "value": bytes([value]),
93 | }
94 |
95 | @staticmethod
96 | def zdoDirectCb():
97 | return {
98 | "id": NvItemsIds.ZDO_DIRECT_CB,
99 | "len": 0x01,
100 | "offset": 0x00,
101 | "value": b"\x01",
102 | }
103 |
104 | @staticmethod
105 | def tcLinkKey():
106 | return {
107 | "id": NvItemsIds.LEGACY_TCLK_TABLE_START,
108 | "offset": 0x00,
109 | "len": 0x20,
110 | # ZigBee Alliance Pre-configured TC Link Key - 'ZigBeeAlliance09'
111 | "value": bytes(
112 | [
113 | 0xFF,
114 | 0xFF,
115 | 0xFF,
116 | 0xFF,
117 | 0xFF,
118 | 0xFF,
119 | 0xFF,
120 | 0xFF,
121 | 0x5A,
122 | 0x69,
123 | 0x67,
124 | 0x42,
125 | 0x65,
126 | 0x65,
127 | 0x41,
128 | 0x6C,
129 | 0x6C,
130 | 0x69,
131 | 0x61,
132 | 0x6E,
133 | 0x63,
134 | 0x65,
135 | 0x30,
136 | 0x39,
137 | 0x00,
138 | 0x00,
139 | 0x00,
140 | 0x00,
141 | 0x00,
142 | 0x00,
143 | 0x00,
144 | 0x00,
145 | ]
146 | ),
147 | }
148 |
--------------------------------------------------------------------------------
/zigpy_cc/zigbee/start_znp.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import logging
3 | import os
4 |
5 | from zigpy.zcl.clusters.general import Ota
6 | from zigpy.zcl.clusters.security import IasZone, IasWd
7 |
8 | from zigpy_cc.api import API
9 | from zigpy_cc.const import Constants
10 | from zigpy_cc.types import NetworkOptions, Subsystem, ZnpVersion, CommandType
11 | from zigpy_cc.exception import CommandError
12 | from zigpy_cc.zigbee.backup import Restore
13 | from zigpy_cc.zigbee.common import Common
14 | from .nv_items import Items
15 |
16 | LOGGER = logging.getLogger(__name__)
17 |
18 |
19 | class Endpoint:
20 | def __init__(self, **kwargs) -> None:
21 | self.endpoint = None
22 | self.appdeviceid = 0x0005
23 | self.appdevver = 0
24 | self.appnuminclusters = 0
25 | self.appinclusterlist = []
26 | self.appnumoutclusters = 0
27 | self.appoutclusterlist = []
28 | self.latencyreq = Constants.AF.networkLatencyReq.NO_LATENCY_REQS
29 | for key, value in kwargs.items():
30 | setattr(self, key, value)
31 |
32 |
33 | Endpoints = [
34 | Endpoint(endpoint=1, appprofid=0x0104),
35 | Endpoint(endpoint=2, appprofid=0x0101),
36 | Endpoint(endpoint=3, appprofid=0x0106),
37 | Endpoint(endpoint=4, appprofid=0x0107),
38 | Endpoint(endpoint=5, appprofid=0x0108),
39 | Endpoint(endpoint=6, appprofid=0x0109),
40 | Endpoint(endpoint=8, appprofid=0x0104),
41 | Endpoint(
42 | endpoint=11,
43 | appprofid=0x0104,
44 | appdeviceid=0x0400,
45 | appnumoutclusters=2,
46 | appoutclusterlist=[IasZone.cluster_id, IasWd.cluster_id],
47 | ),
48 | # TERNCY: https://github.com/Koenkk/zigbee-herdsman/issues/82
49 | Endpoint(endpoint=0x6E, appprofid=0x0104),
50 | Endpoint(endpoint=12, appprofid=0xC05E),
51 | Endpoint(
52 | endpoint=13,
53 | appprofid=0x0104,
54 | appnuminclusters=1,
55 | appinclusterlist=[Ota.cluster_id],
56 | ),
57 | # Insta/Jung/Gira: OTA fallback EP (since it's buggy in firmware 10023202
58 | # when it tries to find a matching EP for OTA - it queries for ZLL profile,
59 | # but then contacts with HA profile)
60 | Endpoint(endpoint=47, appprofid=0x0104),
61 | Endpoint(endpoint=242, appprofid=0xA1E0),
62 | ]
63 |
64 |
65 | async def validate_item(
66 | znp: API,
67 | item,
68 | message,
69 | subsystem=Subsystem.SYS,
70 | command="osalNvRead",
71 | expected_status=None,
72 | ):
73 | result = await znp.request(subsystem, command, item, None, expected_status)
74 | if result.payload["value"] != item["value"]:
75 | msg = "Item '{}' is invalid, got '{}', expected '{}'".format(
76 | message, result.payload["value"], item["value"]
77 | )
78 | LOGGER.debug(msg)
79 | raise AssertionError(msg)
80 | else:
81 | LOGGER.debug("Item '%s' is valid", message)
82 |
83 |
84 | async def needsToBeInitialised(znp: API, version, options):
85 | try:
86 | await validate_item(
87 | znp,
88 | Items.znpHasConfigured(version),
89 | "hasConfigured",
90 | expected_status=[0, 2],
91 | )
92 | await validate_item(znp, Items.channelList(options.channelList), "channelList")
93 | await validate_item(
94 | znp,
95 | Items.networkKeyDistribute(options.networkKeyDistribute),
96 | "networkKeyDistribute",
97 | )
98 |
99 | if version == ZnpVersion.zStack3x0:
100 | await validate_item(znp, Items.networkKey(options.networkKey), "networkKey")
101 | else:
102 | await validate_item(
103 | znp,
104 | Items.networkKey(options.networkKey),
105 | "networkKey",
106 | Subsystem.SAPI,
107 | "readConfiguration",
108 | )
109 |
110 | try:
111 | await validate_item(znp, Items.panID(options.panID), "panID")
112 | await validate_item(
113 | znp, Items.extendedPanID(options.extendedPanID), "extendedPanID"
114 | )
115 | except AssertionError as e:
116 | if version == ZnpVersion.zStack30x or version == ZnpVersion.zStack3x0:
117 | # When the panID has never been set, it will be [0xFF, 0xFF].
118 | result = await znp.request(
119 | Subsystem.SYS, "osalNvRead", Items.panID(options.panID)
120 | )
121 | LOGGER.debug("PANID: %s", result.payload["value"])
122 | if result.payload["value"] == bytes([0xFF, 0xFF]):
123 | LOGGER.debug("Skip enforcing panID because a random panID is used")
124 | else:
125 | raise e
126 |
127 | return False
128 | except AssertionError as e:
129 | LOGGER.debug("Error while validating items: %s", e)
130 | return True
131 |
132 |
133 | async def boot(znp: API):
134 | result = await znp.request(Subsystem.UTIL, "getDeviceInfo", {})
135 |
136 | if result.payload["devicestate"] != Common.devStates["ZB_COORD"]:
137 | LOGGER.debug("Start ZNP as coordinator...")
138 | started = znp.wait_for(
139 | CommandType.AREQ, Subsystem.ZDO, "stateChangeInd", {"state": 9}, 60000
140 | )
141 | await znp.request(
142 | Subsystem.ZDO, "startupFromApp", {"startdelay": 100}, None, [0, 1]
143 | )
144 | await started.wait()
145 | LOGGER.info("ZNP started as coordinator")
146 | else:
147 | LOGGER.info("ZNP is already started as coordinator")
148 |
149 |
150 | async def registerEndpoints(znp: API):
151 | LOGGER.debug("Register endpoints...")
152 |
153 | active_ep_response = znp.wait_for(CommandType.AREQ, Subsystem.ZDO, "activeEpRsp")
154 | asyncio.create_task(
155 | znp.request(
156 | Subsystem.ZDO, "activeEpReq", {"dstaddr": 0, "nwkaddrofinterest": 0}
157 | )
158 | )
159 | active_ep = await active_ep_response.wait()
160 |
161 | for endpoint in Endpoints:
162 | if endpoint.endpoint in active_ep.payload["activeeplist"]:
163 | LOGGER.debug("Endpoint '%s' already registered", endpoint.endpoint)
164 | else:
165 | LOGGER.debug("Registering endpoint '%s'", endpoint.endpoint)
166 | await znp.request(Subsystem.AF, "register", vars(endpoint))
167 |
168 |
169 | async def initialise(znp: API, version, options: NetworkOptions):
170 | await znp.request(Subsystem.SYS, "resetReq", {"type": Constants.SYS.resetType.SOFT})
171 | await znp.request(Subsystem.SYS, "osalNvWrite", Items.startupOption(0x02))
172 | await znp.request(Subsystem.SYS, "resetReq", {"type": Constants.SYS.resetType.SOFT})
173 | await znp.request(
174 | Subsystem.SYS,
175 | "osalNvWrite",
176 | Items.logicalType(Constants.ZDO.deviceLogicalType.COORDINATOR),
177 | )
178 | await znp.request(
179 | Subsystem.SYS,
180 | "osalNvWrite",
181 | Items.networkKeyDistribute(options.networkKeyDistribute),
182 | )
183 | await znp.request(Subsystem.SYS, "osalNvWrite", Items.zdoDirectCb())
184 | await znp.request(
185 | Subsystem.SYS, "osalNvWrite", Items.channelList(options.channelList)
186 | )
187 | await znp.request(Subsystem.SYS, "osalNvWrite", Items.panID(options.panID))
188 | await znp.request(
189 | Subsystem.SYS, "osalNvWrite", Items.extendedPanID(options.extendedPanID)
190 | )
191 |
192 | if version == ZnpVersion.zStack30x or version == ZnpVersion.zStack3x0:
193 | await znp.request(
194 | Subsystem.SYS, "osalNvWrite", Items.networkKey(options.networkKey)
195 | )
196 |
197 | # Default link key is already OK for Z-Stack 3 ('ZigBeeAlliance09')
198 | await znp.request(
199 | Subsystem.APP_CNF,
200 | "bdbSetChannel",
201 | {"isPrimary": 0x1, "channel": options.channelList},
202 | )
203 | await znp.request(
204 | Subsystem.APP_CNF, "bdbSetChannel", {"isPrimary": 0x0, "channel": 0x0}
205 | )
206 |
207 | started = znp.wait_for(
208 | CommandType.AREQ, Subsystem.ZDO, "stateChangeInd", {"state": 9}, 60000
209 | )
210 | await znp.request(Subsystem.APP_CNF, "bdbStartCommissioning", {"mode": 0x04})
211 | try:
212 | await started.wait()
213 | except Exception:
214 | raise Exception(
215 | "Coordinator failed to start, probably the panID is already in use, "
216 | "try a different panID or channel"
217 | )
218 |
219 | await znp.request(Subsystem.APP_CNF, "bdbStartCommissioning", {"mode": 0x02})
220 | else:
221 | await znp.request(
222 | Subsystem.SAPI, "writeConfiguration", Items.networkKey(options.networkKey)
223 | )
224 | await znp.request(Subsystem.SYS, "osalNvWrite", Items.tcLinkKey())
225 |
226 | # expect status code 9 (= item created and initialized)
227 | await znp.request(
228 | Subsystem.SYS,
229 | "osalNvItemInit",
230 | Items.znpHasConfiguredInit(version),
231 | None,
232 | [0, 9],
233 | )
234 | await znp.request(Subsystem.SYS, "osalNvWrite", Items.znpHasConfigured(version))
235 |
236 |
237 | async def addToGroup(znp: API, endpoint: int, group: int):
238 | result = await znp.request(
239 | Subsystem.ZDO,
240 | "extFindGroup",
241 | {"endpoint": endpoint, "groupid": group},
242 | None,
243 | [0, 1],
244 | )
245 | if result.payload["status"] == 1:
246 | await znp.request(
247 | Subsystem.ZDO,
248 | "extAddGroup",
249 | {
250 | "endpoint": endpoint,
251 | "groupid": group,
252 | "namelen": 0,
253 | "groupname": bytes([]),
254 | },
255 | )
256 |
257 |
258 | async def start_znp(
259 | znp: API, version, options: NetworkOptions, greenPowerGroup: int, backupPath=""
260 | ):
261 | result = "resumed"
262 |
263 | try:
264 | await validate_item(
265 | znp,
266 | Items.znpHasConfigured(version),
267 | "hasConfigured",
268 | expected_status=[0, 2],
269 | )
270 | hasConfigured = True
271 | except (AssertionError, CommandError):
272 | hasConfigured = False
273 |
274 | if backupPath and os.path.exists(backupPath) and not hasConfigured:
275 | LOGGER.debug("Restoring coordinator from backup")
276 | await Restore(znp, backupPath, options)
277 | result = "restored"
278 | elif await needsToBeInitialised(znp, version, options):
279 | LOGGER.debug("Initialize coordinator")
280 | await initialise(znp, version, options)
281 |
282 | if version == ZnpVersion.zStack12:
283 | # zStack12 allows to restore a network without restoring a backup
284 | # (as long as the network key, panID and channel don't change).
285 | # If the device has not been configured yet we assume that this is the case.
286 | # If we always return 'reset'
287 | # the controller clears the database on a reflash of the stick.
288 | result = "reset" if hasConfigured else "restored"
289 | else:
290 | result = "reset"
291 |
292 | await boot(znp)
293 | await registerEndpoints(znp)
294 |
295 | # Add to required group to receive greenPower messages.
296 | await addToGroup(znp, 242, greenPowerGroup)
297 |
298 | if result == "restored":
299 | # Write channel list again, otherwise it doesnt seem to stick.
300 | await znp.request(
301 | Subsystem.SYS, "osalNvWrite", Items.channelList(options.channelList)
302 | )
303 |
304 | return result
305 |
--------------------------------------------------------------------------------
/zigpy_cc/zpi_object.py:
--------------------------------------------------------------------------------
1 | from zigpy.profiles import zha
2 | from zigpy.types import BroadcastAddress
3 |
4 | from zigpy_cc import uart
5 | from zigpy_cc.buffalo import Buffalo, BuffaloOptions
6 | from zigpy_cc.definition import Definition
7 | from zigpy_cc.types import CommandType, ParameterType, Subsystem, AddressMode
8 |
9 | BufferAndListTypes = [
10 | ParameterType.BUFFER,
11 | ParameterType.BUFFER8,
12 | ParameterType.BUFFER16,
13 | ParameterType.BUFFER18,
14 | ParameterType.BUFFER32,
15 | ParameterType.BUFFER42,
16 | ParameterType.BUFFER100,
17 | ParameterType.LIST_UINT16,
18 | ParameterType.LIST_ROUTING_TABLE,
19 | ParameterType.LIST_BIND_TABLE,
20 | ParameterType.LIST_NEIGHBOR_LQI,
21 | ParameterType.LIST_NETWORK,
22 | ParameterType.LIST_ASSOC_DEV,
23 | ParameterType.LIST_UINT8,
24 | ]
25 |
26 |
27 | class ZpiObject:
28 | def __init__(
29 | self,
30 | command_type,
31 | subsystem,
32 | command: str,
33 | command_id,
34 | payload,
35 | parameters,
36 | sequence=None,
37 | ):
38 | self.command_type = CommandType(command_type)
39 | self.subsystem = Subsystem(subsystem)
40 | self.command = command
41 | self.command_id = command_id
42 | self.payload = payload
43 | self.parameters = parameters
44 | self.sequence = sequence
45 |
46 | def is_reset_command(self):
47 | return (self.command == "resetReq" and self.subsystem == Subsystem.SYS) or (
48 | self.command == "systemReset" and self.subsystem == Subsystem.SAPI
49 | )
50 |
51 | def to_unpi_frame(self):
52 | data = Buffalo(b"")
53 |
54 | for p in self.parameters:
55 | value = self.payload[p["name"]]
56 | data.write_parameter(p["parameterType"], value, {})
57 |
58 | return uart.UnpiFrame(
59 | self.command_type, self.subsystem, self.command_id, data.buffer
60 | )
61 |
62 | @classmethod
63 | def from_command(cls, subsystem, command, payload):
64 | cmd = next(c for c in Definition[subsystem] if c["name"] == command)
65 | parameters = (
66 | cmd["response"] if cmd["type"] == CommandType.SRSP else cmd["request"]
67 | )
68 |
69 | return cls(cmd["type"], subsystem, cmd["name"], cmd["ID"], payload, parameters)
70 |
71 | @classmethod
72 | def from_unpi_frame(cls, frame):
73 | cmd = next(
74 | c for c in Definition[frame.subsystem] if c["ID"] == frame.command_id
75 | )
76 | parameters = (
77 | cmd["response"]
78 | if frame.command_type == CommandType.SRSP
79 | else cmd["request"]
80 | )
81 | payload = cls.read_parameters(frame.data, parameters)
82 |
83 | return cls(
84 | frame.command_type,
85 | frame.subsystem,
86 | cmd["name"],
87 | cmd["ID"],
88 | payload,
89 | parameters,
90 | )
91 |
92 | @classmethod
93 | def from_cluster(
94 | cls,
95 | nwk,
96 | profile,
97 | cluster,
98 | src_ep,
99 | dst_ep,
100 | sequence,
101 | data,
102 | *,
103 | radius=30,
104 | addr_mode=None
105 | ):
106 | if profile == zha.PROFILE_ID:
107 | subsystem = Subsystem.AF
108 | if addr_mode is None:
109 | cmd = next(c for c in Definition[subsystem] if c["ID"] == 1)
110 | else:
111 | cmd = next(c for c in Definition[subsystem] if c["ID"] == 2)
112 | else:
113 | subsystem = Subsystem.ZDO
114 | cmd = next(c for c in Definition[subsystem] if c["ID"] == cluster)
115 | name = cmd["name"]
116 | parameters = (
117 | cmd["response"] if cmd["type"] == CommandType.SRSP else cmd["request"]
118 | )
119 |
120 | if name == "dataRequest":
121 | payload = {
122 | "dstaddr": int(nwk),
123 | "destendpoint": dst_ep,
124 | "srcendpoint": src_ep,
125 | "clusterid": cluster,
126 | "transid": sequence,
127 | "options": 0,
128 | "radius": radius,
129 | "len": len(data),
130 | "data": data,
131 | }
132 | elif name == "dataRequestExt":
133 | payload = {
134 | "dstaddrmode": addr_mode,
135 | "dstaddr": nwk,
136 | "destendpoint": dst_ep,
137 | "dstpanid": 0,
138 | "srcendpoint": src_ep,
139 | "clusterid": cluster,
140 | "transid": sequence,
141 | "options": 0,
142 | "radius": radius,
143 | "len": len(data),
144 | "data": data,
145 | }
146 | elif name == "mgmtPermitJoinReq":
147 | addrmode = (
148 | AddressMode.ADDR_BROADCAST
149 | if nwk == BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR
150 | else AddressMode.ADDR_16BIT
151 | )
152 | payload = cls.read_parameters(
153 | bytes([addrmode]) + nwk.to_bytes(2, "little") + data[1:], parameters
154 | )
155 | else:
156 | # TODO
157 | # assert sequence == data[0]
158 | payload = cls.read_parameters(
159 | nwk.to_bytes(2, "little") + data[1:], parameters
160 | )
161 |
162 | return cls(
163 | cmd["type"], subsystem, name, cmd["ID"], payload, parameters, sequence
164 | )
165 |
166 | @classmethod
167 | def read_parameters(cls, data: bytes, parameters):
168 | # print(parameters)
169 | buffalo = Buffalo(data)
170 | res = {}
171 | length = None
172 | start_index = None
173 | for p in parameters:
174 | options = BuffaloOptions()
175 | name = p["name"]
176 | param_type = p["parameterType"]
177 | if param_type in BufferAndListTypes:
178 | if isinstance(length, int):
179 | options.length = length
180 |
181 | if param_type == ParameterType.LIST_ASSOC_DEV:
182 | if isinstance(start_index, int):
183 | options.startIndex = start_index
184 |
185 | res[name] = buffalo.read_parameter(name, param_type, options)
186 |
187 | # For LIST_ASSOC_DEV, we need to grab the start_index which is
188 | # right before the length
189 | start_index = length
190 | # When reading a buffer, assume that the previous parsed parameter
191 | # contains the length of the buffer
192 | length = res[name]
193 |
194 | return res
195 |
196 | def __repr__(self) -> str:
197 | command_type = CommandType(self.command_type).name
198 | subsystem = Subsystem(self.subsystem).name
199 | return "{} {} {} tsn: {} {}".format(
200 | command_type, subsystem, self.command, self.sequence, self.payload
201 | )
202 |
--------------------------------------------------------------------------------