├── .dockerignore
├── .github
└── workflows
│ ├── build_test.yml
│ └── publish.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── c3
├── __init__.py
├── consts.py
├── controldevice.py
├── core.py
├── crc.py
├── rtlog.py
└── utils.py
├── cli
├── C3_CancelAlarms.py
├── C3_Discover.py
├── C3_GetDeviceData.py
├── C3_GetDeviceParam.py
├── C3_GetRTLog.py
├── C3_OutputOperation.py
└── C3_SetDeviceDatetime.py
├── pyproject.toml
├── readme.md
├── requirements-dev.txt
├── setup.py
└── tests
├── test_consts.py
├── test_controldevice.py
├── test_core.py
├── test_crc16.py
├── test_rtlog.py
└── test_utils.py
/.dockerignore:
--------------------------------------------------------------------------------
1 | # General files
2 | .git
3 | .github
4 | config
5 | docs
6 |
7 | # Development
8 | .devcontainer
9 | .vscode
10 | .idea
11 |
12 | # Other virtualization methods
13 | .venv
14 | .vagrant
15 |
16 | # Temporary files
17 | **/__pycache__
18 | .pytest_cache
19 | *.egg-info
20 |
--------------------------------------------------------------------------------
/.github/workflows/build_test.yml:
--------------------------------------------------------------------------------
1 | name: Build and test Python package
2 |
3 | on: [push]
4 |
5 | env:
6 | PYTHONPATH: "."
7 |
8 | jobs:
9 | build:
10 |
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
15 |
16 | steps:
17 | - name: Checkout the repository
18 | uses: actions/checkout@v4
19 |
20 | - name: Set up Python ${{ matrix.python-version }}
21 | uses: actions/setup-python@v5
22 | with:
23 | python-version: ${{ matrix.python-version }}
24 |
25 | - name: Install requirements
26 | run: python3 -m pip install -r requirements-dev.txt
27 |
28 | - name: Run isort
29 | run: python3 -m isort --check --profile black C3 cli tests
30 |
31 | - name: "Run Black"
32 | run: python3 -m black --check c3 cli tests
33 |
34 | #- name: "Run Ruff"
35 | # run: python3 -m ruff check -q c3 cli tests
36 |
37 | - name: Test with pytest
38 | run: |
39 | pip install pytest pytest-cov
40 | pytest --junitxml=junit/test-results-${{ matrix.python-version }}.xml --cov=c3 --cov-report=xml --cov-report=html
41 |
42 | - name: Upload pytest test results
43 | uses: actions/upload-artifact@v4
44 | with:
45 | name: pytest-results-${{ matrix.python-version }}
46 | path: junit/test-results-${{ matrix.python-version }}.xml
47 | # Use always() to always run this step to publish test results when there are test failures
48 | if: ${{ always() }}
49 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python Package on PyPi
2 |
3 | on:
4 | release:
5 | types: [published]
6 |
7 | jobs:
8 | deploy:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - uses: actions/checkout@v4
12 | - name: Set up Python
13 | uses: actions/setup-python@v5
14 | with:
15 | python-version: '3.x'
16 | - name: Install dependencies
17 | run: |
18 | python -m pip install --upgrade pip
19 | pip install build setuptools
20 | - name: Build package
21 | run: python -m build
22 | - name: Publish package
23 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
24 | with:
25 | user: __token__
26 | password: ${{ secrets.PYPI_API_TOKEN }}
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # IntelliJ IDEA
2 | .idea
3 |
4 | # pytest
5 | .pytest_cache
6 | .cache
7 | __pycache__
8 |
9 | # Packages
10 | *.egg
11 | *.egg-info
12 | dist
13 | build
14 | eggs
15 | .eggs
16 | parts
17 | bin
18 | var
19 | sdist
20 | develop-eggs
21 | .installed.cfg
22 | lib
23 | lib64
24 | pip-wheel-metadata
25 |
26 | # Logs
27 | *.log
28 | pip-log.txt
29 |
30 | # Unit test / coverage reports
31 | .coverage
32 | coverage.xml
33 | nosetests.xml
34 | htmlcov/
35 | test-reports/
36 | test-results.xml
37 | test-output.xml
38 |
39 | # Mr Developer
40 | .project
41 | .pydevproject
42 |
43 | .python-version
44 |
45 | # emacs auto backups
46 | *~
47 | *#
48 | *.orig
49 |
50 | # venv stuff
51 | pyvenv.cfg
52 | pip-selfcheck.json
53 | venv
54 | .venv
55 |
56 | # Visual Studio Code
57 | .vscode/*
58 | !.vscode/cSpell.json
59 | !.vscode/extensions.json
60 | !.vscode/tasks.json
61 | .env
62 |
63 | # Built docs
64 | docs/build
65 |
66 | # Windows Explorer
67 | desktop.ini
68 |
69 | # mypy
70 | /.mypy_cache/*
71 | /.dmypy.json
72 | /.pypirc
73 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG PYTHON_VERSION=3.10
2 |
3 | FROM python:$PYTHON_VERSION
4 |
5 | RUN pip install --no-cache-dir pytest \
6 | pylint \
7 | pytest-cov \
8 | build \
9 | setuptools \
10 | twine \
11 | isort
12 |
13 | WORKDIR /github/workspace
14 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | prune */__pycache__
2 | exclude .github/**/* Dockerfile .dockerignore .gitignore
3 |
--------------------------------------------------------------------------------
/c3/__init__.py:
--------------------------------------------------------------------------------
1 | """ZKAccess C3 library"""
2 | from . import controldevice, rtlog
3 | from .core import C3
4 |
5 | VERSION = (0, 0, 1)
6 |
7 | __all__ = ["C3", "controldevice", "rtlog"]
8 |
--------------------------------------------------------------------------------
/c3/consts.py:
--------------------------------------------------------------------------------
1 | from enum import IntEnum, unique
2 |
3 | # from collections import namedtuple
4 |
5 | # Defaults
6 | C3_PORT_DEFAULT = 4370
7 | C3_PORT_BROADCAST = 65535
8 |
9 | # Protocol commands
10 | C3_MESSAGE_START = 0xAA
11 | C3_MESSAGE_END = 0x55
12 | C3_PROTOCOL_VERSION = 0x01
13 | C3_DISCOVERY_MESSAGE = "CallSecurityDevice"
14 |
15 |
16 | class Command(IntEnum):
17 | """Enumeration of supported device_name interaction commands"""
18 |
19 | CONNECT_SESSION_LESS = 0x01
20 | DISCONNECT = 0x02
21 | DATETIME = 0x03
22 | GETPARAM = 0x04
23 | CONTROL = 0x05
24 | DATATABLE_CFG = 0x06
25 | GETDATA = 0x08
26 | RTLOG_BINARY = 0x0B
27 | DISCOVER = 0x14
28 | CONNECT_SESSION = 0x76
29 | RTLOG_KEYVALUE = 0x79
30 |
31 |
32 | C3_REPLY_OK = 0xC8
33 | C3_REPLY_ERROR = 0xC9
34 |
35 |
36 | Errors = {
37 | -13: "Command error: This command is not available",
38 | -14: "The communication password is not correct",
39 | }
40 |
41 |
42 | @unique
43 | class _IntEnumWithDescription(IntEnum):
44 | def __new__(cls, *args):
45 | obj = int.__new__(cls, args[0])
46 | obj._value_ = args[0]
47 | return obj
48 |
49 | # ignore the first param since it's already set by __new__
50 | def __init__(self, _: str, description: str = None):
51 | self._description_ = description
52 |
53 | def __str__(self):
54 | return str(self.value)
55 |
56 | def __repr__(self):
57 | return self._description_
58 |
59 | # this makes sure that the description is read-only
60 | @property
61 | def description(self):
62 | return self._description_
63 |
64 |
65 | # Control operations
66 | class ControlOperation(_IntEnumWithDescription):
67 | OUTPUT = 1, "Output operation (door or auxiliary)"
68 | CANCEL_ALARM = 2, "Cancel alarm"
69 | RESTART_DEVICE = 3, "Restart Device"
70 | ENDIS_NO_STATE = 4, "Enable/disable normal open state"
71 |
72 |
73 | class ControlOutputAddress(_IntEnumWithDescription):
74 | DOOR_OUTPUT = 1, "Door output"
75 | AUX_OUTPUT = 2, "Auxiliary output"
76 |
77 |
78 | class DoorSensorType(_IntEnumWithDescription):
79 | NONE = 0, "Not available"
80 | NORMAL_OPEN = 1, "Normal open"
81 | NORMAL_CLOSE = 2, "Normal close"
82 |
83 |
84 | # Event values
85 | class VerificationMode(_IntEnumWithDescription):
86 | NONE = 0, "None"
87 | FINGER = 1, "Only finger"
88 | PASSWORD = 3, "Only password"
89 | CARD = 4, "Only card"
90 | CARD_OR_FINGER = 6, "Card or finger"
91 | CARD_WITH_FINGER = 10, "Card and finger"
92 | CARD_WITH_PASSWORD = 11, "Card and password"
93 | OTHER = 200, "Others"
94 |
95 |
96 | class EventType(_IntEnumWithDescription):
97 | NA = -1, "N/A"
98 | NORMAL_PUNCH_OPEN = 0, "Normal Punch Open"
99 | PUNCH_NORMAL_OPEN_TZ = 1, "Punch during Normal Open Time Zone"
100 | FIRST_CARD_NORMAL_OPEN = 2, "First Card Normal Open (Punch Card)"
101 | MULTI_CARD_OPEN = 3, "Multi-Card Open (Punching Card)"
102 | EMERGENCY_PASS_OPEN = 4, "Emergency Password Open"
103 | OPEN_NORMAL_OPEN_TZ = 5, "Open during Normal Open Time Zone"
104 | LINKAGE_EVENT_TRIGGER = 6, "Linkage Event Triggered"
105 | CANCEL_ALARM = 7, "Cancel Alarm"
106 | REMOTE_OPENING = 8, "Remote Opening"
107 | REMOTE_CLOSING = 9, "Remote Closing"
108 | DISABLE_INTRADAY_NORMAL_OPEN_TZ = 10, "Disable Intraday Normal Open Time Zone"
109 | ENABLE_INTRADAY_NORMAL_OPEN_TZ = 11, "Enable Intraday Normal Open Time Zone"
110 | OPEN_AUX_OUTPUT = 12, "Open Auxiliary Output"
111 | CLOSE_AUX_OUTPUT = 13, "Close Auxiliary Output"
112 | PRESS_FINGER_OPEN = 14, "Press Fingerprint Open"
113 | MULTI_CARD_OPEN_FP = 15, "Multi-Card Open (Press Fingerprint)"
114 | FP_NORMAL_OPEN_TZ = 16, "Press Fingerprint during Normal Open Time Zone"
115 | CARD_FP_OPEN = 17, "Card plus Fingerprint Open"
116 | FIRST_CARD_NORMAL_OPEN_FP = 18, "First Card Normal Open (Press Fingerprint)"
117 | FIRST_CARD_NORMAL_OPEN_CARD_FP = (
118 | 19,
119 | "First Card Normal Open (Card plus Fingerprint)",
120 | )
121 | TOO_SHORT_PUNCH_INTERVAL = 20, "Too Short Punch Interval"
122 | DOOR_INACTIVE_TZ = 21, "Door Inactive Time Zone (Punch Card)"
123 | ILLEGAL_TZ = 22, "Illegal Time Zone"
124 | ACCESS_DENIED = 23, "Access Denied"
125 | ANTI_PASSBACK = 24, "Anti-Passback"
126 | INTERLOCK = 25, "Interlock"
127 | MULTI_CARD_AUTH = 26, "Multi-Card Authentication (Punching Card)"
128 | UNREGISTERED_CARD = 27, "Unregistered Card"
129 | OPENING_TIMEOUT = 28, "Opening Timeout:"
130 | CARD_EXPIRED = 29, "Card Expired"
131 | PASSWORD_ERROR = 30, "Password Error"
132 | TOO_SHORT_FP_INTERVAL = 31, "Too Short Fingerprint Pressing Interval"
133 | MULTI_CARD_AUTH_FP = 32, "Multi-Card Authentication (Press Fingerprint)"
134 | FP_EXPIRED = 33, "Fingerprint Expired"
135 | UNREGISTERED_FP = 34, "Unregistered Fingerprint"
136 | DOOR_INACTIVE_TZ_FP = 35, "Door Inactive Time Zone (Press Fingerprint)"
137 | DOOR_INACTIVE_TZ_EXIT = 36, "Door Inactive Time Zone (Exit Button)"
138 | FAILED_CLOSE_NORMAL_OPEN_TZ = 37, "Failed to Close during Normal Open Time Zone"
139 | VERIFY_TYPE_INVALID = 41, "Verify Type Invalid"
140 | WG_FORMAT_ERROR = 42, "WG Format Error"
141 | DURESS_PASSWORD_OPEN = 101, "Duress Password Open"
142 | OPENED_ACCIDENT = 102, "Opened Accidentally"
143 | DURESS_FP_OPEN = 103, "Duress Fingerprint Open"
144 | DOOR_OPENED_CORRECT = 200, "Door Opened Correctly"
145 | DOOR_CLOSED_CORRECT = 201, "Door Closed Correctly"
146 | EXIT_BUTTON_OPEN = 202, "Exit button Open"
147 | MULTI_CARD_OPEN_CARD_FP = 203, "Multi-Card Open (Card plus Fingerprint)"
148 | NORMAL_OPEN_TZ_OVER = 204, "Normal Open Time Zone Over"
149 | REMOTE_NORMAL_OPEN = 205, "Remote Normal Opening"
150 | DEVICE_START = 206, "Device Start"
151 | DOOR_OPEN_BY_SUPERUSER = 208, "Door Opened by Superuser"
152 | AUX_INPUT_DISCONNECT = 220, "Auxiliary Input Disconnected"
153 | AUX_INPUT_SHORT = 221, "Auxiliary Input Shorted"
154 | DOOR_ALARM_STATUS = 255, "Current door and alarm status"
155 | UNKNOWN_UNSUPPORTED = 999, "Unknown"
156 |
157 |
158 | class InOutDirection(_IntEnumWithDescription):
159 | ENTRY = 0, "Entry"
160 | EXIT = 3, "Exit"
161 | NONE = 2, "None"
162 | UNKNOWN_UNSUPPORTED = 15, "Unknown"
163 |
164 |
165 | class AlarmStatus(_IntEnumWithDescription):
166 | NONE = 0, "None"
167 | ALARM = 1, "Alarm"
168 | DOOR_OPEN_TIMEOUT = 2, "Door opening timeout"
169 |
170 |
171 | class InOutStatus(_IntEnumWithDescription):
172 | UNKNOWN = 0, "Unknown"
173 | CLOSED = 1, "Closed"
174 | OPEN = 2, "Open"
175 |
176 |
177 | # ParameterStruct = namedtuple("read" , "write")
178 | # ParameterAccess = dict(
179 | # "~SerialNumber" = ParameterStruct(True, False),
180 | # "LockCount" = ParameterStruct(True, False),
181 | # "ReaderCount" = ParameterStruct(True, False),
182 | # "AuxInCount" = ParameterStruct(True, False),
183 | # "AuxOutCount" = ParameterStruct(True, False),
184 | # "ComPwd" = ParameterStruct(True, True),
185 | # "IPAddress" = ParameterStruct(True, True),
186 | # "GATEIPAddress" = ParameterStruct(True, True),
187 | # "RS232BaudRate" = ParameterStruct(True, True),
188 | # "NetMask" = ParameterStruct(True, True),
189 | # "AntiPassback" = ParameterStruct(True, True),
190 | # "InterLock" = ParameterStruct(True, True),
191 | # "Door1ForcePassWord" = ParameterStruct(True, True),
192 | # "Door2ForcePassWord" = ParameterStruct(True, True),
193 | # "Door3ForcePassWord" = ParameterStruct(True, True),
194 | # "Door4ForcePassWord" = ParameterStruct(True, True),
195 | # "Door1SupperPassWord" = ParameterStruct(True, True),
196 | # "Door2SupperPassWord" = ParameterStruct(True, True),
197 | # "Door3SupperPassWord" = ParameterStruct(True, True),
198 | # "Door4SupperPassWord" = ParameterStruct(True, True),
199 | # "Door1CloseAndLock" = ParameterStruct(True, True),
200 | # "Door2CloseAndLock" = ParameterStruct(True, True),
201 | # "Door3CloseAndLock" = ParameterStruct(True, True),
202 | # "Door4CloseAndLock" = ParameterStruct(True, True),
203 | # "Door1SensorType" = ParameterStruct(True, True),
204 | # "Door2SensorType" = ParameterStruct(True, True),
205 | # "Door3SensorType" = ParameterStruct(True, True),
206 | # "Door4SensorType" = ParameterStruct(True, True),
207 | # "Door1Drivertime" = ParameterStruct(True, True),
208 | # "Door2Drivertime" = ParameterStruct(True, True),
209 | # "Door3Drivertime" = ParameterStruct(True, True),
210 | # "Door4Drivertime" = ParameterStruct(True, True),
211 | # "Door1Detectortime" = ParameterStruct(True, True),
212 | # "Door2Detectortime" = ParameterStruct(True, True),
213 | # "Door3Detectortime" = ParameterStruct(True, True),
214 | # "Door4Detectortime" = ParameterStruct(True, True),
215 | # "Door1VerifyType" = ParameterStruct(True, True),
216 | # "Door2VerifyType" = ParameterStruct(True, True),
217 | # "Door3VerifyType" = ParameterStruct(True, True),
218 | # "Door4VerifyType" = ParameterStruct(True, True),
219 | # "Door1MultiCardOpenDoor" = ParameterStruct(True, True),
220 | # "Door2MultiCardOpenDoor" = ParameterStruct(True, True),
221 | # "Door3MultiCardOpenDoor" = ParameterStruct(True, True),
222 | # "Door4MultiCardOpenDoor" = ParameterStruct(True, True),
223 | # "Door1FirstCardOpenDoor" = ParameterStruct(True, True),
224 | # "Door2FirstCardOpenDoor" = ParameterStruct(True, True),
225 | # "Door3FirstCardOpenDoor" = ParameterStruct(True, True),
226 | # "Door4FirstCardOpenDoor" = ParameterStruct(True, True),
227 | # "Door1ValidTZ" = ParameterStruct(True, True),
228 | # "Door2ValidTZ" = ParameterStruct(True, True),
229 | # "Door3ValidTZ" = ParameterStruct(True, True),
230 | # "Door4ValidTZ" = ParameterStruct(True, True),
231 | # "Door1KeepOpenTimeZone" = ParameterStruct(True, True),
232 | # "Door2KeepOpenTimeZone" = ParameterStruct(True, True),
233 | # "Door3KeepOpenTimeZone" = ParameterStruct(True, True),
234 | # "Door4KeepOpenTimeZone" = ParameterStruct(True, True),
235 | # "Door1Intertime" = ParameterStruct(True, True),
236 | # "Door2Intertime" = ParameterStruct(True, True),
237 | # "Door3Intertime" = ParameterStruct(True, True),
238 | # "Door4Intertime" = ParameterStruct(True, True),
239 | # "WatchDog" = ParameterStruct(True, True),
240 | # "Door4ToDoor2" = ParameterStruct(True, True),
241 | # "Door1CancelKeepOpenDay" = ParameterStruct(True, False),
242 | # "Door2CancelKeepOpenDay" = ParameterStruct(True, False),
243 | # "Door3CancelKeepOpenDay" = ParameterStruct(True, False),
244 | # "Door4CancelKeepOpenDay" = ParameterStruct(True, False),
245 | # "BackupTime" = ParameterStruct(True, True),
246 | # "Reboot" = ParameterStruct(False, True),
247 | # "DateTime" = ParameterStruct(False, True),
248 | # "Door4ToDoor2" = ParameterStruct(True, True),
249 | # "InBIOTowWay " = ParameterStruct(True, True),
250 | # "~ZKFPVersion" = ParameterStruct(True, False),
251 | # "~DSTF" = ParameterStruct(True, True),
252 | # "DaylightSavingTimeOn" = ParameterStruct(True, True),
253 | # "DLSTMode" = ParameterStruct(True, True),
254 | # "DaylightSavingTime" = ParameterStruct(True, True),
255 | # "StandardTime" = ParameterStruct(True, True),
256 | # "WeekOfMonth1" = ParameterStruct(True, True),
257 | # "WeekOfMonth2" = ParameterStruct(True, True),
258 | # "WeekOfMonth3" = ParameterStruct(True, True),
259 | # "WeekOfMonth4" = ParameterStruct(True, True),
260 | # "WeekOfMonth5" = ParameterStruct(True, True),
261 | # "WeekOfMonth6" = ParameterStruct(True, True),
262 | # "WeekOfMonth7" = ParameterStruct(True, True),
263 | # "WeekOfMonth8" = ParameterStruct(True, True),
264 | # "WeekOfMonth9" = ParameterStruct(True, True),
265 | # "WeekOfMonth10" = ParameterStruct(True, True),
266 | # )
267 |
--------------------------------------------------------------------------------
/c3/controldevice.py:
--------------------------------------------------------------------------------
1 | from abc import ABC
2 |
3 | from c3 import consts
4 |
5 |
6 | class ControlDeviceBase(ABC):
7 | """A ControlDevice is a binary message of 5 bytes send to the C3 access panel.
8 | It changes the states of the doors, auxiliary relays and alarms.
9 | All multibyte values are stored as Little-endian.
10 |
11 | Byte 0 1 2 3 4
12 | 01:01:01:c8:00
13 | Operation: |
14 | 01 => 1 (1: output, 2: cancel alarm, 3: restart device_name, 4: enable/disable normal open state)
15 | Param 1: |
16 | Param 2: |
17 | Param 3: |
18 | Param 4: |
19 |
20 | The meaning of the parameters is depending on the Operation code.
21 | Param 4 is reserved for future use (defaults to 0)
22 | Operation 1: Output operation
23 | Param 1: Door number or auxiliary output number
24 | Param 2: The address type of output operation (1: Door output, 2: Auxiliary output)
25 | Param 3: Duration of the open operation, only for address type = 1 (door output).
26 | 0: close, 255: normal open state, 1~254: normal open duration
27 | Operation 2: Cancel alarm
28 | Param 1: 0 (null)
29 | Param 2: 0 (null)
30 | Param 3: 0 (null)
31 | Operation 3: Restart device_name
32 | Param 1: 0 (null)
33 | Param 2: 0 (null)
34 | Param 3: 0 (null)
35 | Operation 3: Enable/disable normal open state
36 | Param 1: Door number
37 | Param 2: Enable / disable (0: disable, 1: enable)
38 | Param 3: 0 (null)
39 | """
40 |
41 | def __init__(self, operation: consts.ControlOperation, *args: int):
42 | """Constructor to initialize base class.
43 | The param1, param2, param3 and param4 values are provided as variable argument.
44 | """
45 | self.operation: consts.ControlOperation = operation
46 | self.param1: int = args[0] if len(args) > 0 else None
47 | self.param2: int = args[1] if len(args) > 1 else None
48 | self.param3: int = args[2] if len(args) > 2 else None
49 | self.param4: int = args[3] if len(args) > 3 else None
50 |
51 | @classmethod
52 | def from_bytes(cls, data: bytes):
53 | return ControlDeviceBase(*data)
54 |
55 | def to_bytes(self) -> bytes:
56 | return bytes(
57 | [
58 | self.operation,
59 | self.param1 or 0,
60 | self.param2 or 0,
61 | self.param3 or 0,
62 | self.param4 or 0,
63 | ]
64 | )
65 |
66 | def __repr__(self):
67 | return "\r\n".join(
68 | [
69 | "%-12s %-10s (%s)"
70 | % ("operation", self.operation, repr(self.operation)),
71 | "%-12s %-10s" % ("param1", self.param1),
72 | "%-12s %-10s" % ("param2", self.param2),
73 | "%-12s %-10s" % ("param3", self.param3),
74 | "%-12s %-10s" % ("param4", self.param4),
75 | ]
76 | )
77 |
78 |
79 | class ControlDeviceOutput(ControlDeviceBase):
80 | def __init__(
81 | self, output_number: int, address: consts.ControlOutputAddress, duration: int
82 | ):
83 | ControlDeviceBase.__init__(
84 | self, consts.ControlOperation.OUTPUT, output_number, address, duration
85 | )
86 |
87 | @property
88 | def output_number(self) -> int:
89 | return self.param1
90 |
91 | @property
92 | def address(self) -> int:
93 | return self.param2
94 |
95 | @property
96 | def duration(self) -> int:
97 | return self.param3
98 |
99 | def __repr__(self):
100 | return "\r\n".join(
101 | [
102 | "ControlDevice Output Operation:"
103 | "%-12s %-10s (%s)"
104 | % ("operation", self.operation, repr(self.operation)),
105 | "%-12s %-10s (Door/Aux Number)" % ("param1", self.output_number),
106 | "%-12s %-10s %s"
107 | % (
108 | "param2",
109 | self.param2,
110 | repr(consts.ControlOutputAddress(self.address)),
111 | ),
112 | "%-12s %-10s (Duration)" % ("param3", self.duration),
113 | ]
114 | )
115 |
116 |
117 | class ControlDeviceCancelAlarms(ControlDeviceBase):
118 | def __init__(self):
119 | ControlDeviceBase.__init__(self, consts.ControlOperation.CANCEL_ALARM)
120 |
121 | def __repr__(self):
122 | return "\r\n".join(
123 | ["ControlDevice Cancel Alarm Operation:", ControlDeviceBase.__repr__(self)]
124 | )
125 |
126 |
127 | class ControlDeviceNormalOpenStateEnable(ControlDeviceBase):
128 | def __init__(self, door_number: int, enable: bool):
129 | ControlDeviceBase.__init__(
130 | self, consts.ControlOperation.ENDIS_NO_STATE, door_number, enable
131 | )
132 |
133 | @property
134 | def door_number(self) -> int:
135 | return self.param1
136 |
137 | @property
138 | def enabled(self) -> bool:
139 | return bool(self.param2)
140 |
141 | def __repr__(self):
142 | return "\r\n".join(
143 | [
144 | "ControlDevice Normal Open State Operation:"
145 | "%-12s %-10s (%s)"
146 | % ("operation", self.operation, repr(self.operation)),
147 | "%-12s %-10s (Door Number)" % ("param1", self.door_number),
148 | "%-12s %-10s %s"
149 | % ("param2", self.param2, "Enable" if self.enabled else "Disable"),
150 | ]
151 | )
152 |
153 |
154 | class ControlDeviceRestart(ControlDeviceBase):
155 | def __init__(self):
156 | ControlDeviceBase.__init__(self, consts.ControlOperation.RESTART_DEVICE)
157 |
158 | def __repr__(self):
159 | return "\r\n".join(
160 | ["ControlDevice Restart Operation:", ControlDeviceBase.__repr__(self)]
161 | )
162 |
--------------------------------------------------------------------------------
/c3/core.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import logging
4 | import re
5 | import socket
6 | import threading
7 | from dataclasses import dataclass, field
8 | from datetime import datetime
9 | from typing import Dict, Optional
10 |
11 | from c3 import consts, controldevice, crc, rtlog, utils
12 |
13 |
14 | @dataclass
15 | class C3DeviceInfo:
16 | """Basic C3 panel (connection) information, obtained from discovery"""
17 |
18 | host: str
19 | port: int = consts.C3_PORT_DEFAULT
20 | serial_number: str = None
21 | mac: str = None
22 | device_name: str = None
23 | firmware_version: str = None
24 |
25 |
26 | @dataclass
27 | class C3DoorSettings:
28 | """C3 panel door configuration and settings"""
29 |
30 | sensor_type: consts.DoorSensorType = consts.DoorSensorType.NONE
31 | """Door sensor type
32 |
33 | parameter: DoorNSensorType,
34 | 0: Not available
35 | 1: Normal open
36 | 2: Normal closed
37 | """
38 | lock_drive_time: int = None
39 | """Lock driver time length
40 |
41 | parameter: DoorNDrivertime,
42 | The value range is 0 to 255.
43 | 0: Normal closed
44 | 255: Normal open
45 | 1 to 254: Door-opening duration
46 | """
47 | door_alarm_timeout: int = None
48 | """Timeout alarm duration of door magnet
49 |
50 | parameter: DoorNDetectortime
51 | The value range is 0 to 255,
52 | Unit: second
53 | """
54 |
55 |
56 | @dataclass
57 | class C3PanelStatus:
58 | """C3 panel peripheral status"""
59 |
60 | nr_of_locks: int = 0
61 | nr_aux_in: int = 0
62 | nr_aux_out: int = 0
63 | door_settings: Dict[int, C3DoorSettings] = field(default_factory=dict)
64 | lock_status: Dict[int, consts.InOutStatus] = field(default_factory=dict)
65 | aux_in_status: Dict[int, consts.InOutStatus] = field(default_factory=dict)
66 | aux_out_status: Dict[int, consts.InOutStatus] = field(default_factory=dict)
67 |
68 |
69 | @dataclass
70 | class _DataTableCfgField:
71 | name: str = ""
72 | type: str = ""
73 | index: int = 0
74 |
75 |
76 | @dataclass
77 | class _DataTableCfg:
78 | name: str = ""
79 | index: int = 0
80 | fields: list[_DataTableCfgField] = field(default_factory=list)
81 |
82 | def __init__(self, data_cfg_kv: dict):
83 | if data_cfg_kv:
84 | (name, index), *fields = data_cfg_kv.items()
85 | self.name = name
86 | self.index = int(index)
87 | self.fields = [
88 | _DataTableCfgField(
89 | name=field_name, type=field_typedef[0], index=int(field_typedef[1:])
90 | )
91 | for (field_name, field_typedef) in fields
92 | ]
93 |
94 |
95 | class C3:
96 | log = logging.getLogger("C3")
97 | log.setLevel(logging.ERROR)
98 | receive_timeout = 1
99 | receive_retries = 3
100 |
101 | def __init__(
102 | self, host: [str | C3DeviceInfo], port: int = consts.C3_PORT_DEFAULT
103 | ) -> None:
104 | self._sock: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
105 | self._sock.settimeout(self.receive_timeout)
106 | self._connected: bool = False
107 | self._session_less = False
108 | self._initialized = False
109 | self._protocol_version = None
110 | self._rtlog_command = consts.Command.RTLOG_BINARY
111 | self._session_id: int = 0xFEFE
112 | self._request_nr: int = -258
113 | self._status: C3PanelStatus = C3PanelStatus()
114 | if isinstance(host, C3DeviceInfo):
115 | self._device_info: C3DeviceInfo = host
116 | elif isinstance(host, str):
117 | self._device_info: C3DeviceInfo = C3DeviceInfo(
118 | host=host, port=port or consts.C3_PORT_DEFAULT
119 | )
120 |
121 | @classmethod
122 | def _get_message_header(
123 | cls, data: [bytes or bytearray]
124 | ) -> tuple[[int or None], int, int]:
125 | if len(data) >= 5:
126 | version = data[1]
127 | if (
128 | data[0] == consts.C3_MESSAGE_START
129 | ): # and version == consts.C3_PROTOCOL_VERSION:
130 | command = data[2]
131 | data_size = data[3] + (data[4] * 256)
132 | else:
133 | raise ValueError("Received reply does not start with start token")
134 | else:
135 | raise ValueError(f"Received reply of insufficient length {len(data)}")
136 |
137 | return command, data_size, version
138 |
139 | @classmethod
140 | def _get_message(cls, data: [bytes or bytearray]) -> bytearray:
141 | if data[-1] == consts.C3_MESSAGE_END:
142 | # Get the message payload, without start, crc and end bytes
143 | checksum = crc.crc16(data[1:-3])
144 |
145 | if utils.lsb(checksum) == data[-3] or utils.msb(checksum) == data[-2]:
146 | # Return all data without header (leading) and crc (trailing)
147 | message = bytearray(data[5:-3])
148 | else:
149 | raise ValueError(
150 | "Payload checksum is invalid: %02x%02x expected %02x%02x"
151 | % (data[-3], data[-2], utils.lsb(checksum), utils.msb(checksum))
152 | )
153 | else:
154 | raise ValueError(
155 | "Payload does not include message end marker (%02x)" % data[-1]
156 | )
157 |
158 | return message
159 |
160 | @classmethod
161 | def _construct_message(
162 | cls,
163 | session_id: Optional[int],
164 | request_nr: Optional[int],
165 | command: consts.Command,
166 | data=None,
167 | ) -> bytes:
168 | message_length = len(data or []) + (4 if (session_id and request_nr) else 0)
169 | message = bytearray(
170 | [
171 | consts.C3_PROTOCOL_VERSION,
172 | command or 0x00,
173 | utils.lsb(message_length),
174 | utils.msb(message_length),
175 | ]
176 | )
177 | if session_id:
178 | message.append(utils.lsb(session_id))
179 | message.append(utils.msb(session_id))
180 | message.append(utils.lsb(request_nr))
181 | message.append(utils.msb(request_nr))
182 |
183 | if data:
184 | for byte in data:
185 | if isinstance(byte, int):
186 | message.append(byte)
187 | elif isinstance(byte, str):
188 | message.append(ord(byte))
189 | else:
190 | raise TypeError(
191 | "Data does not contain int or str: %s is %s"
192 | % (str(byte), type(byte))
193 | )
194 |
195 | checksum = crc.crc16(message)
196 | message.append(utils.lsb(checksum))
197 | message.append(utils.msb(checksum))
198 |
199 | message.insert(0, consts.C3_MESSAGE_START)
200 | message.append(consts.C3_MESSAGE_END)
201 | return message
202 |
203 | def _send(self, command: consts.Command, data=None) -> int:
204 | message = self._construct_message(
205 | self._session_id, self._request_nr, command, data
206 | )
207 |
208 | self.log.debug("Sending: %s", message.hex())
209 |
210 | bytes_written = self._sock.send(message)
211 | self._request_nr = self._request_nr + 1
212 | return bytes_written
213 |
214 | def _receive(self) -> tuple[bytearray, int, int]:
215 | # Get the first 5 bytes
216 | self._sock.settimeout(self.receive_timeout)
217 |
218 | header = bytes()
219 | for _ in range(self.receive_retries):
220 | try:
221 | header = self._sock.recv(5)
222 | if len(header) == 5:
223 | break
224 | except socket.timeout:
225 | pass
226 |
227 | if len(header) == 5:
228 | self.log.debug("Received header: %s", header.hex())
229 |
230 | message = bytearray()
231 | received_command, data_size, protocol_version = self._get_message_header(
232 | header
233 | )
234 | # Get the optional message data, checksum (2 bytes) and end marker (1 byte)
235 | payload = self._sock.recv(data_size + 3)
236 | if data_size > 0:
237 | # Process message in case data available
238 | self.log.debug(
239 | "Receiving payload (data size %d): %s", data_size, payload.hex()
240 | )
241 | message = self._get_message(header + payload)
242 |
243 | if len(message) != data_size:
244 | raise ValueError(
245 | f"Length of received message ({len(message)}) doesn't match specified ({data_size})"
246 | )
247 |
248 | if received_command == consts.C3_REPLY_OK:
249 | pass
250 | elif received_command == consts.C3_REPLY_ERROR:
251 | error = utils.byte_to_signed_int(message[-1])
252 | raise ConnectionError(
253 | f"Error {error} received in reply: {consts.Errors[error] if error in consts.Errors else 'Unknown'}"
254 | )
255 | else:
256 | raise ConnectionError(
257 | f"Invalid response header received; expected 5 bytes, received {header}"
258 | )
259 |
260 | return message, data_size, protocol_version
261 |
262 | def _send_receive(
263 | self, command: consts.Command, data=None
264 | ) -> tuple[bytearray, int]:
265 | bytes_received = 0
266 | receive_data = bytearray()
267 | session_offset = 0
268 |
269 | try:
270 | bytes_written = self._send(command, data)
271 | if bytes_written > 0:
272 | receive_data, bytes_received, _ = self._receive()
273 | if not self._session_less and bytes_received > 2:
274 | session_offset = 4
275 | session_id = (receive_data[1] << 8) + receive_data[0]
276 | # msg_seq = (receive_data[3] << 8) + receive_data[2]
277 | if self._session_id != session_id:
278 | raise ValueError("Data received with invalid session ID")
279 | except BrokenPipeError as ex:
280 | self._connected = False
281 | raise ConnectionError(f"Unexpected connection end: {ex}") from ex
282 |
283 | return receive_data[session_offset:], bytes_received - session_offset
284 |
285 | def _initialize(self):
286 | if not self._initialized:
287 | try:
288 | params = self.get_device_param(
289 | [
290 | "~SerialNumber",
291 | "FirmVer",
292 | "DeviceName",
293 | "LockCount",
294 | "AuxInCount",
295 | "AuxOutCount",
296 | ]
297 | )
298 | self._device_info.serial_number = params.get(
299 | "~SerialNumber", self._device_info.serial_number
300 | )
301 | self._device_info.firmware_version = params.get(
302 | "FirmVer", self._device_info.firmware_version
303 | )
304 | self._device_info.device_name = params.get(
305 | "DeviceName", self._device_info.device_name
306 | )
307 | self._status.nr_of_locks = int(
308 | params.get("LockCount", self._status.nr_of_locks)
309 | )
310 | self._status.nr_aux_in = int(
311 | params.get("AuxInCount", self._status.nr_aux_in)
312 | )
313 | self._status.nr_aux_out = int(
314 | params.get("AuxOutCount", self._status.nr_aux_out)
315 | )
316 | self._initialized = True
317 | except ConnectionError as ex:
318 | self.log.error(
319 | "Connection to %s failed: %s", self._device_info.host, ex
320 | )
321 | except ValueError as ex:
322 | self.log.error(
323 | "Retrieving configuration parameters from %s failed: %s",
324 | self._device_info.host,
325 | ex,
326 | )
327 |
328 | def is_connected(self) -> bool:
329 | # try:
330 | # # this will try to read bytes without blocking and also without removing them from buffer (peek only)
331 | # data = self._sock.recv(1, socket.MSG_DONTWAIT | socket.MSG_PEEK)
332 | # if len(data) == 0:
333 | # return True
334 | # except BlockingIOError:
335 | # return True # socket is open and reading from it would block
336 | # except ConnectionResetError:
337 | # return False # socket was closed for some other reason
338 | # except Exception as e:
339 | # return False
340 | return self._sock is not None and self._connected
341 |
342 | @classmethod
343 | def _parse_kv_from_message(cls, message: bytes) -> dict:
344 | kv_pairs = {}
345 |
346 | message_str = message.decode(encoding="ascii", errors="ignore")
347 | pattern = re.compile(r"([\w~]+)=([^,\t]+)")
348 | for param_name, param_value in re.findall(pattern, message_str):
349 | kv_pairs[param_name] = param_value
350 |
351 | return kv_pairs
352 |
353 | @classmethod
354 | def _kv_to_message(cls, data: dict):
355 | kv_array = ["{0}={1}".format(k, v) for k, v in data.items()]
356 | kv_str = ",".join(kv_array)
357 | return kv_str.encode(encoding="ascii", errors="ignore")
358 |
359 | def __repr__(self):
360 | return "\r\n".join(
361 | [
362 | f"- Host: {self.host} @ {self.port}",
363 | f"- Device: {self.device_name} (sn: {self.serial_number})",
364 | f"- Firmware version: {self.firmware_version}",
365 | ]
366 | )
367 |
368 | def log_level(self, level: int):
369 | self.log.setLevel(level)
370 |
371 | @property
372 | def host(self) -> str:
373 | return self._device_info.host
374 |
375 | @host.setter
376 | def host(self, host: str):
377 | if not self.is_connected():
378 | self._device_info.host = host
379 | else:
380 | raise ConnectionError(
381 | "Cannot set host when C3 is connected. Disconnect first."
382 | )
383 |
384 | @property
385 | def port(self) -> int:
386 | return self._device_info.port
387 |
388 | @port.setter
389 | def port(self, port: int):
390 | if not self.is_connected():
391 | self._device_info.port = port
392 | else:
393 | raise ConnectionError(
394 | "Cannot set port when C3 is connected. Disconnect first."
395 | )
396 |
397 | @property
398 | def mac(self) -> str:
399 | return self._device_info.mac or "?"
400 |
401 | @property
402 | def serial_number(self) -> str:
403 | return self._device_info.serial_number or "?"
404 |
405 | @property
406 | def device_name(self) -> str:
407 | return self._device_info.device_name or "?"
408 |
409 | @property
410 | def firmware_version(self) -> str:
411 | return self._device_info.firmware_version or "?"
412 |
413 | @property
414 | def nr_of_locks(self) -> int:
415 | return self._status.nr_of_locks or 0
416 |
417 | @property
418 | def nr_aux_in(self) -> int:
419 | return self._status.nr_aux_in or 0
420 |
421 | @property
422 | def nr_aux_out(self) -> int:
423 | return self._status.nr_aux_out or 0
424 |
425 | @classmethod
426 | def discover(cls, interface_address: str = None, timeout: int = 2) -> list[C3]:
427 | """Scan on all local network interface, or the provided interface, for C3 panels."""
428 | devices = []
429 | message = cls._construct_message(
430 | None, None, consts.Command.DISCOVER, consts.C3_DISCOVERY_MESSAGE
431 | )
432 |
433 | if interface_address:
434 | ip_addresses = [interface_address]
435 | else:
436 | interfaces = socket.getaddrinfo(
437 | host=socket.gethostname(), port=None, family=socket.AF_INET
438 | )
439 | ip_addresses = [ip[-1][0] for ip in interfaces]
440 | for ip_address in ip_addresses:
441 | cls.log.debug("Discover on %s", ip_address)
442 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
443 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
444 | sock.settimeout(timeout)
445 | sock.bind((ip_address, 0))
446 | sock.sendto(message, ("255.255.255.255", consts.C3_PORT_BROADCAST))
447 |
448 | while True:
449 | try:
450 | payload = sock.recv(64 * 1024)
451 | except socket.timeout:
452 | break
453 |
454 | if payload:
455 | received_command, data_size, _ = cls._get_message_header(payload)
456 | if received_command == consts.C3_REPLY_OK:
457 | # Get the message data and signature
458 | message = cls._get_message(payload)
459 |
460 | if len(message) != data_size:
461 | raise ValueError(
462 | "Length of received message (%d) does not match specified size (%d)"
463 | % (len(message), data_size)
464 | )
465 | data = cls._parse_kv_from_message(message)
466 | devices.append(
467 | C3(
468 | C3DeviceInfo(
469 | host=data.get("IP"),
470 | mac=data.get("MAC"),
471 | serial_number=data.get("SN"),
472 | device_name=data.get("Device"),
473 | firmware_version=data.get("Ver"),
474 | )
475 | )
476 | )
477 | sock.close()
478 |
479 | return devices
480 |
481 | def connect(self, password: Optional[str] = None) -> bool:
482 | """Connect to the C3 panel on the host/port provided in the constructor."""
483 | self._connected = False
484 | self._session_id = 0xFEFE
485 | self._request_nr: -258
486 |
487 | data = None
488 | if password:
489 | data = bytearray(password.encode("ascii"))
490 |
491 | # Recreate a socket when it has been removed in disconnect method because of an error
492 | if self._sock is None:
493 | self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
494 |
495 | try:
496 | self._sock.connect((self._device_info.host, self._device_info.port))
497 | except socket.error as ex:
498 | self.log.error("Error while opening socket: %s", str(ex))
499 | self._sock = None
500 |
501 | if self._sock is not None:
502 | # Attempt to connect to panel with session initiation command
503 | try:
504 | bytes_written = self._send(consts.Command.CONNECT_SESSION, data)
505 | if bytes_written > 0:
506 | receive_data, bytes_received, protocol_version = self._receive()
507 | if bytes_received > 2:
508 | self._session_id = (receive_data[1] << 8) + receive_data[0]
509 | self.log.debug(
510 | "Connected with Session ID %04x", self._session_id
511 | )
512 | self._session_less = False
513 | self._protocol_version = protocol_version
514 | self._connected = True
515 | except ConnectionError as ex:
516 | self.log.debug(
517 | "Connection attempt with session to %s failed: %s",
518 | self._device_info.host,
519 | ex,
520 | )
521 | except ValueError as ex:
522 | self.log.error("Reply from %s failed: %s", self._device_info.host, ex)
523 |
524 | # Alternatively attempt to connect to panel without session initiation
525 | if not self._connected:
526 | try:
527 | self._session_id = None
528 | bytes_written = self._send(
529 | consts.Command.CONNECT_SESSION_LESS, data
530 | )
531 | if bytes_written > 0:
532 | _, _, protocol_version = self._receive()
533 | self.log.debug("Connected without session")
534 | self._session_less = True
535 | self._protocol_version = protocol_version
536 | self._connected = True
537 | except ConnectionError as ex:
538 | self.log.debug(
539 | "Connection attempt without session to %s failed: %s",
540 | self._device_info.host,
541 | ex,
542 | )
543 | except ValueError as ex:
544 | self.log.error(
545 | "Reply from %s failed: %s", self._device_info.host, ex
546 | )
547 |
548 | if self._connected:
549 | self._initialize()
550 |
551 | return self._connected
552 |
553 | def disconnect(self):
554 | """Disconnect from C3 panel and end session."""
555 | if self.is_connected():
556 | try:
557 | self._send_receive(consts.Command.DISCONNECT)
558 | except ConnectionError:
559 | # Disconnecting a broken connection should not create more trouble,
560 | # ignoring a ConnectionError for that reason.
561 | pass
562 |
563 | if self._sock is not None:
564 | try:
565 | self._sock.close()
566 | except socket.error as ex:
567 | self.log.error("Error while closing socket: %s", str(ex))
568 | self._sock = None
569 |
570 | self._connected = False
571 | self._session_id = None
572 | self._request_nr: -258
573 |
574 | def set_device_datetime(self, time: Optional[datetime] = None):
575 | """Send a control command to the panel."""
576 | time = time or datetime.now()
577 | time_seconds = utils.C3DateTime(
578 | year=time.year,
579 | month=time.month,
580 | day=time.day,
581 | hour=time.hour,
582 | minute=time.minute,
583 | second=time.second,
584 | )
585 |
586 | if self.is_connected():
587 | self._send_receive(
588 | consts.Command.DATETIME,
589 | self._kv_to_message({"DateTime": time_seconds.to_value()}),
590 | )
591 | else:
592 | raise ConnectionError("No connection to C3 panel.")
593 |
594 | def get_device_param(self, request_parameters: list[str]) -> dict:
595 | """Retrieve the requested device parameter values."""
596 | if self.is_connected():
597 | message, _ = self._send_receive(
598 | consts.Command.GETPARAM, ",".join(request_parameters)
599 | )
600 | parameter_values = self._parse_kv_from_message(message)
601 | else:
602 | raise ConnectionError("No connection to C3 panel.")
603 |
604 | return parameter_values
605 |
606 | def _get_device_data_cfg(self) -> list[_DataTableCfg]:
607 | data_cfg = []
608 |
609 | if self.is_connected():
610 | message, _ = self._send_receive(consts.Command.DATATABLE_CFG)
611 | # get the individual table configuration, that is split using a newline (\n)
612 | for message_line in message.split(b"\x0a"):
613 | data_items = self._parse_kv_from_message(message_line)
614 | if data_items:
615 | data_cfg.append(_DataTableCfg(data_items))
616 | else:
617 | raise ConnectionError("No connection to C3 panel.")
618 |
619 | return data_cfg
620 |
621 | def get_device_data(
622 | self, table_name: str, field_names: Optional[list[str]] = None
623 | ) -> list[dict]:
624 | data_cfg = self._get_device_data_cfg()
625 | device_data = []
626 |
627 | cfg = next((c for c in data_cfg if c.name == table_name), None)
628 | if cfg:
629 | data_fields = [f.name for f in cfg.fields]
630 | if field_names:
631 | valid_fields = [f for f in field_names if f in data_fields]
632 | if not len(valid_fields) == len(field_names):
633 | raise ValueError(
634 | "Not all fields are available (%s), choose from %s"
635 | % (
636 | ",".join([f for f in field_names if f not in data_fields]),
637 | ",".join([f for f in data_fields]),
638 | )
639 | )
640 | else:
641 | field_names = data_fields
642 | field_indexes = [f.index for f in cfg.fields if f.name in field_names]
643 | field_indexes.sort()
644 |
645 | # Construct the parameters for the GETDATA command.
646 | # This consists of:
647 | # - the index of the table to retrieve
648 | # - the number of fields to retrieve
649 | # - the indexes of the fields to retrieve
650 | # - two bytes set to 0 - purpose or meaning unknown
651 | parameters = [cfg.index, len(field_indexes)] + field_indexes + [0, 0]
652 | message, _ = self._send_receive(consts.Command.GETDATA, parameters)
653 | if message[0] == cfg.index:
654 | response_field_cnt = message[1]
655 | response_field_indexes = message[2 : 2 + response_field_cnt]
656 | response_data = message[2 + response_field_cnt :]
657 | while response_data:
658 | device_data_record = {}
659 |
660 | for response_field_index in response_field_indexes:
661 | response_field = next(
662 | (f for f in cfg.fields if f.index == response_field_index),
663 | None,
664 | )
665 | if response_field:
666 | field_size = response_data[0]
667 | if response_field.type == "i":
668 | device_data_record[
669 | response_field.name
670 | ] = int.from_bytes(
671 | response_data[1 : 1 + field_size], "little"
672 | )
673 | elif response_field.type == "s":
674 | device_data_record[response_field.name] = response_data[
675 | 1 : 1 + field_size
676 | ].decode(encoding="ascii", errors="ignore")
677 | else:
678 | ValueError(
679 | "Unsupported type %s for field %s"
680 | % (response_field.type, response_field.name)
681 | )
682 |
683 | response_data = response_data[1 + field_size :]
684 | else:
685 | raise ValueError(
686 | "Unknown field index returned by panel: %d"
687 | % response_field_index
688 | )
689 |
690 | device_data.append(device_data_record)
691 | else:
692 | raise ValueError(
693 | "Wrong table returned by panel. Expected %d, received %d"
694 | % (cfg.index, message[0])
695 | )
696 | else:
697 | raise ValueError(
698 | "Table '%s' is not available, use one of: %s"
699 | % (table_name, ",".join([cfg.name for cfg in data_cfg]))
700 | )
701 |
702 | return device_data
703 |
704 | def _update_inout_status(self, logs: list[rtlog.RTLogRecord]):
705 | for log in logs:
706 | if isinstance(log, rtlog.DoorAlarmStatusRecord):
707 | for lock_nr in range(1, self.nr_of_locks + 1):
708 | self._set_lock_status(
709 | lock_nr, log.door_sensor_status(lock_nr), auto_close=False
710 | )
711 |
712 | elif isinstance(log, rtlog.EventRecord) and log.port_nr - 1 in range(
713 | self.nr_of_locks
714 | ):
715 | if log.event_type == consts.EventType.OPEN_AUX_OUTPUT:
716 | self._set_aux_out_status(
717 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
718 | )
719 | elif log.event_type == consts.EventType.CLOSE_AUX_OUTPUT:
720 | self._set_aux_out_status(log.port_nr, consts.InOutStatus.CLOSED)
721 |
722 | elif log.event_type == consts.EventType.OPENED_ACCIDENT:
723 | # Event feedback also expected via DoorAlarmStatusRecord, handling is probably double
724 | self._set_lock_status(
725 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
726 | )
727 | elif log.event_type == consts.EventType.DOOR_OPENED_CORRECT:
728 | # Event feedback also expected via DoorAlarmStatusRecord, handling is probably double
729 | self._set_lock_status(
730 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
731 | )
732 | elif log.event_type == consts.EventType.DOOR_CLOSED_CORRECT:
733 | # Event feedback also expected via DoorAlarmStatusRecord, handling is probably double
734 | self._set_lock_status(log.port_nr, consts.InOutStatus.CLOSED)
735 |
736 | elif log.event_type == consts.EventType.AUX_INPUT_DISCONNECT:
737 | self._set_aux_in_status(log.port_nr, consts.InOutStatus.OPEN)
738 | elif log.event_type == consts.EventType.AUX_INPUT_SHORT:
739 | self._set_aux_in_status(log.port_nr, consts.InOutStatus.CLOSED)
740 |
741 | elif (
742 | self.door_settings(log.port_nr).sensor_type
743 | == consts.DoorSensorType.NONE
744 | ):
745 | # When the door has no sensor, set the status based on the lock open/close events
746 |
747 | # The lock drive time is used for automatic closing
748 | lock_drive_time = self.door_settings(log.port_nr).lock_drive_time
749 |
750 | if log.event_type == consts.EventType.NORMAL_PUNCH_OPEN:
751 | self._set_lock_status(
752 | log.port_nr,
753 | consts.InOutStatus.OPEN,
754 | auto_close=lock_drive_time,
755 | )
756 | # PUNCH_NORMAL_OPEN_TZ
757 | # Ignore "Punch during Normal Open Time Zone", door is already open
758 | # FIRST_CARD_NORMAL_OPEN
759 | # Ingore "First Card Normal Open (Punch Card)", door is already open
760 | elif log.event_type == consts.EventType.MULTI_CARD_OPEN:
761 | self._set_lock_status(
762 | log.port_nr,
763 | consts.InOutStatus.OPEN,
764 | auto_close=lock_drive_time,
765 | )
766 | elif log.event_type == consts.EventType.EMERGENCY_PASS_OPEN:
767 | self._set_lock_status(
768 | log.port_nr,
769 | consts.InOutStatus.OPEN,
770 | auto_close=lock_drive_time,
771 | )
772 | elif log.event_type == consts.EventType.OPEN_NORMAL_OPEN_TZ:
773 | # Not autoclosing, door is open during normal open time zone
774 | self._set_lock_status(
775 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
776 | )
777 | elif log.event_type == consts.EventType.REMOTE_OPENING:
778 | # Remote closing command exected for closing, not setting auto-close
779 | self._set_lock_status(
780 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
781 | )
782 | elif log.event_type == consts.EventType.REMOTE_CLOSING:
783 | self._set_lock_status(log.port_nr, consts.InOutStatus.CLOSED)
784 | elif log.event_type == consts.EventType.PRESS_FINGER_OPEN:
785 | self._set_lock_status(
786 | log.port_nr,
787 | consts.InOutStatus.OPEN,
788 | auto_close=lock_drive_time,
789 | )
790 | elif log.event_type == consts.EventType.MULTI_CARD_OPEN_FP:
791 | self._set_lock_status(
792 | log.port_nr,
793 | consts.InOutStatus.OPEN,
794 | auto_close=lock_drive_time,
795 | )
796 | # FP_NORMAL_OPEN_TZ
797 | # Ingore "Press Fingerprint during Normal Open Time Zone", door is already open
798 | elif log.event_type == consts.EventType.CARD_FP_OPEN:
799 | self._set_lock_status(
800 | log.port_nr,
801 | consts.InOutStatus.OPEN,
802 | auto_close=lock_drive_time,
803 | )
804 | elif log.event_type == consts.EventType.FIRST_CARD_NORMAL_OPEN_FP:
805 | self._set_lock_status(
806 | log.port_nr,
807 | consts.InOutStatus.OPEN,
808 | auto_close=lock_drive_time,
809 | )
810 | elif (
811 | log.event_type
812 | == consts.EventType.FIRST_CARD_NORMAL_OPEN_CARD_FP
813 | ):
814 | self._set_lock_status(
815 | log.port_nr,
816 | consts.InOutStatus.OPEN,
817 | auto_close=lock_drive_time,
818 | )
819 | elif log.event_type == consts.EventType.DURESS_PASSWORD_OPEN:
820 | self._set_lock_status(
821 | log.port_nr,
822 | consts.InOutStatus.OPEN,
823 | auto_close=lock_drive_time,
824 | )
825 | elif log.event_type == consts.EventType.DURESS_FP_OPEN:
826 | self._set_lock_status(
827 | log.port_nr,
828 | consts.InOutStatus.OPEN,
829 | auto_close=lock_drive_time,
830 | )
831 | elif log.event_type == consts.EventType.EXIT_BUTTON_OPEN:
832 | self._set_lock_status(
833 | log.port_nr,
834 | consts.InOutStatus.OPEN,
835 | auto_close=lock_drive_time,
836 | )
837 | elif log.event_type == consts.EventType.MULTI_CARD_OPEN_CARD_FP:
838 | self._set_lock_status(
839 | log.port_nr,
840 | consts.InOutStatus.OPEN,
841 | auto_close=lock_drive_time,
842 | )
843 | elif log.event_type == consts.EventType.NORMAL_OPEN_TZ_OVER:
844 | self._set_lock_status(log.port_nr, consts.InOutStatus.CLOSED)
845 | elif log.event_type == consts.EventType.REMOTE_NORMAL_OPEN:
846 | # Changes door to normal open, so open until normal open time ends (NORMAL_OPEN_TZ_OVER)
847 | self._set_lock_status(
848 | log.port_nr, consts.InOutStatus.OPEN, auto_close=False
849 | )
850 | elif log.event_type == consts.EventType.DOOR_OPEN_BY_SUPERUSER:
851 | self._set_lock_status(
852 | log.port_nr,
853 | consts.InOutStatus.OPEN,
854 | auto_close=lock_drive_time,
855 | )
856 |
857 | def get_rt_log(self) -> list[rtlog.EventRecord | rtlog.DoorAlarmStatusRecord]:
858 | """Retrieve the latest event or alarm records."""
859 | records = []
860 |
861 | if self.is_connected():
862 | message, message_length = self._send_receive(self._rtlog_command)
863 | if message_length:
864 | if self._rtlog_command == consts.Command.RTLOG_BINARY:
865 | # One RT log is 16 bytes
866 | # Ensure the array is not empty and a multiple of 16
867 | if message_length % 16 == 0:
868 | logs_messages = [
869 | message[i : i + 16] for i in range(0, message_length, 16)
870 | ]
871 | for log_message in logs_messages:
872 | self.log.debug(
873 | "Received RT binary log: %s", log_message.hex()
874 | )
875 | records.append(rtlog.factory(log_message))
876 | else:
877 | # The panel firmware does not support binary mode
878 | self.log.debug("Transition RT log mode to key/value")
879 | self._rtlog_command = consts.Command.RTLOG_KEYVALUE
880 | elif self._rtlog_command == consts.Command.RTLOG_KEYVALUE:
881 | kv_pairs = self._parse_kv_from_message(message)
882 | self.log.debug(
883 | "Received RT k/v log (%d): %s", len(kv_pairs), kv_pairs
884 | )
885 | if len(kv_pairs) > 0:
886 | records.append(rtlog.factory(kv_pairs))
887 | else:
888 | raise NotImplementedError(
889 | f"The requested RT log command {self._rtlog_command} is not supported"
890 | )
891 | else:
892 | raise ConnectionError("No connection to C3 panel.")
893 |
894 | self._update_inout_status(records)
895 |
896 | return records
897 |
898 | def _set_lock_status(
899 | self, door_nr: int, status: consts.InOutStatus, auto_close: bool | int = False
900 | ) -> None:
901 | """Set the specified door lock status and optionally performs automatic close after specified timeout."""
902 |
903 | # Update the status only when status is more specific than unknown, or when no status is recorded at all
904 | if (
905 | not status == consts.InOutStatus.UNKNOWN
906 | or door_nr not in self._status.lock_status
907 | ):
908 | self._status.lock_status[door_nr] = status
909 |
910 | if status == consts.InOutStatus.OPEN and ((auto_close or 0) > 0):
911 | threading.Timer(
912 | auto_close, self._set_lock_status, [door_nr, consts.InOutStatus.CLOSED]
913 | ).start()
914 |
915 | def _auto_close_lock(self, door_nr: int) -> None:
916 | """Set the specified door lock to closed.
917 |
918 | The C3 does not send an event to update the door lock activation status, only the sensor status.
919 | This means the lock (or alternatively the door) status is not updated for doors without sensor.
920 | This function is triggered by an automatic internal timer to set the lock state to closed.
921 | """
922 | self._status.lock_status[door_nr] = consts.InOutStatus.CLOSED
923 |
924 | def _set_aux_in_status(self, aux_nr: int, status: consts.InOutStatus) -> None:
925 | """Set the specified auxiliary input status"""
926 |
927 | # Update the status only when status is more specific than unknown, or when no status is recorded at all
928 | if (
929 | not status == consts.InOutStatus.UNKNOWN
930 | or aux_nr not in self._status.aux_in_status
931 | ):
932 | self._status.aux_in_status[aux_nr] = status
933 |
934 | def _set_aux_out_status(
935 | self, aux_nr: int, status: consts.InOutStatus, auto_close: bool | int = False
936 | ) -> None:
937 | """Set the specified auxiliary output status and optionally performs automatic close after specified timeout."""
938 |
939 | # Update the status only when status is more specific than unknown, or when no status is recorded at all
940 | if (
941 | not status == consts.InOutStatus.UNKNOWN
942 | or aux_nr not in self._status.aux_out_status
943 | ):
944 | self._status.aux_out_status[aux_nr] = status
945 |
946 | if status == consts.InOutStatus.OPEN and ((auto_close or 0) > 0):
947 | threading.Timer(
948 | auto_close,
949 | self._set_aux_out_status,
950 | [aux_nr, consts.InOutStatus.CLOSED],
951 | ).start()
952 |
953 | def _auto_close_aux_out(self, aux_nr: int) -> None:
954 | """Set the specified auxiliary output to closed.
955 |
956 | The C3 does not send an event when an auxiliary output closes after a certain duration.
957 | This function is triggered by an automatic internal timer to set the aux state to closed.
958 | """
959 | self._status.aux_out_status[aux_nr] = consts.InOutStatus.CLOSED
960 |
961 | def control_device(self, command: controldevice.ControlDeviceBase):
962 | """Send a control command to the panel."""
963 | if self.is_connected():
964 | self._send_receive(consts.Command.CONTROL, command.to_bytes())
965 |
966 | if isinstance(command, controldevice.ControlDeviceOutput):
967 | if (
968 | command.operation == consts.ControlOperation.OUTPUT
969 | and command.duration < 255
970 | ):
971 | if (
972 | command.address == consts.ControlOutputAddress.DOOR_OUTPUT
973 | and self.door_settings(command.output_number).sensor_type
974 | == consts.DoorSensorType.NONE
975 | ):
976 | threading.Timer(
977 | command.duration,
978 | self._auto_close_lock,
979 | [command.output_number],
980 | ).start()
981 | if command.address == consts.ControlOutputAddress.AUX_OUTPUT:
982 | threading.Timer(
983 | command.duration,
984 | self._auto_close_aux_out,
985 | [command.output_number],
986 | ).start()
987 | else:
988 | raise ConnectionError("No connection to C3 panel.")
989 |
990 | def door_settings(self, door_nr: int) -> C3DoorSettings:
991 | """Returns the settings of the door as configured on the panel"""
992 | if door_nr in self._status.door_settings:
993 | return self._status.door_settings[door_nr]
994 | elif not self._status.door_settings:
995 | for door_idx in range(self._status.nr_of_locks):
996 | door_prefix = f"Door{door_idx+1}"
997 | param_values = self.get_device_param(
998 | [
999 | door_prefix + p
1000 | for p in ["SensorType", "Drivertime", "Detectortime"]
1001 | ]
1002 | )
1003 | if param_values:
1004 | self._status.door_settings[door_idx + 1] = C3DoorSettings(
1005 | sensor_type=consts.DoorSensorType(
1006 | int(param_values.get(door_prefix + "SensorType"))
1007 | ),
1008 | lock_drive_time=int(
1009 | param_values.get(door_prefix + "Drivertime")
1010 | ),
1011 | door_alarm_timeout=int(
1012 | param_values.get(door_prefix + "Detectortime")
1013 | ),
1014 | )
1015 |
1016 | return self._status.door_settings[door_nr]
1017 | else:
1018 | raise ValueError(
1019 | "Invalid door number specified (%d), 1-%d supported",
1020 | door_nr,
1021 | self._status.nr_of_locks,
1022 | )
1023 |
1024 | def lock_status(self, door_nr: int) -> consts.InOutStatus:
1025 | """Returns the (cached) door open/close status.
1026 | Requires a preceding call to get_rt_log to update to the latest status."""
1027 | return (
1028 | self._status.lock_status[door_nr]
1029 | if door_nr in self._status.lock_status
1030 | else consts.InOutStatus.UNKNOWN
1031 | )
1032 |
1033 | def aux_in_status(self, aux_nr: int) -> consts.InOutStatus:
1034 | """Returns the (cached) auxiliary input short/disconnect status.
1035 | Requires a preceding call to get_rt_log to update to the latest status."""
1036 | return (
1037 | self._status.aux_in_status[aux_nr]
1038 | if aux_nr in self._status.aux_in_status
1039 | else consts.InOutStatus.UNKNOWN
1040 | )
1041 |
1042 | def aux_out_status(self, aux_nr: int) -> consts.InOutStatus:
1043 | """Returns the (cached) auxiliary output open/close status.
1044 | Requires a preceding call to get_rt_log to update to the latest status."""
1045 | return (
1046 | self._status.aux_out_status[aux_nr]
1047 | if aux_nr in self._status.aux_out_status
1048 | else consts.InOutStatus.UNKNOWN
1049 | )
1050 |
--------------------------------------------------------------------------------
/c3/crc.py:
--------------------------------------------------------------------------------
1 | # Ported CRC-16 from libcrc.org
2 | # (https://github.com/lammertb/libcrc/blob/master/src/crc16.c)
3 |
4 | CRC_POLY_16 = 0xA001
5 | CRC_START_16 = 0x0000
6 |
7 |
8 | class Crc16Builder:
9 | def __init__(self, crc: int = None):
10 | self._crc = crc or CRC_START_16
11 |
12 | @classmethod
13 | def _calc_divisor(cls, byte):
14 | poly = 0
15 |
16 | for _ in range(8):
17 | if ((poly ^ byte) & 0x0001) == 1:
18 | poly = (poly >> 1) ^ CRC_POLY_16
19 | else:
20 | poly = poly >> 1
21 |
22 | byte = byte >> 1
23 |
24 | return poly
25 |
26 | def add_byte(self, data: int):
27 | data = data & 0xFF # Limit data size to byte
28 | crc = self._crc & 0xFFFF # Truncate to 16bit
29 | msb = crc >> 8 # Take msb from 16bit crc
30 | self._crc = msb ^ self._calc_divisor(crc ^ data)
31 |
32 | @property
33 | def crc(self):
34 | return self._crc & 0xFFFF
35 |
36 |
37 | def crc16(data, crc=None):
38 | builder = Crc16Builder(crc)
39 |
40 | if hasattr(data, "__iter__"):
41 | for byte in data:
42 | if isinstance(byte, int):
43 | builder.add_byte(byte)
44 | elif isinstance(byte, str):
45 | if len(byte) == 1:
46 | builder.add_byte(ord(byte))
47 | else:
48 | for char in byte:
49 | builder.add_byte(ord(char))
50 | else:
51 | raise TypeError("Data of type %s is not supported" % type(byte))
52 | else:
53 | raise TypeError("Data '%s' is not iterable" % data)
54 |
55 | return builder.crc
56 |
--------------------------------------------------------------------------------
/c3/rtlog.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | from abc import ABC, abstractmethod
4 |
5 | from c3 import consts
6 | from c3.utils import C3DateTime
7 |
8 |
9 | class RTLogRecord(ABC):
10 | @abstractmethod
11 | def is_door_alarm(self) -> bool:
12 | ...
13 |
14 | @abstractmethod
15 | def is_event(self) -> bool:
16 | ...
17 |
18 |
19 | class DoorAlarmStatusRecord(RTLogRecord):
20 | """Realtime Log record for a door and alarm status"""
21 |
22 | def __init__(self):
23 | self.alarm_status = bytes(4)
24 | self.dss_status = bytes(4)
25 | self.verified: consts.VerificationMode = consts.VerificationMode.NONE
26 | self.event_type: consts.EventType = consts.EventType.NA
27 | self.time_second = 0
28 |
29 | @classmethod
30 | def from_bytes(cls, data: bytes):
31 | """Create DoorAlarmStatusRecord from binary log
32 | An RTLog is a binary message of 16 bytes send by the C3 access panel.
33 | If the value of byte 10 (the event type) is 255, the RTLog is a Door/Alarm Realtime Status.
34 | If the value of byte 10 (the event type) is not 255, the RTLog is a Realtime Event.
35 |
36 | Door/Alarm Realtime Status record
37 | All multibyte values are stored as Little-endian.
38 |
39 | Byte: 0 1 2 3 4 5 6 7 8 9 A B C D E F
40 | 01:4f:86:00:99:92:98:00:04:01:00:00:a5:ad:ad:21
41 | Alarm status (byte 4-7): |
42 | 99:92:98:00 => (big endian:) 00989299 = 9999001
43 | DSS status (byte 0-3): |
44 | 01:4f:86:00 => (big endian:) 00864f01 = 8802049
45 | Verified (byte 8): |
46 | 04
47 | Unused (byte 9): |
48 | 01
49 | EventType (byte 10): |
50 | 00
51 | Unused (byte 11): |
52 | 00
53 | |
54 | Time_second (byte 12-15) a5:ad:ad:21 => (big endian:) 21ADADA5 =
55 | 2017-7-30 16:51:49
56 | """
57 | record = DoorAlarmStatusRecord()
58 | record.alarm_status = bytes(data[0:4])
59 | record.dss_status = bytes(data[4:8])
60 | try:
61 | record.verified = consts.VerificationMode(data[9])
62 | except ValueError:
63 | record.verified = consts.VerificationMode.OTHER
64 | try:
65 | record.event_type = consts.EventType(data[10])
66 | except ValueError:
67 | record.event_type = consts.EventType.UNKNOWN_UNSUPPORTED
68 | record.time_second = C3DateTime.from_value(
69 | int.from_bytes(data[12:16], byteorder="little")
70 | )
71 | return record
72 |
73 | @classmethod
74 | def from_kv(cls, data: dict):
75 | """Create EventRecord from text-based key/value log
76 | A key/value log contains the following fields:
77 | {
78 | 'time': '2023-12-09 15:09:33',
79 | 'sensor': '24',
80 | 'relay': '04',
81 | 'alarm': '00000000'
82 | }
83 | """
84 | record = DoorAlarmStatusRecord()
85 | record.alarm_status = bytes.fromhex(data["alarm"])
86 | sensor = int(data["sensor"], base=16)
87 | record.dss_status = bytes([(sensor >> (i * 2)) & 0x03 for i in range(0, 4)])
88 | # relay = 00
89 | # try:
90 | # record.verified = consts.VerificationMode(data[9])
91 | # except ValueError:
92 | # record.verified = consts.VerificationMode.OTHER
93 | # try:
94 | # record.event_type = consts.EventType(data[10])
95 | # except ValueError:
96 | # record.event_type = consts.EventType.UNKNOWN_UNSUPPORTED
97 | record.time_second = C3DateTime.from_str(data["time"])
98 | return record
99 |
100 | def is_door_alarm(self) -> bool:
101 | return True
102 |
103 | def is_event(self) -> bool:
104 | return False
105 |
106 | def get_alarms(self, door_nr: int) -> list[consts.AlarmStatus]:
107 | alarms = []
108 |
109 | for i in range(0, 3):
110 | if i + 1 == door_nr or not door_nr:
111 | if self.alarm_status[i] & consts.AlarmStatus.ALARM:
112 | if alarms.count(consts.AlarmStatus.ALARM) == 0:
113 | alarms.append(consts.AlarmStatus.ALARM)
114 | elif self.alarm_status[i] & consts.AlarmStatus.DOOR_OPEN_TIMEOUT:
115 | if alarms.count(consts.AlarmStatus.DOOR_OPEN_TIMEOUT) == 0:
116 | alarms.append(consts.AlarmStatus.DOOR_OPEN_TIMEOUT)
117 |
118 | return alarms
119 |
120 | def has_alarm(self, door_nr: int, status: consts.AlarmStatus = None):
121 | return ((self.alarm_status[door_nr - 1] & (status or 0)) == status) or (
122 | (self.alarm_status[door_nr - 1] > 0) and status is None
123 | )
124 |
125 | def door_sensor_status(self, door_nr: int) -> consts.InOutStatus:
126 | return consts.InOutStatus(self.dss_status[door_nr - 1] & 0x0F)
127 |
128 | def door_is_open(self, door_nr: int):
129 | is_open = None
130 |
131 | if self.door_sensor_status(door_nr) == consts.InOutStatus.OPEN:
132 | is_open = True
133 | elif self.door_sensor_status(door_nr) == consts.InOutStatus.CLOSED:
134 | is_open = False
135 |
136 | return is_open
137 |
138 | def __repr__(self):
139 | repr_arr = [
140 | "Door/Alarm Realtime Status:",
141 | "%-12s %-10s" % ("time_second", self.time_second),
142 | "%-12s %-10s %s" % ("event_type", self.event_type, repr(self.event_type)),
143 | "%-12s %-10s %s" % ("verified", self.verified, repr(self.verified)),
144 | "%-12s %-10s" % ("alarm_status", self.alarm_status.hex()),
145 | ]
146 |
147 | for i in range(0, 4):
148 | for status in consts.AlarmStatus:
149 | if status != consts.AlarmStatus.NONE:
150 | if self.alarm_status[i] & status == status:
151 | repr_arr.append(
152 | " Door %-2s %-4s %s" % (i, status, repr(status))
153 | )
154 |
155 | repr_arr.append("%-12s %-10s" % ("dss_status", self.dss_status.hex()))
156 | for i in range(0, 4):
157 | repr_arr.append(
158 | " Door %-2s %-4s %s"
159 | % (
160 | i + 1,
161 | self.dss_status[i],
162 | repr(consts.InOutStatus(self.dss_status[i] & 0x0F)),
163 | )
164 | )
165 |
166 | return "\r\n".join(repr_arr)
167 |
168 |
169 | class EventRecord(RTLogRecord):
170 | """Realtime Event record"""
171 |
172 | def __init__(self):
173 | self.card_no = 0
174 | self.pin = 0
175 | self.verified: consts.VerificationMode = consts.VerificationMode.NONE
176 | self.port_nr: int = 0
177 | self.event_type: consts.EventType = consts.EventType.NA
178 | self.in_out_state: consts.InOutDirection = consts.InOutDirection.NONE
179 | self.time_second = 0
180 |
181 | @classmethod
182 | def from_bytes(cls, data: bytes):
183 | """Create EventRecord from binary log
184 | All multibyte values are stored as Little-endian.
185 |
186 | Byte: 0 1 2 3 4 5 6 7 8 9 A B C D E F
187 | 01:4f:86:00:99:92:98:00:04:01:00:00:a5:ad:ad:21
188 | Cardno (byte 4-7): |
189 | 99:92:98:00 => (big endian:) 00989299 = 9999001
190 | Pin (byte 0-3): |
191 | 01:4f:86:00 => (big endian:) 00864f01 = 8802049
192 | Verified (byte 8): |
193 | 04
194 | DoorID (byte 9): |
195 | 01
196 | EventType (byte 10): |
197 | 00
198 | InOutState (byte 11): |
199 | 00
200 | |
201 | Time_second (byte 12-15) a5:ad:ad:21 => (big endian)21ADADA5 = 2017-07-30 16:51:49
202 | """
203 | record = EventRecord()
204 | record.card_no = int.from_bytes(data[0:4], byteorder="little")
205 | record.pin = int.from_bytes(data[4:8], byteorder="little")
206 | try:
207 | record.verified = consts.VerificationMode(data[8])
208 | except ValueError:
209 | record.verified = consts.VerificationMode.OTHER
210 | record.port_nr = data[9]
211 | try:
212 | record.event_type = consts.EventType(data[10])
213 | except ValueError:
214 | record.event_type = consts.EventType.UNKNOWN_UNSUPPORTED
215 | try:
216 | record.in_out_state = consts.InOutDirection(data[11])
217 | except ValueError:
218 | record.in_out_state = consts.InOutDirection.UNKNOWN_UNSUPPORTED
219 | record.time_second = C3DateTime.from_value(
220 | int.from_bytes(data[12:16], byteorder="little")
221 | )
222 | return record
223 |
224 | @classmethod
225 | def from_kv(cls, data: dict):
226 | """Create EventRecord from text-based key/value log
227 | A key/value log contains the following fields:
228 | {
229 | 'time': '2023-12-06 22:33:15',
230 | 'pin': '0',
231 | 'cardno': '0',
232 | 'eventaddr': '1',
233 | 'event': '8',
234 | 'inoutstatus': '2',
235 | 'verifytype': '200',
236 | 'index': '9'
237 | }
238 | """
239 | record = EventRecord()
240 | record.card_no = int(data["cardno"])
241 | record.pin = int(data["pin"])
242 | try:
243 | record.verified = consts.VerificationMode(int(data["verifytype"]))
244 | except ValueError:
245 | record.verified = consts.VerificationMode.OTHER
246 | record.port_nr = int(data["eventaddr"])
247 | try:
248 | record.event_type = consts.EventType(int(data["event"]))
249 | except ValueError:
250 | record.event_type = consts.EventType.UNKNOWN_UNSUPPORTED
251 | try:
252 | record.in_out_state = consts.InOutDirection(int(data["inoutstatus"]))
253 | except ValueError:
254 | record.in_out_state = consts.InOutDirection.UNKNOWN_UNSUPPORTED
255 | record.time_second = C3DateTime.from_str(data["time"])
256 | return record
257 |
258 | def is_door_alarm(self) -> bool:
259 | return False
260 |
261 | def is_event(self) -> bool:
262 | return True
263 |
264 | def __repr__(self):
265 | repr_arr = [
266 | "Realtime Event:",
267 | "%-12s %-10s" % ("time_second", self.time_second),
268 | "%-12s %-10s %s" % ("event_type", self.event_type, repr(self.event_type)),
269 | "%-12s %-10s %s"
270 | % ("in_out_state", self.in_out_state, repr(self.in_out_state)),
271 | "%-12s %-10s %s" % ("verified", self.verified, repr(self.verified)),
272 | "%-12s %-10s" % ("card_no", self.card_no),
273 | # "%-12s %-10s" % ("pin", self.pin),
274 | "%-12s %-10s" % ("port_no", self.port_nr),
275 | ]
276 |
277 | return "\r\n".join(repr_arr)
278 |
279 |
280 | def factory(
281 | log_message: [bytes, bytearray, dict]
282 | ) -> DoorAlarmStatusRecord | EventRecord:
283 | if isinstance(log_message, (bytes, bytearray)):
284 | if log_message[10] == consts.EventType.DOOR_ALARM_STATUS:
285 | rtlog = DoorAlarmStatusRecord.from_bytes(log_message)
286 | else:
287 | rtlog = EventRecord.from_bytes(log_message)
288 | elif isinstance(log_message, dict):
289 | if "event" in log_message:
290 | rtlog = EventRecord.from_kv(log_message)
291 | else:
292 | rtlog = DoorAlarmStatusRecord.from_kv(log_message)
293 | else:
294 | raise NotImplementedError(f"RT log type {type(log_message)} is not supported")
295 |
296 | return rtlog
297 |
--------------------------------------------------------------------------------
/c3/utils.py:
--------------------------------------------------------------------------------
1 | import math
2 | from datetime import datetime
3 |
4 |
5 | def lsb(data):
6 | return data & 0x00FF
7 |
8 |
9 | def msb(data):
10 | return (data >> 8) & 0x00FF
11 |
12 |
13 | def byte_to_signed_int(byte, size=8):
14 | """Two's complement conversion from byte to int"""
15 | value = int(byte, 16) if isinstance(byte, str) else int(byte)
16 | if value & (1 << (size - 1)):
17 | value -= 1 << size
18 | return value
19 |
20 |
21 | class C3DateTime(datetime):
22 | @classmethod
23 | def from_value(cls, value: int):
24 | """Converts a C3 time byte array in Big-Endian encoding to a datetime object
25 | In the C3 protocol, the time is stored in seconds as a byte array
26 |
27 | DateTime= ((Year-2000)*12*31 + (Month -1)*31 + (Day-1))*(24*60*60) + Hour* 60 *60 + Minute*60 + Second
28 | For example, the now datetime is 2010-10-26 20:54:55, so DateTime= 347748895
29 |
30 | And calculate the reverse “DateTime = 347748895”
31 | Second = DateTime % 60
32 | Minute = ( DateTime / 60 ) % 60
33 | Hour = ( DateTime / 3600 ) % 24
34 | Day = ( DateTime / 86400 ) % 31 + 1
35 | Month= ( DateTime / 2678400 ) % 12 + 1
36 | Year = (DateTime / 32140800 ) + 2000"""
37 | return C3DateTime(
38 | year=math.floor(value / 32140800) + 2000,
39 | month=math.floor(value / 2678400) % 12 + 1,
40 | day=math.floor(value / 86400) % 31 + 1,
41 | hour=math.floor(value / 3600) % 24,
42 | minute=math.floor(value / 60) % 60,
43 | second=value % 60,
44 | )
45 |
46 | @classmethod
47 | def from_str(cls, value: str):
48 | """Converts a datetime string like '2023-12-06 22:33:15' to a datetime object"""
49 | return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
50 |
51 | def to_value(self) -> int:
52 | return (
53 | ((self.year - 2000) * 12 * 31 + (self.month - 1) * 31 + (self.day - 1))
54 | * (24 * 60 * 60)
55 | + (self.hour * 60 * 60)
56 | + (self.minute * 60)
57 | + self.second
58 | )
59 |
--------------------------------------------------------------------------------
/cli/C3_CancelAlarms.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 |
6 | from c3 import C3, controldevice
7 |
8 |
9 | def main():
10 | parser = argparse.ArgumentParser()
11 | parser.add_argument("host", help="C3 panel IP address or host name")
12 | parser.add_argument("--password", help="Password")
13 | parser.add_argument(
14 | "--debug",
15 | action=argparse.BooleanOptionalAction,
16 | help="Enable verbose debug output",
17 | )
18 | args = parser.parse_args()
19 |
20 | print("Connecting to %s" % args.host)
21 | panel = C3(args.host)
22 |
23 | if args.debug:
24 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
25 | panel.log.setLevel(logging.DEBUG)
26 |
27 | try:
28 | if panel.connect(args.password):
29 | panel.control_device(controldevice.ControlDeviceCancelAlarms())
30 | except Exception as e:
31 | print(f"Cancel alarms faied: {e}")
32 | finally:
33 | panel.disconnect()
34 |
35 |
36 | if __name__ == "__main__":
37 | main()
38 |
--------------------------------------------------------------------------------
/cli/C3_Discover.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 |
6 | from c3 import C3
7 |
8 |
9 | def main():
10 | parser = argparse.ArgumentParser()
11 | parser.add_argument(
12 | "--interface", help="IP address of the interface to look for devices on"
13 | )
14 | parser.add_argument(
15 | "--debug",
16 | action=argparse.BooleanOptionalAction,
17 | help="Enable verbose debug output",
18 | )
19 | args = parser.parse_args()
20 |
21 | if args.debug:
22 | C3.log.addHandler(logging.StreamHandler(sys.stdout))
23 | C3.log.setLevel(logging.DEBUG)
24 |
25 | devices = C3.discover(args.interface)
26 | for device in devices:
27 | print(f"Found device ({device.mac or '?'}):")
28 | print(repr(device))
29 |
30 |
31 | if __name__ == "__main__":
32 | main()
33 |
--------------------------------------------------------------------------------
/cli/C3_GetDeviceData.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 |
6 | from c3 import C3
7 | from c3.utils import C3DateTime
8 |
9 |
10 | def main():
11 | parser = argparse.ArgumentParser()
12 | parser.add_argument("host", help="C3 panel IP address or host name")
13 | parser.add_argument("--password", help="Password")
14 | parser.add_argument("--table", help="Table to request")
15 | parser.add_argument("--field", nargs="+", help="Field name(s) to request")
16 | parser.add_argument(
17 | "--debug",
18 | action=argparse.BooleanOptionalAction,
19 | help="Enable verbose debug output",
20 | )
21 | args = parser.parse_args()
22 |
23 | print("Connecting to %s" % args.host)
24 | panel = C3(args.host)
25 |
26 | if args.debug:
27 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
28 | panel.log.setLevel(logging.DEBUG)
29 |
30 | try:
31 | if panel.connect(args.password):
32 | print("Device:")
33 | print(repr(panel))
34 |
35 | data = panel.get_device_data(args.table, args.field)
36 | if data:
37 | print("Device Data records:")
38 | else:
39 | print("No device data records")
40 | for record in data:
41 | first = True
42 | for field_name, field_value in record.items():
43 | print(
44 | "%s %s: %s"
45 | % ("-" if first else " ", field_name, str(field_value))
46 | )
47 | first = False
48 |
49 | except Exception as e:
50 | print(f"Parameter retrieval failed: {e}")
51 | finally:
52 | panel.disconnect()
53 |
54 |
55 | if __name__ == "__main__":
56 | main()
57 |
--------------------------------------------------------------------------------
/cli/C3_GetDeviceParam.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 |
6 | from c3 import C3
7 | from c3.utils import C3DateTime
8 |
9 |
10 | def main():
11 | parser = argparse.ArgumentParser()
12 | parser.add_argument("host", help="C3 panel IP address or host name")
13 | parser.add_argument("--password", help="Password")
14 | parser.add_argument("--param", nargs="+", help="Parameter name(s) to request")
15 | parser.add_argument(
16 | "--debug",
17 | action=argparse.BooleanOptionalAction,
18 | help="Enable verbose debug output",
19 | )
20 | args = parser.parse_args()
21 |
22 | print("Connecting to %s" % args.host)
23 | panel = C3(args.host)
24 |
25 | if args.debug:
26 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
27 | panel.log.setLevel(logging.DEBUG)
28 |
29 | try:
30 | if panel.connect(args.password):
31 | print("Device:")
32 | print(repr(panel))
33 |
34 | param_names = args.param or [
35 | "~ZKFPVersion",
36 | "~SerialNumber",
37 | "FirmVer",
38 | "DeviceName",
39 | "LockCount",
40 | "ReaderCount",
41 | "AuxInCount",
42 | "AuxOutCount",
43 | "DateTime",
44 | ]
45 | params = panel.get_device_param(param_names)
46 |
47 | for k in params:
48 | if k == "DateTime":
49 | print(
50 | "- %s: %s"
51 | % (k, C3DateTime.from_value(int(params.get(k))).isoformat())
52 | )
53 | else:
54 | print("- %s: %s" % (k, params.get(k)))
55 | except Exception as e:
56 | print(f"Parameter retrieval failed: {e}")
57 | finally:
58 | panel.disconnect()
59 |
60 |
61 | if __name__ == "__main__":
62 | main()
63 |
--------------------------------------------------------------------------------
/cli/C3_GetRTLog.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 | import time
6 |
7 | from c3 import C3, rtlog
8 |
9 |
10 | def main():
11 | parser = argparse.ArgumentParser()
12 | parser.add_argument("host", help="C3 panel IP address or host name")
13 | parser.add_argument("--password", help="Password")
14 | parser.add_argument(
15 | "--debug",
16 | action=argparse.BooleanOptionalAction,
17 | help="Enable verbose debug output",
18 | )
19 | args = parser.parse_args()
20 |
21 | print("Connecting to %s" % args.host)
22 | panel = C3(args.host)
23 |
24 | if args.debug:
25 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
26 | panel.log.setLevel(logging.DEBUG)
27 |
28 | if panel.connect(args.password):
29 | try:
30 | while True:
31 | last_record_is_status = False
32 | records = []
33 |
34 | if not panel.is_connected():
35 | panel.connect(args.password)
36 |
37 | try:
38 | records = panel.get_rt_log()
39 | except ConnectionError as ex:
40 | print(f"Error retrieving RT logs: {ex}")
41 | panel.disconnect()
42 |
43 | for record in records:
44 | print(repr(record))
45 | if isinstance(record, rtlog.DoorAlarmStatusRecord):
46 | last_record_is_status = True
47 |
48 | print(
49 | f"Door status: {[repr(panel.lock_status(i+1)) for i in range(panel.nr_of_locks)]}:"
50 | )
51 | print(
52 | f"Aux status: {[repr(panel.aux_out_status(i+1)) for i in range(panel.nr_aux_out)]}:"
53 | )
54 |
55 | if last_record_is_status:
56 | time.sleep(9)
57 |
58 | print("-" * 25)
59 |
60 | time.sleep(1)
61 | except KeyboardInterrupt:
62 | pass
63 |
64 | panel.disconnect()
65 |
66 |
67 | if __name__ == "__main__":
68 | main()
69 |
--------------------------------------------------------------------------------
/cli/C3_OutputOperation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 |
6 | from c3 import C3, consts, controldevice
7 |
8 |
9 | def main():
10 | parser = argparse.ArgumentParser()
11 | parser.add_argument("host", help="C3 panel IP address or host name")
12 | parser.add_argument("--password", help="Password")
13 | parser.add_argument(
14 | "--output",
15 | choices=["door", "aux"],
16 | required=True,
17 | help="Output is door or auxiliary",
18 | )
19 | parser.add_argument(
20 | "--number", type=int, required=True, help="Door or auxiliary output number"
21 | )
22 | group = parser.add_mutually_exclusive_group(required=True)
23 | group.add_argument("--open", action="store_true", help="Set state to normal open")
24 | group.add_argument("--close", action="store_true", help="Set state to closed")
25 | parser.add_argument(
26 | "--duration", type=int, help="Duration to (temporarily) open the door"
27 | )
28 | parser.add_argument(
29 | "--debug",
30 | action=argparse.BooleanOptionalAction,
31 | help="Enable verbose debug output",
32 | )
33 | args = parser.parse_args()
34 |
35 | duration = 0
36 | if args.open:
37 | duration = (
38 | args.duration or 255
39 | ) # Use default open when no duration is specified
40 |
41 | print("Connecting to %s" % args.host)
42 | panel = C3(args.host)
43 |
44 | if args.debug:
45 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
46 | panel.log.setLevel(logging.DEBUG)
47 |
48 | try:
49 | if panel.connect(args.password):
50 | operation = controldevice.ControlDeviceOutput(
51 | args.number,
52 | consts.ControlOutputAddress.AUX_OUTPUT
53 | if args.output == "aux"
54 | else consts.ControlOutputAddress.DOOR_OUTPUT,
55 | duration,
56 | )
57 | panel.control_device(operation)
58 | except Exception as e:
59 | print(f"Parameter retrieval failed: {e}")
60 | finally:
61 | panel.disconnect()
62 |
63 |
64 | if __name__ == "__main__":
65 | main()
66 |
--------------------------------------------------------------------------------
/cli/C3_SetDeviceDatetime.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import logging
4 | import sys
5 | from datetime import datetime
6 |
7 | from c3 import C3
8 | from c3.utils import C3DateTime
9 |
10 |
11 | def main():
12 | parser = argparse.ArgumentParser()
13 | parser.add_argument("host", help="C3 panel IP address or host name")
14 | parser.add_argument("--password", help="Password")
15 | parser.add_argument(
16 | "--time",
17 | type=datetime.fromisoformat,
18 | help="Time to set as ISO format, e.g. YYYY-MM-DD HH:mm:ss (defaults to now)",
19 | )
20 | parser.add_argument(
21 | "--debug",
22 | action=argparse.BooleanOptionalAction,
23 | help="Enable verbose debug output",
24 | )
25 | args = parser.parse_args()
26 |
27 | print("Connecting to %s" % args.host)
28 | panel = C3(args.host)
29 |
30 | if args.debug:
31 | panel.log.addHandler(logging.StreamHandler(sys.stdout))
32 | panel.log.setLevel(logging.DEBUG)
33 |
34 | try:
35 | if panel.connect(args.password):
36 | print("Device:")
37 | print(repr(panel))
38 |
39 | panel.set_device_datetime(args.time or datetime.now())
40 |
41 | params = panel.get_device_param(["DateTime"])
42 | for k in params:
43 | if k == "DateTime":
44 | print(
45 | "- %s: %s"
46 | % (k, C3DateTime.from_value(int(params.get(k))).isoformat())
47 | )
48 | except Exception as e:
49 | print(f"Setting the date/time failed: {e}")
50 | finally:
51 | panel.disconnect()
52 |
53 |
54 | if __name__ == "__main__":
55 | main()
56 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "zkaccess_c3"
3 | version = "0.0.15"
4 | description = "A native Python library for communicating with the ZKAccess C3 and inBio Door Access Control Panels."
5 | authors = [
6 | {name = "Vwout", email="vwout@users.noreply.github.com"},
7 | ]
8 | #license = "GPL-3.0-or-later"
9 | readme = "readme.md"
10 | requires-python = ">=3.7"
11 | classifiers = [
12 | "Programming Language :: Python :: 3",
13 | "Operating System :: OS Independent",
14 | ]
15 |
16 | [project.urls]
17 | "Homepage" = "https://github.com/vwout/zkaccess-c3-py"
18 | "Bug Tracker" = "https://github.com/vwout/zkaccess-c3-py/issues"
19 |
20 | [build-system]
21 | requires = ["setuptools>=61.0", "setuptools-scm"]
22 | build-backend = "setuptools.build_meta"
23 |
24 | [tool.setuptools.packages.find]
25 | include = ["c3"]
26 |
27 | [tool.pytest.ini_options]
28 | addopts = [
29 | "--import-mode=importlib",
30 | ]
31 |
32 | [tool.pylint]
33 | max-line-length = 120
34 | disable = ["C0114", "C0115", "C0116", "C0209", "R0801"]
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # C3
2 | A native Python library for communicating with the ZKTeco ZKAccess C3 Access Control Panels.
3 |
4 | This library intends to implement the same functionality as provided by the ZKAccess C3 PullSDK API, but using native Python only.
5 | The full documentation of the official SDK is available from [ZKTeco](https://www.zkteco.com.pk/SoftwareDevelopmentKit/pullsdk).
6 | A snapshot can be found at [licjapodaca/Pull-SDK-Demo](https://github.com/licjapodaca/Pull-SDK-Demo) or [hmojicag/ZKTecoStandAlonePullSDK](https://github.com/hmojicag/ZKTecoStandAlonePullSDK).
7 |
8 | [](https://opensource.org/licenses/)
9 | 
10 | [](https://pypi.python.org/pypi/zkaccess-c3/)
11 | [](https://github.com/psf/black)
12 |
13 | ## Usage
14 | To use the library, import the main class:
15 | ```
16 | from c3 import C3
17 | ```
18 | A panel connection can be created from the main class `C3`:
19 | ```
20 | panel = C3(ip)
21 | if panel.connect():
22 | panel.get_device_param(["~SerialNumber", "LockCount")
23 | ```
24 | To use the real-time log (RTLog), or control outputs, also include the helper classes from `controldevice` and `rtlog`.
25 |
26 | ## Compatible devices
27 | The following devices are tested and known compatible:
28 | - C3-200 (firmware AC Ver 4.1.9 4609-03 Apr 7 2016)
29 | - C3-400 (firmware AC Ver 4.3.4 Apr 27 2017)
30 | - C3-400 (firmware AC Ver 5.4.3.2001 Sep 25 2019)
31 | - inBio 460 (firmware AC Ver 5.0.9 4609-06 - Sep 15 2017) (probably 260 and 160 also work)
32 |
33 | ## Protocol
34 | The C3 access panels communicate using RS485 or TCP/IP.
35 | This library only support TCP/IP connections using IPv4.
36 | The connection is optionally secured by a password.
37 |
38 | The wire protocol for the access panels is binary, with the following datagram both for requests (from client to equipment) and responses:
39 |
40 | | Byte | 0 | 1 | 2 | 3 | 4 | 5,6,7,8, ... | n-2, n-1 | n |
41 | |-------------|--------|---------|---------|------------|------------|---------------|----------|---------|
42 | | **Meaning** | Start | Version | Command | Length LSB | Length MSB | Data | Checksum | End |
43 | | **Value** | `0xAA` | `0x01` | | | | | | `0x55` |
44 |
45 | - The start bytes 0, 1 and last byte have a fixed value.
46 | - The *Command* is one of the following (only listing commands supported by this library)
47 |
48 | | Code | Command |
49 | |--------|----------------------------------------------------|
50 | | `0x01` | Connect (without session initiation) |
51 | | `0x02` | Disconnect |
52 | | `0x03` | Set datetime |
53 | | `0x04` | Get parameters |
54 | | `0x05` | Device control command |
55 | | `0x06` | Get datatable configuration |
56 | | `0x08` | Retrieve data from datatable |
57 | | `0x0B` | Retrieve realtime log |
58 | | `0x14` | Device discovery |
59 | | `0x76` | Connect (session initiation) |
60 | | `0x79` | Realtime log key-values |
61 | | `0xC8` | Response (confirm successful execution of command) |
62 |
63 | - The *Length* field (2 bytes, in Little Endian encoding) contains the number of bytes of the *Data* field.
64 | - The *Data* field (as of byte 5) may use 4 reserved bytes in front of actual payload:
65 | - Session Id (2 bytes, in Little Endian encoding): The session identifier assigned by the equipment in response to a session initiation command
66 | - Message Number (2 bytes, in Little Endian encoding): A message sequence number that starts from -258 (the session initiation command) and is increased with every command send
67 |
68 | | Byte | 5 | 6 | 7 | 8 | ... |
69 | |--------------|---------------|---------------|----------------|----------------|----------|
70 | | **Meaning** | SessionId Lsb | SessionId Msb | Message Nr Lsb | Message Nr Msb | Payload |
71 |
72 | Whether the Session Id and Message Number is used, depends on how the connection is made (using either command 0x01 or 0x76).
73 | The support for these commands varies per panel / firmware combination.
74 |
75 | - The *Checksum* is a CRC-16 checksum calculated over the full message excluding the *Start* and *End* byte.
76 |
77 | ## API
78 |
79 | ### Connect
80 | ```
81 | connect(password)
82 | ```
83 | The method is used to connect a C3 device using TCP.
84 | RS485 is not supported, neither is using a password to secure the connection.
85 | This method must be called before any other method and initializes a C3 session.
86 | The parameter `password` is optional, when omitted, a connection attempt is made without password.
87 | Returns true in case of a successful connection.
88 |
89 | ### Disconnect
90 | ```
91 | disconnect()
92 | ```
93 |
94 | Disconnects from the C3 access panel and ends the session.
95 |
96 | ### SetDeviceDatetime
97 | ```
98 | set_device_datetime(self, time)
99 | ```
100 | Sets the device date/time as ISO timestamp.
101 |
102 |
103 | ### SetDeviceParam
104 | Not implemented yet.
105 |
106 | ### Get Device Parameters
107 | ```
108 | get_device_param(params_arr)
109 | ```
110 |
111 | This method reads device parameters, both configuration and static parameters.
112 | The argument is a list of (maximum 30) strings with the parameter names for which the values need to be returned.
113 | Valid values are (reduced list):
114 | - ~CardFormatFunOn, ~DeviceName, ~Ext485ReaderFunOn, ~IsOnlyRFMachine, ~MaxAttLogCount, ~MaxUserCount, ~MaxUserFingerCount, ~SerialNumber, ~ZKFPVersion,
115 | AntiPassback, AuxInCount, AuxOutCount, BackupTime, DateTime, DaylightSavingTime, DaylightSavingTimeOn, DeviceID, DLSTMode,
116 | Door{N}CancelKeepOpenDay, Door{N}CloseAndLock, Door{N}Detectortime, Door{N}Drivertime, Door{N}FirstCardOpenDoor, Door{N}ForcePassWord, Door{N}Intertime, Door{N}KeepOpenTimeZone, Door{N}MultiCardOpenDoor, Door{N}SensorType, Door{N}SupperPassWord, Door{N}ValidTZ, Door{N}VerifyType,
117 | Door4ToDoor2, FirmVer, GATEIPAddress, InBIOTowWay, InterLock,
118 | IPAddress, LockCount, MachineType, MasterInbio485, MThreshold, NetMask, PC485AsInbio485, ReaderCount, Reboot, RS232BaudRate, SimpleEventType, StandardTime, WatchDog, WeekOfMonth{N}
119 |
120 | For the full list and the meaning of the returned value, refer to the PullSDK specification.
121 | The return value is a table of key/value pairs with the parameter name and value.
122 |
123 | ### Control Device
124 | ```
125 | control_device(control_command_object)
126 | ```
127 |
128 | Sends a control command to the access panel to perform an action on the requipment. The control_command is an instance of one of the following objects:
129 | - `ControlDeviceOutput(output_number, address, duration)`: Open or close a door or auxiliary device
130 | - *output_number*: The number of the door or auxiliary to control (1-4)
131 | - *address*: Determines whether *door_number* is a door (*address* = 1) or an auxiliary (*address* = 2)
132 | - *duration*: The duration for which the door will be open; 0 will close the door immediately, 1-254 will leave the door open for that number of seconds: 255 will leave the door open for an undetermined period
133 | - `ControlDeviceCancelAlarms()`: Cancel any triggered alarm
134 | - `ControlDeviceRestart()`: Reboot the access panel
135 | - `ControlDeviceNormalOpenStateEnable(door_number, enable_disable)`: Change the normal open/close state for the door controller
136 | - *door_number*: The number of the door to control (1-4)
137 | - *enable*: Enable normally open mode (*enable* = True) or disable normally open mode for the door (*enable_disable* = 0, default)
138 |
139 |
140 | ### SetDeviceData
141 | Not implemented yet.
142 |
143 | ### Get Device Data
144 | ```
145 | get_device_data(table_name, field_names)
146 | ```
147 |
148 | Read the device data (such as the user configuration, user access, timezones and holiday information).
149 | The method supports the following tables and will return al available records for:
150 | - user
151 | - userauthorize
152 | - holiday
153 | - timezone
154 | - transaction
155 | - firstcard
156 | - multicard or multimcard
157 | - inoutfun
158 | - template
159 | - templatev10
160 |
161 | The table support varies between devices and firmwares.
162 | When no table is provided, the method will raise an exception listing all supported tables.
163 | The data is returned as a list of records, with a key/value dictionary per record.
164 |
165 | ### GetDeviceDataCount
166 | Not implemented yet.
167 |
168 | ### DeleteDeviceData
169 | Not implemented yet.
170 |
171 | ### Get RT Log (real-time log)
172 | ```
173 | get_rt_log()
174 | ```
175 |
176 | This method acquires the realtime event log generated by the access panel.
177 | It contains the door and/or alarm status of the equipment.
178 | It returns an array of DoorAlarmStatusRecord and/or EventRecord objects.
179 |
180 | ### SearchDevice
181 | Not implemented yet.
182 |
183 | ### ModifyIPAddress
184 | Not implemented yet.
185 |
186 | ### PullLastError
187 | Not implemented yet.
188 |
189 | ### SetDeviceFileData
190 | Not implemented yet.
191 |
192 | ### GetDeviceFileData
193 | Not implemented yet.
194 |
195 | ### ProcessBackupData
196 | Not implemented yet.
197 |
198 | ### Set log level
199 | ```
200 | log_level(level)
201 | ```
202 | Sets the logging level, using the Python logging levels.
203 |
--------------------------------------------------------------------------------
/requirements-dev.txt:
--------------------------------------------------------------------------------
1 | black==23.9.1
2 | colorlog==6.7.0
3 | isort==5.12.0
4 | ruff==0.0.267
5 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup()
4 |
--------------------------------------------------------------------------------
/tests/test_consts.py:
--------------------------------------------------------------------------------
1 | from c3.consts import *
2 |
3 |
4 | def test_commands():
5 | connect_cmd = Command.CONNECT_SESSION
6 | assert 0x76 == connect_cmd
7 | connect_reply = C3_REPLY_OK
8 | assert 0xC8 == connect_reply
9 |
10 |
11 | def test_control_operation():
12 | cancel_alarm = ControlOperation.CANCEL_ALARM
13 | assert 2 == int(cancel_alarm)
14 | assert "2" == str(cancel_alarm)
15 | assert "Cancel alarm" == cancel_alarm.description
16 | assert "2" == "%s" % cancel_alarm
17 | assert "Cancel alarm" == "%r" % cancel_alarm
18 |
19 |
20 | def test_door_sensor_status():
21 | assert InOutStatus.UNKNOWN == InOutStatus(0)
22 | assert InOutStatus.CLOSED == InOutStatus(1)
23 |
--------------------------------------------------------------------------------
/tests/test_controldevice.py:
--------------------------------------------------------------------------------
1 | from c3 import consts, controldevice
2 |
3 |
4 | def test_c3_device_control_message_output_door():
5 | output_operation = controldevice.ControlDeviceOutput(
6 | 1, consts.ControlOutputAddress.DOOR_OUTPUT, 200
7 | )
8 | assert bytes([0x01, 0x01, 0x01, 0xC8, 0x00]) == output_operation.to_bytes()
9 | print(repr(output_operation))
10 |
11 |
12 | def test_c3_device_control_message_output_door_int():
13 | output_operation = controldevice.ControlDeviceOutput(3, 1, 200)
14 | assert bytes([0x01, 0x03, 0x01, 0xC8, 0x00]) == output_operation.to_bytes()
15 | print(repr(output_operation))
16 |
17 |
18 | def test_c3_device_control_message_output_aux():
19 | output_operation = controldevice.ControlDeviceOutput(
20 | 2, consts.ControlOutputAddress.AUX_OUTPUT, 100
21 | )
22 | assert bytes([0x01, 0x02, 0x02, 0x64, 0x00]) == output_operation.to_bytes()
23 | print(repr(output_operation))
24 |
25 |
26 | def test_c3_device_control_message_cancel():
27 | output_operation = controldevice.ControlDeviceCancelAlarms()
28 | assert bytes([0x02, 0x00, 0x00, 0x00, 0x00]) == output_operation.to_bytes()
29 | print(repr(output_operation))
30 |
31 |
32 | def test_c3_device_control_message_restart():
33 | output_operation = controldevice.ControlDeviceRestart()
34 | assert bytes([0x03, 0x00, 0x00, 0x00, 0x00]) == output_operation.to_bytes()
35 | print(repr(output_operation))
36 |
37 |
38 | def test_c3_device_control_message_nostate():
39 | output_operation = controldevice.ControlDeviceNormalOpenStateEnable(2, 1)
40 | assert bytes([0x04, 0x02, 0x01, 0x00, 0x00]) == output_operation.to_bytes()
41 |
--------------------------------------------------------------------------------
/tests/test_core.py:
--------------------------------------------------------------------------------
1 | import time
2 | from datetime import datetime
3 | from unittest import mock
4 |
5 | import pytest
6 |
7 | from c3 import consts, controldevice, rtlog
8 | from c3.core import C3
9 |
10 |
11 | @pytest.fixture
12 | def data_cfg_response_data() -> str:
13 | return (
14 | "4ac70200757365723d312c5549443d69312c436172644e6f3d69322c50696e3d69332c50617373776f72643d73342c47"
15 | "726f75703d69352c537461727454696d653d69362c456e6454696d653d69372c4e616d653d73382c5375706572417574"
16 | "686f72697a653d69390a75736572617574686f72697a653d322c50696e3d69312c417574686f72697a6554696d657a6f"
17 | "6e6549643d69322c417574686f72697a65446f6f7249643d69330a686f6c696461793d332c486f6c696461793d69312c"
18 | "486f6c69646179547970653d69322c4c6f6f703d69330a74696d657a6f6e653d342c54696d657a6f6e6549643d69312c"
19 | "53756e54696d65313d69322c53756e54696d65323d69332c53756e54696d65333d69342c4d6f6e54696d65313d69352c"
20 | "4d6f6e54696d65323d69362c4d6f6e54696d65333d69372c54756554696d65313d69382c54756554696d65323d69392c"
21 | "54756554696d65333d6931302c57656454696d65313d6931312c57656454696d65323d6931322c57656454696d65333d"
22 | "6931332c54687554696d65313d6931342c54687554696d65323d6931352c54687554696d65333d6931362c4672695469"
23 | "6d65313d6931372c46726954696d65323d6931382c46726954696d65333d6931392c53617454696d65313d6932302c53"
24 | "617454696d65323d6932312c53617454696d65333d6932322c486f6c3154696d65313d6932332c486f6c3154696d6532"
25 | "3d6932342c486f6c3154696d65333d6932352c486f6c3254696d65313d6932362c486f6c3254696d65323d6932372c48"
26 | "6f6c3254696d65333d6932382c486f6c3354696d65313d6932392c486f6c3354696d65323d6933302c486f6c3354696d"
27 | "65333d6933310a7472616e73616374696f6e3d352c436172646e6f3d69312c50696e3d69322c56657269666965643d69"
28 | "332c446f6f7249443d69342c4576656e74547970653d69352c496e4f757453746174653d69362c54696d655f7365636f"
29 | "6e643d69370a6669727374636172643d362c50696e3d69312c446f6f7249443d69322c54696d657a6f6e6549443d6933"
30 | "0a6d756c74696d636172643d372c496e6465783d69312c446f6f7249643d69322c47726f7570313d69332c47726f7570"
31 | "323d69342c47726f7570333d69352c47726f7570343d69362c47726f7570353d69370a696e6f757466756e3d382c496e"
32 | "6465783d69312c4576656e74547970653d69322c496e416464723d69332c4f7574547970653d69342c4f757441646472"
33 | "3d69352c4f757454696d653d69362c52657365727665643d69370a74656d706c6174653d392c53697a653d69312c5069"
34 | "6e3d69322c46696e67657249443d69332c56616c69643d69342c54656d706c6174653d73350a74656d706c6174657631"
35 | "303d31302c53697a653d69312c5549443d69322c50696e3d69332c46696e67657249443d69342c56616c69643d69352c"
36 | "54656d706c6174653d42362c526573766572643d69372c456e645461673d69380a6c6f7373636172643d31312c436172"
37 | "644e6f3d69312c52657365727665643d69320a75736572747970653d31322c50696e3d69312c547970653d69320a7769"
38 | "6567616e64666d743d31332c50696e3d69312c4e616d653d73322c5767436f756e743d69332c466f726d61743d73340a70c055"
39 | )
40 |
41 |
42 | def test_core_init():
43 | panel = C3("localhost")
44 | assert panel.nr_of_locks == 0
45 | assert panel.nr_aux_in == 0
46 | assert panel.nr_aux_out == 0
47 | assert panel.lock_status(1) == consts.InOutStatus.UNKNOWN
48 | assert panel.aux_in_status(1) == consts.InOutStatus.UNKNOWN
49 | assert panel.aux_out_status(2) == consts.InOutStatus.UNKNOWN
50 |
51 |
52 | def test_core_set_device_datetime():
53 | with mock.patch("socket.socket") as mock_socket:
54 | panel = C3("localhost")
55 | mock_socket.return_value.send.return_value = 8
56 | mock_socket.return_value.recv.side_effect = [
57 | bytes.fromhex("aa01c80400"),
58 | bytes.fromhex("d18a0000915255"),
59 | bytes.fromhex("aa01c80400"),
60 | bytes.fromhex("d18a000055"),
61 | bytes.fromhex("aa01c80400"),
62 | bytes.fromhex("d18a0003d15355"),
63 | ]
64 |
65 | assert panel.connect() is True
66 | test_time = datetime(2025, 4, 13, hour=15, minute=54, second=12)
67 | panel.set_device_datetime(test_time)
68 |
69 | assert mock_socket.return_value.send.call_count == 3
70 | mock_socket.return_value.send.assert_any_call(
71 | bytearray(b"\xaa\x01\x03\x16\x00\xd1\x8a\x00\xffDateTime=812649252\x05>U")
72 | )
73 |
74 |
75 | def test_core_get_device_param():
76 | with mock.patch("socket.socket") as mock_socket:
77 | panel = C3("localhost")
78 | mock_socket.return_value.send.return_value = 8
79 | mock_socket.return_value.recv.side_effect = [
80 | bytes.fromhex("aa01c80400"),
81 | bytes.fromhex("d18a0000915255"),
82 | bytes.fromhex("aa01c80400"),
83 | bytes.fromhex("d18a000055"),
84 | ]
85 |
86 | assert panel.connect() is True
87 |
88 | mock_socket.return_value.recv.side_effect = [
89 | bytes.fromhex("aa01c84800"),
90 | bytes.fromhex(
91 | "d18a02007e5a4b465056657273696f6e3d31302c4c6f636b436f756e743d322c5265616465"
92 | "72436f756e743d342c417578496e436f756e743d322c4175784f7574436f756e743d32783f55"
93 | ),
94 | ]
95 | params = panel.get_device_param(
96 | ["~ZKFPVersion:", "LockCount", "ReaderCount", "AuxInCount", "AuxOutCount"]
97 | )
98 | assert params["~ZKFPVersion"] == "10"
99 | assert params["LockCount"] == "2"
100 | assert params["ReaderCount"] == "4"
101 | assert params["AuxInCount"] == "2"
102 | assert params["AuxOutCount"] == "2"
103 |
104 |
105 | def test_core_get_device_data_cfg(data_cfg_response_data):
106 | with mock.patch("socket.socket") as mock_socket:
107 | panel = C3("localhost")
108 | mock_socket.return_value.send.return_value = 8
109 | mock_socket.return_value.recv.side_effect = [
110 | bytes.fromhex("aa00c80400"),
111 | bytes.fromhex("4ac70100ee3d55"),
112 | bytes.fromhex("aa01c80200"),
113 | bytes.fromhex("4ac797c355"),
114 | ]
115 |
116 | assert panel.connect() is True
117 | mock_socket.return_value.recv.side_effect = [
118 | bytes.fromhex("aa00c8b004"),
119 | bytes.fromhex(data_cfg_response_data),
120 | ]
121 |
122 | data_cfg = panel._get_device_data_cfg()
123 | assert len(data_cfg) == 13
124 | user_cfg = data_cfg[0]
125 | assert user_cfg.name == "user"
126 | assert user_cfg.index == 1
127 | assert len(user_cfg.fields) == 9
128 | assert user_cfg.fields[5].name == "StartTime"
129 | assert user_cfg.fields[5].type == "i"
130 | assert user_cfg.fields[5].index == 6
131 | assert user_cfg.fields[7].name == "Name"
132 | assert user_cfg.fields[7].type == "s"
133 | assert user_cfg.fields[7].index == 8
134 |
135 |
136 | def test_core_get_device_data_user(data_cfg_response_data):
137 | with mock.patch("socket.socket") as mock_socket:
138 | panel = C3("localhost")
139 | mock_socket.return_value.send.return_value = 8
140 | mock_socket.return_value.recv.side_effect = [
141 | bytes.fromhex("aa00c80400"),
142 | bytes.fromhex("4ac70100ee3d55"),
143 | bytes.fromhex("aa01c80200"),
144 | bytes.fromhex("4ac797c355"),
145 | ]
146 |
147 | assert panel.connect() is True
148 | mock_socket.return_value.recv.side_effect = [
149 | bytes.fromhex("aa00c8b004"),
150 | bytes.fromhex(data_cfg_response_data),
151 | bytes.fromhex("aa00c83d00"),
152 | bytes.fromhex(
153 | "4ac70400"
154 | "0109010203040506070809"
155 | "01010387D6120376543200010001000100000100"
156 | "010203a1a3a303b1b2b3000100042a893401049fb03401000100"
157 | "b44b55"
158 | ),
159 | ]
160 |
161 | user_data = panel.get_device_data(table_name="user")
162 | assert len(user_data) == 2
163 | assert user_data[0]["UID"] == 1
164 | assert user_data[0]["CardNo"] == 1234567
165 | assert user_data[1]["StartTime"] == 20220202
166 | assert user_data[1]["EndTime"] == 20230303
167 |
168 |
169 | def test_core_connect_response_incomplete():
170 | with mock.patch("socket.socket") as mock_socket:
171 | panel = C3("localhost")
172 | mock_socket.return_value.send.return_value = 8
173 | mock_socket.return_value.recv.side_effect = [
174 | bytes.fromhex("aa01c80400"),
175 | bytes.fromhex("d18a0000915255"),
176 | bytes.fromhex("aa01c80400"),
177 | bytes.fromhex("d18a000055"),
178 | ]
179 |
180 | assert panel.connect() is True
181 |
182 | mock_socket.return_value.recv.side_effect = [
183 | bytes.fromhex("aa01c80800"),
184 | bytes.fromhex("d18a020012345678"),
185 | ]
186 | with pytest.raises(ValueError):
187 | panel.get_device_param([])
188 |
189 |
190 | def test_core_connect_response_no_data():
191 | with mock.patch("socket.socket") as mock_socket:
192 | panel = C3("localhost")
193 | panel.receive_retries = 1
194 | mock_socket.return_value.send.return_value = 8
195 | mock_socket.return_value.recv.side_effect = [
196 | bytes.fromhex("aa01c80400"),
197 | bytes.fromhex("d18a0000915255"),
198 | bytes(),
199 | bytes(),
200 | ]
201 |
202 | assert panel.connect() is True
203 |
204 | mock_socket.return_value.recv.side_effect = [
205 | bytes.fromhex("aa01c80800"),
206 | bytes(),
207 | ]
208 | with pytest.raises(ValueError):
209 | panel.get_device_param([])
210 |
211 |
212 | def test_core_connect_session_less():
213 | with mock.patch("socket.socket") as mock_socket:
214 | panel = C3("localhost")
215 | mock_socket.return_value.send.return_value = 8
216 | mock_socket.return_value.recv.side_effect = [
217 | # Reject response to session connect attempt
218 | bytes.fromhex("aa01c90100"),
219 | bytes.fromhex("f313d955"),
220 | # Confirm session-less connection attempt
221 | bytes.fromhex("aa00c80000"),
222 | bytes.fromhex("81fe55"),
223 | # Session-less response to init-getparams
224 | bytes.fromhex("aa00c84800"),
225 | bytes.fromhex(
226 | "7e53657269616c4e756d6265723d4444473831333030313630393232303034"
227 | "30312c4c6f636b436f756e743d342c417578496e436f756e743d342c417578"
228 | "4f7574436f756e743d343b3f55"
229 | ),
230 | ]
231 |
232 | assert panel.connect() is True
233 | assert panel.serial_number == "DDG8130016092200401"
234 | assert panel.nr_of_locks == 4
235 | assert panel.nr_aux_out == 4
236 | assert panel.nr_aux_in == 4
237 |
238 |
239 | def test_core_connect_password():
240 | with mock.patch("socket.socket") as mock_socket:
241 | panel = C3("localhost")
242 | mock_socket.return_value.send.return_value = 12
243 | mock_socket.return_value.recv.side_effect = [
244 | bytes.fromhex("aa01c80400"),
245 | bytes.fromhex("1420fefe4c5e55"),
246 | bytes.fromhex("aa01c80000"),
247 | bytes.fromhex("1420efe955"),
248 | ]
249 |
250 | assert panel.connect("banana123") is True
251 | assert mock_socket.return_value.send.call_count == 2
252 | mock_socket.return_value.send.assert_any_call(
253 | bytes.fromhex("aa01760d00fefefefe62616E616E61313233961955")
254 | )
255 |
256 |
257 | def test_core_lock_status():
258 | with mock.patch("socket.socket") as mock_socket:
259 | panel = C3("localhost")
260 | mock_socket.return_value.send.return_value = 8
261 | mock_socket.return_value.recv.side_effect = [
262 | bytes.fromhex("aa01c80400"),
263 | bytes.fromhex("eb6600005c7f55"),
264 | bytes.fromhex("aa01c84600"),
265 | bytes.fromhex(
266 | "eb6601007e53657269616c4e756d6265723d363430343136323130313638392c4c6f636b"
267 | "436f756e743d322c417578496e436f756e743d322c4175784f7574436f756e743d326a2255"
268 | ),
269 | ]
270 |
271 | assert panel.connect() is True
272 | assert panel.nr_of_locks == 2
273 | assert panel.lock_status(1) == consts.InOutStatus.UNKNOWN
274 | assert panel.lock_status(2) == consts.InOutStatus.UNKNOWN
275 | assert panel.lock_status(3) == consts.InOutStatus.UNKNOWN
276 | assert panel.lock_status(4) == consts.InOutStatus.UNKNOWN
277 |
278 | mock_socket.return_value.recv.side_effect = [
279 | bytes.fromhex("aa01c81400"),
280 | bytes.fromhex("eb66030003000000110000000001ff00f5c1ca2caa1f55"),
281 | ]
282 | logs = panel.get_rt_log()
283 | assert len(logs) == 1
284 | assert isinstance(logs[0], rtlog.DoorAlarmStatusRecord)
285 | assert logs[0].door_sensor_status(1) == consts.InOutStatus.CLOSED
286 | assert logs[0].door_sensor_status(2) == consts.InOutStatus.UNKNOWN
287 | assert panel.lock_status(1) == consts.InOutStatus.CLOSED
288 | assert panel.lock_status(2) == consts.InOutStatus.UNKNOWN
289 | assert panel.lock_status(3) == consts.InOutStatus.UNKNOWN
290 | assert panel.lock_status(4) == consts.InOutStatus.UNKNOWN
291 |
292 |
293 | def test_core_aux_in_status():
294 | with mock.patch("socket.socket") as mock_socket:
295 | panel = C3("localhost")
296 | mock_socket.return_value.send.return_value = 8
297 | mock_socket.return_value.recv.side_effect = [
298 | bytes.fromhex("aa01c80400"),
299 | bytes.fromhex("eb6600005c7f55"),
300 | bytes.fromhex("aa01c84600"),
301 | bytes.fromhex(
302 | "eb6601007e53657269616c4e756d6265723d363430343136323130313638392c4c6f636b"
303 | "436f756e743d322c417578496e436f756e743d322c4175784f7574436f756e743d326a2255"
304 | ),
305 | ]
306 |
307 | assert panel.connect() is True
308 | assert panel.nr_aux_in == 2
309 | assert panel.aux_in_status(1) == consts.InOutStatus.UNKNOWN
310 | assert panel.aux_in_status(2) == consts.InOutStatus.UNKNOWN
311 |
312 | mock_socket.return_value.recv.side_effect = [
313 | bytes.fromhex("aa01c81400"),
314 | bytes.fromhex("eb663c000000000000000000c802dd02f5c3ca2c0abe55"),
315 | ]
316 | logs = panel.get_rt_log()
317 | assert len(logs) == 1
318 | assert isinstance(logs[0], rtlog.EventRecord)
319 | assert logs[0].port_nr == 2
320 | assert logs[0].event_type == consts.EventType.AUX_INPUT_SHORT
321 | assert panel.aux_in_status(1) == consts.InOutStatus.UNKNOWN
322 | assert panel.aux_in_status(2) == consts.InOutStatus.CLOSED
323 |
324 | mock_socket.return_value.recv.side_effect = [
325 | bytes.fromhex("aa01c81400"),
326 | bytes.fromhex("eb663e000000000000000000c802dc02f9c3ca2ca98755"),
327 | ]
328 | logs = panel.get_rt_log()
329 | assert len(logs) == 1
330 | assert isinstance(logs[0], rtlog.EventRecord)
331 | assert logs[0].port_nr == 2
332 | assert logs[0].event_type == consts.EventType.AUX_INPUT_DISCONNECT
333 | assert panel.aux_in_status(1) == consts.InOutStatus.UNKNOWN
334 | assert panel.aux_in_status(2) == consts.InOutStatus.OPEN
335 |
336 |
337 | def test_core_aux_out_status():
338 | with mock.patch("socket.socket") as mock_socket:
339 | panel = C3("localhost")
340 | mock_socket.return_value.send.return_value = 8
341 | mock_socket.return_value.recv.side_effect = [
342 | bytes.fromhex("aa01c80400"),
343 | bytes.fromhex("eb6600005c7f55"),
344 | bytes.fromhex("aa01c84600"),
345 | bytes.fromhex(
346 | "eb6601007e53657269616c4e756d6265723d363430343136323130313638392c4c6f636b"
347 | "436f756e743d322c417578496e436f756e743d322c4175784f7574436f756e743d326a2255"
348 | ),
349 | ]
350 |
351 | assert panel.connect() is True
352 | assert panel.nr_aux_out == 2
353 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
354 | assert panel.aux_out_status(2) == consts.InOutStatus.UNKNOWN
355 |
356 | mock_socket.return_value.recv.side_effect = [
357 | bytes.fromhex("aa01c81400"),
358 | bytes.fromhex("eb6643000000000000000000c8020c0229c4ca2cbb6255"),
359 | ]
360 | logs = panel.get_rt_log()
361 | assert len(logs) == 1
362 | assert isinstance(logs[0], rtlog.EventRecord)
363 | assert logs[0].port_nr == 2
364 | assert logs[0].event_type == consts.EventType.OPEN_AUX_OUTPUT
365 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
366 | assert panel.aux_out_status(2) == consts.InOutStatus.OPEN
367 |
368 | mock_socket.return_value.recv.side_effect = [
369 | bytes.fromhex("aa01c81400"),
370 | bytes.fromhex("eb664c000000000000000000c8020d0271c4ca2c9ac455"),
371 | ]
372 | logs = panel.get_rt_log()
373 | assert len(logs) == 1
374 | assert isinstance(logs[0], rtlog.EventRecord)
375 | assert logs[0].port_nr == 2
376 | assert logs[0].event_type == consts.EventType.CLOSE_AUX_OUTPUT
377 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
378 | assert panel.aux_out_status(2) == consts.InOutStatus.CLOSED
379 |
380 |
381 | def test_core_aux_out_open_close():
382 | with mock.patch("socket.socket") as mock_socket:
383 | panel = C3("localhost")
384 | mock_socket.return_value.send.return_value = 8
385 | mock_socket.return_value.recv.side_effect = [
386 | bytes.fromhex("aa01c80400"),
387 | bytes.fromhex("eb6600005c7f55"),
388 | bytes.fromhex("aa01c84600"),
389 | bytes.fromhex(
390 | "eb6601007e53657269616c4e756d6265723d363430343136323130313638392c4c6f636b"
391 | "436f756e743d322c417578496e436f756e743d322c4175784f7574436f756e743d326a2255"
392 | ),
393 | ]
394 |
395 | assert panel.connect() is True
396 | assert panel.nr_aux_out == 2
397 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
398 | assert panel.aux_out_status(2) == consts.InOutStatus.UNKNOWN
399 |
400 | mock_socket.return_value.recv.side_effect = [
401 | bytes.fromhex("aa01c80400"),
402 | bytes.fromhex("eb6602005d1f55"),
403 | ]
404 |
405 | command = controldevice.ControlDeviceOutput(
406 | 2, consts.ControlOutputAddress.AUX_OUTPUT, 2
407 | )
408 | panel.control_device(command)
409 |
410 | mock_socket.return_value.recv.side_effect = [
411 | bytes.fromhex("aa01c81400"),
412 | bytes.fromhex("eb6643000000000000000000c8020c0229c4ca2cbb6255"),
413 | ]
414 | panel.get_rt_log()
415 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
416 | assert panel.aux_out_status(2) == consts.InOutStatus.OPEN
417 |
418 | time.sleep(2.1)
419 |
420 | assert panel.aux_out_status(1) == consts.InOutStatus.UNKNOWN
421 | assert panel.aux_out_status(2) == consts.InOutStatus.CLOSED
422 |
423 |
424 | def test_core_door_settings():
425 | with mock.patch("socket.socket") as mock_socket:
426 | panel = C3("localhost")
427 | mock_socket.return_value.send.return_value = 8
428 | mock_socket.return_value.recv.side_effect = [
429 | bytes.fromhex("aa01c80400"),
430 | bytes.fromhex("4d9cfefe9f2655"),
431 | bytes.fromhex("aa01c82a00"),
432 | bytes.fromhex(
433 | "4d9cfffe4c6f636b436f756e743d322c417578496e436f75"
434 | "6e743d322c4175784f7574436f756e743d32bb5755"
435 | ),
436 | ]
437 |
438 | assert panel.connect() is True
439 | assert panel.nr_of_locks == 2
440 |
441 | mock_socket.return_value.recv.side_effect = [
442 | bytes.fromhex("aa00c83d00"),
443 | bytes.fromhex(
444 | "4d9c08ff446f6f723153656e736f72547970653d322c446f"
445 | "6f723144726976657274696d653d312c446f6f7231446574"
446 | "6563746f7274696d653d323530b18d55"
447 | ),
448 | bytes.fromhex("aa00c83c00"),
449 | bytes.fromhex(
450 | "4d9c09ff446f6f723253656e736f72547970653d302c446f"
451 | "6f723244726976657274696d653d352c446f6f7232446574"
452 | "6563746f7274696d653d3135158355"
453 | ),
454 | ]
455 |
456 | assert panel.door_settings(1).sensor_type == consts.DoorSensorType.NORMAL_CLOSE
457 | assert panel.door_settings(1).lock_drive_time == 1
458 | assert panel.door_settings(1).door_alarm_timeout == 250
459 | assert panel.door_settings(2).sensor_type == consts.DoorSensorType.NONE
460 | assert panel.door_settings(2).lock_drive_time == 5
461 | assert panel.door_settings(2).door_alarm_timeout == 15
462 |
463 |
464 | def test_core_update_inout_status_exit_button():
465 | with mock.patch("socket.socket") as mock_socket:
466 | panel = C3("localhost")
467 | mock_socket.return_value.send.return_value = 8
468 | mock_socket.return_value.recv.side_effect = [
469 | bytes.fromhex("aa01c80400"),
470 | bytes.fromhex("4d9cfefe9f2655"),
471 | bytes.fromhex("aa01c82a00"),
472 | bytes.fromhex(
473 | "4d9cfffe4c6f636b436f756e743d322c417578496e436f75"
474 | "6e743d322c4175784f7574436f756e743d32bb5755"
475 | ),
476 | ]
477 |
478 | assert panel.connect() is True
479 | assert panel.nr_of_locks == 2
480 | assert panel.lock_status(1) == consts.InOutStatus.UNKNOWN
481 | assert panel.lock_status(2) == consts.InOutStatus.UNKNOWN
482 |
483 | mock_socket.return_value.recv.side_effect = [
484 | bytes.fromhex("aa00c81400"),
485 | bytes.fromhex("4d9c06ff03000000111000000001ff0013ecfd2d4ae555"),
486 | ]
487 |
488 | panel.get_rt_log()
489 | assert panel.lock_status(1) == consts.InOutStatus.CLOSED
490 | assert panel.lock_status(2) == consts.InOutStatus.UNKNOWN
491 |
492 | mock_socket.return_value.recv.side_effect = [
493 | bytes.fromhex("aa00c81400"),
494 | bytes.fromhex("4d9c07ff0000000000000000c802ca0215ecfd2d710f55"),
495 | bytes.fromhex("aa00c83d00"),
496 | bytes.fromhex(
497 | "4d9c08ff446f6f723153656e736f72547970653d322c446f"
498 | "6f723144726976657274696d653d312c446f6f7231446574"
499 | "6563746f7274696d653d323530b18d55"
500 | ),
501 | bytes.fromhex("aa00c83c00"),
502 | bytes.fromhex(
503 | "4d9c09ff446f6f723253656e736f72547970653d302c446f"
504 | "6f723244726976657274696d653d312c446f6f7232446574"
505 | "6563746f7274696d653d3135507055"
506 | ),
507 | ]
508 |
509 | panel.get_rt_log()
510 | assert panel.lock_status(1) == consts.InOutStatus.CLOSED
511 | assert panel.lock_status(2) == consts.InOutStatus.OPEN
512 | assert panel.door_settings(2).sensor_type == consts.DoorSensorType.NONE
513 | assert panel.door_settings(2).lock_drive_time == 1
514 |
515 | time.sleep(panel.door_settings(2).lock_drive_time + 0.1)
516 |
517 | assert panel.lock_status(2) == consts.InOutStatus.CLOSED
518 |
519 | mock_socket.return_value.recv.side_effect = [
520 | bytes.fromhex("aa00c81400"),
521 | bytes.fromhex("4d9c06ff03000000111000000001ff0013ecfd2d4ae555"),
522 | ]
523 |
524 | # Subsequent DoorAlarmStatus logs with door 2 status 'unknown' are ignored,
525 | # last-known status better than unknown is used
526 | panel.get_rt_log()
527 | assert panel.lock_status(1) == consts.InOutStatus.CLOSED
528 | assert panel.lock_status(2) == consts.InOutStatus.CLOSED
529 |
--------------------------------------------------------------------------------
/tests/test_crc16.py:
--------------------------------------------------------------------------------
1 | from c3 import crc
2 |
3 |
4 | def test_crc_basic():
5 | # Test data generated from https, http://www.lammertbies.nl/comm/info/crc-calculation.html
6 | assert 0xBB3D == crc.crc16(b"123456789")
7 | assert 0xBB3D == crc.crc16(["1", "2", "3", "4", "5", "6", "7", "8", "9"])
8 | assert 0xBB3D == crc.crc16({49, 50, 51, 52, 53, 54, 55, 56, 57})
9 | assert 0xE9D9 == crc.crc16(b"abcdefg")
10 | assert 0x0F65 == crc.crc16(b"0123456789ABCDEF")
11 | assert 0x0F65 == crc.crc16((["0123456789", "ABCDEF"]))
12 |
13 |
14 | def test_crc_connect():
15 | # Request
16 | assert 0x8FD7 == crc.crc16([0x01, 0x76, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00])
17 | # Response
18 | assert 0x3320 == crc.crc16((0x01, 0xC8, 0x04, 0x00, 0xD6, 0xCD, 0x00, 0x00))
19 | # Response
20 | assert 0x47C8 == crc.crc16([0x01, 0xC8, 0x04, 0x00, 0x54, 0xF1, 0x00, 0x00])
21 |
22 |
23 | def test_crc_real_log():
24 | # Request
25 | assert 0xF687 == crc.crc16([0x01, 0x0B, 0x04, 0x00, 0x3E, 0xE3, 0x02, 0x00])
26 | # Response
27 | assert 0xBF72 == crc.crc16(bytes.fromhex("01 0b 04 00 78 e5 02 00"))
28 |
29 | # Request
30 | assert 0xCD2C == crc.crc16(
31 | [
32 | 0x01,
33 | 0xC8,
34 | 0x14,
35 | 0x00,
36 | 0x78,
37 | 0xE5,
38 | 0x02,
39 | 0x00,
40 | 0x03,
41 | 0x00,
42 | 0x00,
43 | 0x00,
44 | 0x11,
45 | 0x00,
46 | 0x00,
47 | 0x00,
48 | 0x00,
49 | 0x01,
50 | 0xFF,
51 | 0x00,
52 | 0x00,
53 | 0x33,
54 | 0x75,
55 | 0x21,
56 | ]
57 | )
58 | # Response
59 | assert 0x4F24 == crc.crc16(
60 | b"\x01\xc8\x14\x00\x54\xf1\x02\x00\x03\x00\x00\x00\x11\x00\x00\x00\x00\x01\xff\x00\xda"
61 | b"\x3e\x75\x21"
62 | )
63 |
64 |
65 | def test_crc_disconnect():
66 | # Request
67 | assert 0x0FDE == crc.crc16([0x01, 0x02, 0x04, 0x00, 0x3A, 0xCF, 0x02, 0x00])
68 | # Request
69 | assert 0x6A75 == crc.crc16([0x01, 0xC8, 0x04, 0x00, 0x3E, 0xE3, 0x03, 0x00])
70 |
--------------------------------------------------------------------------------
/tests/test_rtlog.py:
--------------------------------------------------------------------------------
1 | from unittest import mock
2 |
3 | from c3.consts import EventType, InOutStatus, VerificationMode
4 | from c3.core import C3
5 | from c3.rtlog import DoorAlarmStatusRecord, EventRecord
6 | from c3.utils import C3DateTime
7 |
8 |
9 | def test_c3_rtlog_event_decode1():
10 | raw_data = bytes(
11 | [
12 | 0x00,
13 | 0x00,
14 | 0x00,
15 | 0x00,
16 | 0x00,
17 | 0x00,
18 | 0x00,
19 | 0x00,
20 | 0xC8,
21 | 0x01,
22 | 0x66,
23 | 0x02,
24 | 0x32,
25 | 0x8F,
26 | 0xAE,
27 | 0x21,
28 | ]
29 | )
30 | # assert 1501491250 == int.from_bytes(raw_data[12:16], byteorder="little") #11439922
31 | # assert 1501491250 == int.from_bytes(raw_data[12:16], byteorder="big") #3313582
32 | # assert 1501491250 == int.from_bytes(reversed(raw_data[12:16]), byteorder="little") # 3313582
33 | # assert 1501491250 == int.from_bytes(reversed(raw_data[12:16]), byteorder="big") #11439922
34 | record = EventRecord.from_bytes(raw_data)
35 | # assert C3DateTime.from_value(1501491250) == record.time_second
36 | assert (
37 | C3DateTime(year=2017, month=7, day=31, hour=8, minute=54, second=10)
38 | == record.time_second
39 | )
40 | assert not record.is_door_alarm()
41 | assert record.is_event()
42 | print(repr(record))
43 |
44 |
45 | def test_c3_rtlog_event_decode2():
46 | raw_data = bytes(
47 | [
48 | 0x17,
49 | 0x30,
50 | 0x64,
51 | 0x12,
52 | 0xE2,
53 | 0xB1,
54 | 0x04,
55 | 0x00,
56 | 0x04,
57 | 0x01,
58 | 0x00,
59 | 0x00,
60 | 0x74,
61 | 0x2C,
62 | 0xAF,
63 | 0x21,
64 | ]
65 | )
66 | record = EventRecord.from_bytes(raw_data)
67 | # assert C3DateTime.from_value(1501531508) == record.time_second
68 | assert not record.is_door_alarm()
69 | assert record.is_event()
70 | print(repr(record))
71 |
72 |
73 | def test_c3_rtlog_decode_status1():
74 | raw_data = bytes(
75 | [
76 | 0x03,
77 | 0x00,
78 | 0x00,
79 | 0x00,
80 | 0x11,
81 | 0x00,
82 | 0x00,
83 | 0x00,
84 | 0x00,
85 | 0x01,
86 | 0xFF,
87 | 0x00,
88 | 0xF2,
89 | 0x31,
90 | 0xB3,
91 | 0x21,
92 | ]
93 | )
94 | record = DoorAlarmStatusRecord.from_bytes(raw_data)
95 | assert 0 < len(record.get_alarms(door_nr=None))
96 | assert record.has_alarm(1)
97 | assert not record.has_alarm(2)
98 | assert record.has_alarm(1, 1)
99 | assert record.has_alarm(1, 2)
100 | # assert not record.has_alarm(1, 3)
101 | assert False is record.door_is_open(1)
102 | assert None is record.door_is_open(3)
103 | assert record.is_door_alarm()
104 | assert not record.is_event()
105 | print(repr(record))
106 |
107 |
108 | def test_c3_rtlog_decode_status2():
109 | raw_data = bytes(
110 | [
111 | 0x03,
112 | 0x00,
113 | 0x00,
114 | 0x00,
115 | 0x02,
116 | 0x00,
117 | 0x00,
118 | 0x00,
119 | 0x01,
120 | 0x01,
121 | 0xFF,
122 | 0x00,
123 | 0xFC,
124 | 0x31,
125 | 0xB3,
126 | 0x21,
127 | ]
128 | )
129 | record = DoorAlarmStatusRecord.from_bytes(raw_data)
130 | assert record.has_alarm(1)
131 | assert record.door_is_open(1)
132 | assert None is record.door_is_open(2)
133 | assert record.is_door_alarm()
134 | assert not record.is_event()
135 | print(repr(record))
136 |
137 |
138 | @mock.patch.object(C3, "_update_inout_status", new_callable=mock.MagicMock)
139 | def test_rtlog_unknown_verification_mode(_unused_update_inout_status_mock):
140 | with mock.patch("socket.socket") as mock_socket:
141 | panel = C3("localhost")
142 | mock_socket.return_value.send.return_value = 8
143 | mock_socket.return_value.recv.side_effect = [
144 | bytes.fromhex("aa00c80400"),
145 | bytes.fromhex("d805fefea30955"),
146 | bytes.fromhex("aa00c80400"),
147 | bytes.fromhex("d805000062e955"),
148 | ]
149 |
150 | assert panel.connect() is True
151 |
152 | mock_socket.return_value.recv.side_effect = [
153 | bytes.fromhex("aa01c81400"),
154 | bytes.fromhex("d805e8ff0200000011000000000bff00fa61fb2c38b255"),
155 | ]
156 | logs = panel.get_rt_log()
157 | assert len(logs) == 1
158 | assert isinstance(logs[0], DoorAlarmStatusRecord)
159 | assert logs[0].verified == VerificationMode.CARD_WITH_PASSWORD
160 |
161 | mock_socket.return_value.recv.side_effect = [
162 | bytes.fromhex("aa01c81400"),
163 | bytes.fromhex("d805e8ff02000000110007000007ff00fa61fb2c456855"),
164 | ]
165 | logs = panel.get_rt_log()
166 | assert len(logs) == 1
167 | assert logs[0].verified == VerificationMode.OTHER
168 |
169 |
170 | @mock.patch.object(C3, "_update_inout_status", new_callable=mock.MagicMock)
171 | def test_rtlog_keyvalue_response(_unused_update_inout_status_mock):
172 | with mock.patch("socket.socket") as mock_socket:
173 | panel = C3("localhost")
174 | mock_socket.return_value.send.return_value = 8
175 | mock_socket.return_value.recv.side_effect = [
176 | bytes.fromhex("aa02c90100"),
177 | bytes.fromhex("f357d955"),
178 | bytes.fromhex("aa02c80000"),
179 | bytes.fromhex("81fe55"),
180 | bytes.fromhex("aa02c84200"),
181 | bytes.fromhex(
182 | "7e53657269616c4e756d6265723d4143"
183 | "59543033323335333632372c4c6f636b"
184 | "436f756e743d342c417578496e436f756"
185 | "e743d342c4175784f7574436f756e743d"
186 | "34599355"
187 | ),
188 | # Not sure what the message structure of the response use protocol version (?) 02 is
189 | bytes.fromhex("aa01c86801"),
190 | bytes.fromhex(
191 | "000000000000000000000000000000000000000000000000000000"
192 | "0000000000000000000000000000000000000000000000000000000000000000"
193 | "0000000000000000000000000000000000000000000000000000000000000000"
194 | "0000000000000000000000000000000000000000000000000000000000000000"
195 | "0000000000000000000000000000000000000000000000000000000000000000"
196 | "0000000000000000000000000000000000000000000000000000000000000000"
197 | "0000000000000000000000000000000000000000000000000000000000000000"
198 | "0000000000000000000000000000000000000000000000000000000000000000"
199 | "0000000000000000000000000000000000000000000000000000000000000000"
200 | "0000000000000000000000000000000000000000000000000000000000000000"
201 | "0000000000000000000000000000000000000000000000000000000000000000"
202 | "00000000000000000000000000fabb55"
203 | ),
204 | bytes.fromhex("aa01c8c400"),
205 | bytes.fromhex(
206 | "74696d653d323032332d31322d30362032323a33333a3135097069"
207 | "6e3d3009636172646e6f3d30096576656e74616464723d30096576656e743d32"
208 | "303609696e6f75747374617475733d3209766572696679747970653d32303009"
209 | "696e6465783d380d0a74696d653d323032332d31322d30362032323a35373a35"
210 | "340970696e3d3009636172646e6f3d30096576656e74616464723d3109657665"
211 | "6e743d3809696e6f75747374617475733d3209766572696679747970653d3230"
212 | "3009696e6465783d39621455"
213 | ),
214 | bytes.fromhex("aa01c83a00"),
215 | bytes.fromhex(
216 | "74696d653d323032332d31322d30392031353a30393a33330973656e736f72"
217 | "3d32340972656c61793d303409616c61726d3d3030303030303030c2b655"
218 | ),
219 | ]
220 |
221 | assert panel.connect() is True
222 |
223 | logs = panel.get_rt_log()
224 | assert len(logs) == 0
225 |
226 | logs = panel.get_rt_log()
227 | assert len(logs) == 1
228 | assert isinstance(logs[0], EventRecord)
229 | assert logs[0].port_nr == 1
230 | assert logs[0].event_type == EventType.REMOTE_OPENING
231 | assert logs[0].verified == VerificationMode.OTHER
232 |
233 | logs = panel.get_rt_log()
234 | assert len(logs) == 1
235 | assert isinstance(logs[0], DoorAlarmStatusRecord)
236 | assert not logs[0].door_is_open(1)
237 | assert not logs[0].door_is_open(2)
238 | assert logs[0].door_is_open(3)
239 | assert not logs[0].door_is_open(4)
240 | assert logs[0].door_sensor_status(1) == InOutStatus.UNKNOWN
241 | assert logs[0].door_sensor_status(2) == InOutStatus.CLOSED
242 | assert logs[0].door_sensor_status(3) == InOutStatus.OPEN
243 | assert logs[0].door_sensor_status(4) == InOutStatus.UNKNOWN
244 | assert not logs[0].get_alarms(1)
245 | assert not logs[0].get_alarms(2)
246 | assert not logs[0].get_alarms(3)
247 | assert not logs[0].get_alarms(4)
248 |
--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | from c3.utils import *
2 |
3 |
4 | def test_lsb():
5 | assert lsb(0x123AA) == 0xAA
6 | assert lsb(0xAB00) == 0
7 |
8 |
9 | def test_msb():
10 | assert msb(0xEF) == 0
11 | assert msb(0x12CD34) == 0xCD
12 |
13 |
14 | def test_c3_datetime_from_value():
15 | c3_dt = C3DateTime.from_value(347748895)
16 | assert c3_dt.year == 2010
17 | assert c3_dt.month == 10
18 | assert c3_dt.minute == 54
19 |
20 | assert C3DateTime(
21 | year=2017, month=7, day=30, hour=15, minute=24, second=32
22 | ) == C3DateTime.from_value(
23 | int.from_bytes([0x21, 0xAD, 0x99, 0x30], byteorder="big")
24 | )
25 | assert C3DateTime(
26 | year=2013, month=10, day=8, hour=14, minute=38, second=32
27 | ) == C3DateTime.from_value(
28 | int.from_bytes(reversed([0x1A, 0x61, 0x70, 0xE8]), byteorder="little")
29 | )
30 |
31 |
32 | def test_c3_datetime_to_value():
33 | c3_dt = C3DateTime(2010, 10, 26, 20, 54, 55)
34 | assert c3_dt.to_value() == 347748895
35 |
--------------------------------------------------------------------------------