Metadata-Version: 2.5
Name: pyzkaccess-native
Version: 0.6.6
Summary: Pure-Python, cross-platform client for ZKTeco PullSDK / ZKAccess access-control devices (C3, inBio, MA500...) - no DLL required
Project-URL: Homepage, https://github.com/Avataar120/pyzkaccess
Project-URL: Documentation, https://github.com/Avataar120/pyzkaccess#readme
Project-URL: Issues, https://github.com/Avataar120/pyzkaccess/issues
Project-URL: Changelog, https://github.com/Avataar120/pyzkaccess/blob/main/CHANGELOG.md
Author: Avataar120
License-Expression: MIT
License-File: LICENSE
Keywords: access-control,c3,fingerprint,home-assistant,inbio,ma500,pullsdk,zkaccess,zkteco
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Home Automation
Classifier: Topic :: Security
Classifier: Topic :: System :: Hardware
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/Avataar120/pyzkaccess/main/custom_components/zkaccess_native/brand/icon.png" alt="pyzkaccess-native logo" width="128">
</p>

# pyzkaccess-native

**Talk to ZKTeco access-control devices from any OS, in pure Python. No DLL, no Windows,
no ZKAccess.**

[![PyPI](https://img.shields.io/pypi/v/pyzkaccess-native)](https://pypi.org/project/pyzkaccess-native/)
[![Python](https://img.shields.io/pypi/pyversions/pyzkaccess-native)](https://pypi.org/project/pyzkaccess-native/)
[![Tests](https://github.com/Avataar120/pyzkaccess/actions/workflows/ci.yml/badge.svg)](https://github.com/Avataar120/pyzkaccess/actions/workflows/ci.yml)
[![Marketplace](https://img.shields.io/badge/Marketplace-default-41BDF5)](#install)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)

ZKTeco panels and readers that are managed by **ZKAccess** (C3-100/200/400, inBio,
MA500...) speak a binary TCP protocol. The only official way to use it is the PullSDK
(`plcommpro.dll`), a 32-bit Windows DLL. This project reimplements that protocol from
scratch, from captures of the DLL's own traffic, so you can:

- read and manage **users, RFID cards, keypad codes and fingerprint templates**;
- grant and revoke **door access**;
- receive **access events in real time** (who opened which door, refused attempts...);
- **open doors**, drive auxiliary outputs, set the clock, read and write parameters;
- **back up and restore** a whole device, fingerprint templates included, byte for byte;

from Linux, macOS, Windows, a Raspberry Pi or a container, with no dependency at all.

It comes with:

| | |
|---|---|
| 🐍 **Python library** | `pip install pyzkaccess-native` |
| 💻 **Command line tool** | `zkaccess --host 192.168.1.201 users` |
| 🏠 **Home Assistant integration** | installable from the Home Assistant Marketplace, with a management page in the sidebar, see [below](#home-assistant-integration) |
| 🧪 **Device emulator** | test your code without hardware |
| 📖 **Protocol documentation** | [docs/PROTOCOL.md](docs/PROTOCOL.md) |

> [!NOTE]
> Not to be confused with [`pyzkaccess`](https://github.com/bdragon300/pyzkaccess), a
> different project that wraps the official Windows DLL. This one does not need the DLL.

---

## Contents

- [Supported devices](#supported-devices)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Library guide](#library-guide)
- [Command line tool](#command-line-tool)
- [Home Assistant integration](#home-assistant-integration)
- [Safety notes (read this)](#safety-notes-read-this)
- [Testing without hardware](#testing-without-hardware)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)

## Supported devices

This library and integration speak the **PullSDK / ZKAccess protocol** of ZKTeco
*access control* devices: the one the ZKAccess 3.5 software uses (TCP port 4370, tables
`user`, `templatev10`, `userauthorize`, real-time log). Any device that ZKAccess 3.5 can
manage *should* work.

| Device | Status |
|---|---|
| **MA500** (fingerprint + RFID reader), firmware 6.64 | ✅ tested, used daily (fingerprints, cards, codes, phones, reboot) |
| C3-100 / C3-200 / C3-400 (access control panels) | 🧪 being tested with a user on a C3-400 ([#1](https://github.com/Avataar120/pyzkaccess/issues/1)): connection, device info and the 36-byte real-time log work (0.6.4); its text UserIDs are supported since 0.6.5. Card / code events and user management still to be confirmed (C3 panels have no fingerprint) |
| inBio 160 / 260 / 460 (access control panels with fingerprint readers) | 🟡 expected to work; please report |
| **Time attendance terminals and standalone units** using the "attendance" protocol (`pyzk`): MA300, SCR100, F18, F22, K40, iClock, uFace, SpeedFace... | ❌ not supported: different protocol |
| Devices that only push their events to a server (ADMS / "push" protocol) | ❌ not supported |

**How to tell?** If the device is managed by **ZKAccess 3.5** (access control software), it
uses this protocol. If it is managed by **ZKTime / ZKBio Time / Attendance Management**
(time attendance software), it uses the other one. A quick check from any computer:
`pip install pyzkaccess-native` then `zkaccess --host <device IP> info`. An answer with a
serial number means it speaks this protocol.

If you try another model, please open an issue with the output of `zkaccess info` and
`zkaccess tables`: it helps a lot.

## Installation

```bash
pip install pyzkaccess-native
```

Python 3.10 or newer, no other dependency.

## Quick start

```python
from pyzkaccess_native import ZKAccess

with ZKAccess("192.168.1.201") as dev:          # password="..." if one is set
    info = dev.info()
    print(info.serial_number, info.firmware)

    for user in dev.get_users():
        print(user.user_id, user.name, user.card_no)

    for event in dev.events():                  # Ctrl+C to stop
        print(event.time, event.user_id, event.label, "granted" if event.granted else "")
```

From a shell:

```bash
zkaccess --host 192.168.1.201 info
zkaccess --host 192.168.1.201 events
```

## Library guide

### Connecting

```python
from pyzkaccess_native import ZKAccess

dev = ZKAccess("192.168.1.201", port=4370, password="", timeout=5.0)
dev.connect()
...
dev.disconnect()
```

Or, better, `with ZKAccess(...) as dev:`. The client is thread-safe: requests from
several threads are serialized on its session.

> [!IMPORTANT]
> Share one `ZKAccess` instance inside your program. A device may accept a second
> session (the MA500 does), but **real-time events are delivered to every session**, and
> writes from two programs are not coordinated. Do not manage the same device from
> ZKAccess and from this library at the same time.

### Device information, parameters and clock

```python
info = dev.info()            # DeviceInfo(serial_number, firmware, lock_count, ...)
dev.get_params(["~SerialNumber", "Door1Drivertime", "MThreshold"])
dev.set_params({"Door1Drivertime": 5})

dev.get_time()               # naive datetime, device local time
dev.set_time()               # sync with this computer (or pass a datetime)
```

### Users

> **Vocabulary.** A user is identified by its **UserID**, the number typed on the keypad
> (stored by the device in a field called `Pin`). The device also gives each user an internal
> **slot** (field `UID`) that binds fingerprint templates to their owner; it cannot be chosen.

```python
from pyzkaccess_native import User

dev.get_users()                                  # list[User]
dev.get_user(105)                                # User | None

# Create, or update only the given fields (the others are kept):
dev.save_user(User(user_id=105, name="Alice", card_no=12345678, password="1234"))
dev.save_user(User(user_id=105, name="Alice Smith"))  # rename, card and password kept

dev.delete_user(105)       # also deletes its fingerprint templates and authorizations
```

`User` fields: `user_id`, `name`, `card_no`, `password` (keypad code), `group`, `start_time`,
`end_time`, `privilege`, `super_authorize`, and `slot` (read-only, see below).

### Door access

```python
dev.grant(105)                               # time zone 1 ("always"), door 1
dev.grant(105, timezone_id=2, door_mask=0b0101)   # doors 1 and 3 during time zone 2
dev.get_authorizations(105)                  # list[Authorization]
dev.revoke(105)                              # remove all of them
```

A user can open a door only if they have an authorization for it **and** a credential
(fingerprint, card or password).

### Fingerprint templates

Fingerprints are enrolled **on the device** (keypad menu or ZKAccess with a USB reader).
The library can copy, back up and restore the resulting templates:

```python
from pyzkaccess_native import Template

templates = dev.get_templates()          # all of them (large transfer handled for you)
mine = dev.get_templates(user_id=105)

# Copy a template to another device (the user must exist there):
other.save_user(User(user_id=105, name="Alice"))
other.save_template(Template(user_id=105, finger_id=0, template=mine[0].template))

dev.delete_templates(105)                # or delete_templates(105, finger_id=3)
dev.move_template(105, 3, 100)           # one finger to another user (first free slot)
dev.move_templates(105, 100)             # all fingers of 105 to 100, in one go
```

`save_template()` refuses to write when another user has the same internal slot (see
[safety notes](#safety-notes-read-this)).

### Real-time events

```python
from pyzkaccess_native import AccessEvent, EventType

for ev in dev.events(interval=0.5):      # reconnects automatically
    if ev.granted:
        print(f"{ev.user_id} opened door {ev.door} ({ev.label})")
    elif ev.event == EventType.UNREGISTERED_FINGERPRINT:
        print("unknown finger")
```

Or poll yourself: `dev.poll()` returns the records received since the previous call:
`AccessEvent` objects, plus a `DoorStatus` (door sensors, alarms) on every call.

`AccessEvent` has `event` (an `EventType`, or a plain `int` for unlisted codes), `user_id`,
`card`, `door`, `verify_mode`, `in_out`, `time`, plus the helpers `granted`, `denied` and
`label`.

Two record formats exist: 16 bytes (MA500 and most readers) and 36 bytes (C3 panels with a
recent firmware, where the UserID is sent as text). `poll()` detects the format on the first
answers and keeps it in `dev.detected_rtlog_format`; pass `ZKAccess(..., rtlog_format=36)` to
force it. `parse_rtlog(data)` decodes a captured answer.

### Doors and outputs

```python
dev.open_door(1, seconds=5)    # pulse the lock relay of door 1
dev.hold_door_open(1)          # until close_door()
dev.close_door(1)
dev.set_aux_output(1, 3)       # aux output 1 for 3 s (0 = off, 255 = on)
dev.cancel_alarm()
dev.restart()
```

### Generic table access

Everything above is built on four generic calls. They work on any table the device
reports (`dev.tables()`), with the device's own field names:

```python
dev.read_table("transaction", where={"Pin": 105})          # list[dict]
dev.read_table("user", fields=["Pin", "Name"])
dev.write_records("timezone", [{"TimezoneId": 2, "MonTime1": ...}])
dev.delete_records("holiday", where={"Holiday": 20261225})
dev.count("user")
```

### Backup and restore

```python
from pyzkaccess_native import backup

snap = backup.backup(dev)             # users, templates, authorizations, time zones...
backup.save(snap, "device.json")

backup.restore(dev, backup.load("device.json"))             # merge
backup.restore(dev, backup.load("device.json"), wipe=True)  # exact copy
```

> [!WARNING]
> Backups contain **biometric data** (fingerprint templates) and user passwords.
> Store them like any other secret.

### Discovery

```python
from pyzkaccess_native import discover, scan
discover()                    # UDP broadcast: devices on the same subnet only
scan(["192.168.5.0/24"])      # TCP port 4370 on each address: works across routers / VLANs
```

`scan()` tries the device port on every address of the ranges (at most a /22 each, in
parallel: a /24 takes a few seconds), then opens a session to read the serial number and
firmware. A device that needs a communication password is listed with
`raw["auth"] == "required"`.

### Errors

All exceptions derive from `ZKError`: `ZKConnectionError` (network),
`DeviceError` (the device refused, `.code` = -14 for a wrong password...),
`ProtocolError` (unexpected answer), `SafetyError` (refused by a safety check).

## Command line tool

```text
zkaccess [--host HOST] [--port 4370] [--password PWD] [-v|-vv] <command>
```

`--host` and `--password` can also come from `ZKACCESS_HOST` / `ZKACCESS_PASSWORD`.

| Command | Description |
|---|---|
| `discover` | find devices on the local network (UDP broadcast) |
| `scan 192.168.5.0/24` | find devices on any subnet (TCP port 4370) |
| `info` | serial number, firmware, doors, readers... |
| `tables` | tables and fields supported by the device |
| `params NAME... / NAME=VALUE...` | read / write parameters |
| `time [--set [ISO date]]` | read, or set the clock (default: now) |
| `users [--json]` | list users |
| `user-set USERID [--name] [--card] [--user-password]` | create or update a user (`--user-password` = keypad code) |
| `user-delete USERID [--yes]` | delete a user, its templates and authorizations |
| `grant USERID [--timezone 1] [--doors 1]` / `revoke USERID` | door access |
| `read TABLE [--where F=V] [--fields a,b] [--json]` | dump any table |
| `count TABLE` | number of records |
| `events [--status] [--json]` | live events, Ctrl+C to stop |
| `door open\|close\|hold [--door 1] [--seconds 5]` | drive a lock relay |
| `aux OUTPUT SECONDS` | drive an auxiliary output |
| `backup FILE [--logs]` / `restore FILE [--wipe] [--yes]` | full backup / restore |
| `cancel-alarm`, `restart` | |

`-vv` prints every frame in hex, handy for protocol work. `python -m pyzkaccess_native`
works too.

Example:

```console
$ export ZKACCESS_HOST=192.168.1.201
$ zkaccess users
UserID  Name   Card      Code  Slot
101     Alice  12345678  yes   1
$ zkaccess events
2026-11-21 08:02:11  door 1  user 101   card 0          14 Fingerprint open
2026-11-21 08:05:40  door 1  user 0     card 0          34 Unregistered fingerprint
```

## Home Assistant integration

The repository is also a custom integration built on the library, listed in the Home Assistant
**Marketplace**. It adds an **Access control** page to the sidebar (administrators only) to
manage people, fingerprints, cards and codes without any YAML.

### Install

**From the Marketplace** (recommended):

1. In Home Assistant, go to **Settings** → **Marketplace**, search for **ZKAccess Native**,
   open it and click **Download**.
2. Restart Home Assistant.

On older Home Assistant versions with HACS installed separately, search for it in HACS the
same way.

**By hand** (without the Marketplace):

1. Download the latest release from
   [Releases](https://github.com/Avataar120/pyzkaccess/releases/latest)
   (*Source code (zip)*) and unzip it.
2. Copy its folder `custom_components/zkaccess_native` into the `custom_components` folder of
   your Home Assistant configuration (create it if needed), so that you get
   `config/custom_components/zkaccess_native/manifest.json`. With the *Samba share*, *File
   editor* or *Studio Code Server* add-on, or over SSH:

   ```sh
   cd /config
   wget -O zkaccess.zip https://github.com/Avataar120/pyzkaccess/archive/refs/tags/vX.Y.Z.zip
   unzip zkaccess.zip
   mkdir -p custom_components
   cp -r pyzkaccess-X.Y.Z/custom_components/zkaccess_native custom_components/
   rm -rf zkaccess.zip pyzkaccess-X.Y.Z
   ```

   (replace `X.Y.Z` with the release number, e.g. `0.4.2`).
3. Restart Home Assistant. It installs the `pyzkaccess-native` library from PyPI by itself
   (internet access needed at that first start).

To update by hand, replace the `zkaccess_native` folder the same way and restart: your
people, categories, phones and backups are kept (they live in Home Assistant's storage, not
in that folder).

**Then:**

1. **Settings → Devices & services → Add integration → ZKAccess Native**. The integration
   searches for devices: UDP broadcast on Home Assistant's network, and TCP port 4370 on
   its subnet plus any range you add (e.g. `192.168.5.0/24` for a device on another subnet
   or VLAN). Pick the device (or enter its address), then the communication password if any.
   A ZKTeco device that gets its address by DHCP on Home Assistant's network is also offered
   by itself (*Discovered*), and its new address is picked up when it changes.
2. Open **Access control** in the sidebar.

The device's address, port or password changed? **Settings → Devices & services → ZKAccess
Native → ⋮ → Reconfigure**: everything else (people, phones, history) is kept. When the
device refuses the communication password, Home Assistant asks for the new one.

### People and action categories

Access events only tell *which UserID* was recognized, never which finger or card. To let one
person trigger different actions (open the door, arm the alarm, open the garage...), each
person gets one UserID per **action category**:

```
UserID = person number (2 digits) followed by the category digit
person 12 + category 0 (Open)  -> UserID 120
person 12 + category 3 (Arm)   -> UserID 123
```

- Category **0 is always "Open"**. Digits 1-9 are free: standard types (Close, Lock,
  Unlock, Arm, Disarm) or custom names (Garage...), set in **Settings**.
- Each UserID holds **several fingerprints, one card and one keypad code**. A person can have
  two fingers that open and a third one that arms the alarm, or one card to open and
  another one to close.
- On the keypad, the code is typed after the UserID, so a person can reuse the same code in
  every category.
- A category can hold **two cards** (two badges for the same person and action, e.g. a key fob
  and a card in the wallet). The device keeps one card number per UserID, so the second card
  is stored on an extra UserID: **9000 + the category's UserID** (9120 for 120). It gets the
  same name and access rights, follows the person and category switches, and its events
  carry the same person and category. It is shown under the category in the panel, not as a
  UserID of its own. Person 99 has no second card (9990-9999 are reserved for finger
  identification).
- Each category says whether **the reader opens its lock** (its own relay). An "Arm" finger
  usually should not open the door: the device then refuses it (event 23 with the UserID,
  verified on the MA500; red LED as for a refusal), and the integration turns that refusal
  into an `action` event for Home Assistant. Automations react to both `granted` and
  `action`, so the door can be opened by Home Assistant either way.

> **Security advice: do not wire the door lock to the reader's own relay when the reader is
> outside.** A standalone reader such as the MA500 is mounted on the outer wall. If the lock
> is wired to its relay, someone who tears the reader off reaches those wires and opens the
> door just by touching them together. Keep the lock relay inside (a relay module driven by
> Home Assistant, or a ZKTeco controller such as a C3 / inBio mounted indoors, with only the
> reader outside), let Home Assistant open the door from the access event (see the
> *Open the door and disarm* blueprint), and use the reader's relay for nothing critical.
> Trade-off: with the relay unused, the reader shows a red LED for accepted credentials of
> categories without its lock; enable the reader's lock on a category only if its relay is
> not wired to anything critical.
- **Second presentation** (per category): presenting the same card or finger again within a
  few seconds (5 s by default, measured with the device's own event time) runs a second
  category *in addition*. Example: badge once to open the gate,
  twice to open the gate and then lock and arm the house.

- **Toggle** categories: one presentation, and Home Assistant picks the category from the state
  of an entity (e.g. alarm armed → *Disarm*, otherwise → *Arm*). Active means anything but
  `off`, `unlocked`, `disarmed`, `closed`, `not_home`, `idle`, `unavailable`, `unknown`.

Prefer one UserID per person, without categories? Choose **One UserID per person** in
**Settings → Numbering**.

### Phones (NFC tags)

A phone running the Home Assistant app can act as a badge:

1. Create a tag in Home Assistant (**Settings → Tags**), stick it next to the door, and declare
   it in **Access control → Settings → NFC tags** with the door it stands for.
2. On a person's page, **Pair a phone**: the next phone that scans a declared tag within two
   minutes is paired with that person, in the chosen category.
3. A scan then produces the same `zkaccess_native_access` event as a fingerprint or a card
   (`method: phone`, `phone: <device name>`), with second presentation (scan twice) and toggle
   categories. If the category drives the relay, the integration releases the door itself.

Disabling a person also disables their phones; each phone can also be disabled on its own.

### The Access control page

| Tab | What you can do |
|---|---|
| **People** | list, search, create; per person: a two-hand view of enrolled fingers with their category, move a finger to another category, delete it; cards and codes per category; paired phones; enable / disable all access (rights are remembered and restored); switch each category on or off for that person (*Active* column: the device refuses its credentials and Home Assistant sees them as denied); link to a Home Assistant person; delete. UserIDs that do not follow the numbering (e.g. enrolled on the keypad) are listed as **Unassigned** and can be attached to a person. |
| **Activity** | live log with names, category, method (fingerprint, card, code, remote) and second presentations; filters; unknown cards can be assigned in one click |
| **Door** | open / hold open / close the lock relay; door settings written to the device (relay time, door sensor, open-door alarm delay, verification mode, free-passage time zone, relock on close); device clock; cancel alarm |
| **Settings** | numbering, action categories (incl. toggle), second-presentation delay, NFC tags for phones, automatic backups (on every change, nightly, retention), download / restore / import, keypad notifications, reader polling interval (0.3 to 3 s, applied live), name of the page in the sidebar |

**Enrolling a fingerprint.** Fingerprints are captured by the device itself (there is no
remote enrollment command). Click a free finger on the hand, pick its category: the page
shows the exact keys to type on the device keypad (`* #`, admin code, `3`, the UserID, `#`)
and detects the new fingerprint by itself. The page creates the UserID first, so the keypad
menu is `3` (backup fingerprint, adds a finger to an existing user); menu `1` (add user)
refuses an existing UserID. A UserID can hold several fingers: enroll them one after the
other with menu `3`.

**Identifying a finger.** The device reports which UserID recognized a finger, not which
of its fingerprints. *Identify a finger* (on a person, or from a free finger: *Already
enrolled? Identify it on the reader*) uses the reader as a sensor: place a finger and the
page shows the person, the UserID and the fingerprint slot. Started from a person, a finger
of someone else is refused (the page says whose finger it is, and which one) and nothing is
changed. Otherwise the page shows the current finger on the hand (or *not assigned*) and the
category, and offers to delete it; *Confirm* records the finger on the hand, by default the
current one (or the finger chosen to start), which can be changed first. While identifying, the reader's events run no
automation and are not logged (it stops after 60 s without a finger). When the UserID has
several fingerprints, they are separated for a moment: each is copied to a temporary
UserID without rights (9990-9999), the UserID's own copies are removed, and the page asks
for the same finger again; then everything is put back and checked. The isolation is
recorded first, so a restart or an error puts the fingerprints back as well. No backup is
taken meanwhile. The device may still drive its own lock output for a recognized finger.
The category can be changed from the same dialog: the fingerprint then moves to the
UserID of that category.

**Journaled fingerprint operations.** Every operation that writes or removes
fingerprints, or rewrites a user record (identification, moving a fingerprint to another
category, deleting one, assigning an unassigned UserID, renaming, card and code, preparing
an enrollment, slot repair), first writes the state of the UserIDs it touches to a journal
on disk: user record, rights, and each template with its data. Afterwards the device is
read back and compared with what the operation must have produced: the same templates,
byte for byte, in the same finger slots, bound to the user's own internal slot, a slot no
other user has. On any difference or error, those UserIDs are written back exactly as they
were and the operation reports it. If the operation was interrupted (Home Assistant
restarted, the device froze or was switched off), the journal left on disk is settled at
the next poll, retried every minute until it succeeds, with a notification; nothing else
(identification, automatic backup) runs meanwhile. The journal holds biometric data: it
is kept next to the backups, readable by Home Assistant only, and removed once settled.
Fingerprints or UserIDs that disappear from the device without an operation of Home
Assistant (keypad, other software, device fault) raise a notification pointing to the
backups.

**Learning a card.** Click *Learn a card* and present the card: the device reports it as
unknown, the page shows its number and writes it to the chosen person and category.

### Dashboard card

The integration also provides a card with the access activity, the same rows as the
panel's *Activity* tab, updated live. Any logged-in user can display it (managing people stays
reserved to administrators, in the panel):

```yaml
type: custom:zkaccess-activity-card
title: Front door        # optional
limit: 10                # rows shown, 1 to 100
filter: all              # all, open, actions or denied
person: 12               # optional: one person only
```

### Entities

| Entity | Description |
|---|---|
| `event.<device>_access` | fires `granted`, `action`, `denied` or `other` (attributes below) |
| `binary_sensor.<device>_door_N` | door contact (unknown when no sensor is wired) |
| `binary_sensor.<device>_door_N_alarm` | alarm / door open too long |
| `sensor.<device>_last_person` | name of the last person let in or who triggered an action |
| `sensor.<device>_people`, `_fingerprints`, `_cards` | counters |
| `button.<device>_open_door_N` | pulse the lock relay |
| `button.<device>_sync_clock` | set the device clock |
| `button.<device>_restart` | reboot the device (about 25 s without access; data and lock untouched) |
| `sensor.<device>_response_time` | median response time of the device, measured every hour |
| `switch.<device>_access_<person>` | one per person: access enabled / disabled (same as the panel toggle); usable in automations, e.g. a schedule |
| `binary_sensor.<device>_connected` | device reachable (stays available, so you can alert on it) |
| `sensor.<device>_clock_offset` | device clock drift before the last sync, in seconds |

Every access event is also fired on the bus as **`zkaccess_native_access`** with:

| Field | Example | Meaning |
|---|---|---|
| `result` | `granted` | `granted` (door released), `action` (known credential of a category without relay), `denied`, `other` |
| `person`, `person_name` | `12`, `Alice` | the person (with the "person + category" numbering) |
| `ha_person` | `person.alice` | linked Home Assistant person, if any |
| `category`, `category_digit`, `category_type` | `Arm`, `3`, `arm` | the action category |
| `gesture` | `single` / `double` | `double` = second presentation |
| `method` | `fingerprint` | `fingerprint`, `card`, `code`, `phone`, `remote`, `other` |
| `toggle` | `true` | the category was chosen by a toggle |
| `phone` | `Pixel 9` | name of the phone (phone access only) |
| `card_known` | `true` | card accesses only: the device knows the card (`false` = unknown card) |
| `user_id`, `door`, `event`, `event_name`, `time`, `device_id` | | raw details |

Card numbers are access credentials: they are **not** in this event, nor in the attributes of
the event entity (so not in the recorder history), nor sent to users who are not
administrators. Only the **Access control** page (administrators) shows them, for instance to
assign an unknown card that was just presented.

Actions:

- `zkaccess_native.set_access` (person, optional category, enabled): enable or disable a
  person, or one of their categories; `rename_person`; `open_door`; `sync_clock`; `backup`.
- Advanced, on raw UserIDs outside the person / category model: `set_user`, `delete_user`,
  `grant`, `revoke`, `list_users` (returns the users). Prefer the panel or `set_access`.
  These five actions are **reserved to administrators** (they create users on the door
  controller and give them access); the others can be used by any user.

The door sensor and its alarm are disabled by default when the device reports no door
contact wired; enable them in the entity settings if you wire one later.

Options: polling interval (default 1 s, 0.3 to 3 s), door open duration, clock sync on connection.

**Maintenance** (panel *Settings*, both on by default): reboot the reader every night at 04:00,
after the clock sync and the backup; and reboot it when its response time, measured every hour,
is over 0.5 s (at most once every 6 hours). A MA500 was seen slowing down to 0.5 s per request
after a busy day, which made everything slow (identification especially), and a reboot fixed it.
Action `zkaccess_native.restart` reboots on demand. The same page shows the **response time
history**: a chart of the measurements (24 h, 7 days, 30 days, 1 year) read from Home
Assistant's recorder, with the 0.5 s threshold and the reader reboots. Beyond 7 days it shows
the hourly (or daily) average with the min-max band, which the recorder keeps without limit.

While the reader reboots (about 25 s), an action you start gets the message "the reader is
rebooting, try again in N s". **Settings → Repairs** shows an issue when the reader has not
answered for more than 30 minutes, or had to be rebooted for slowness twice in 24 hours; it
disappears by itself once things are back to normal.
The device clock is also synced every night at 04:00.

**Diagnostics** can be downloaded from the device page (personal data, card numbers, names
and addresses are removed).

### Example automations

**Without YAML**, in the automation editor: *Add trigger → Device → your reader*, then
*Category … presented* (optionally by one person), *Access denied*, *Unknown card presented*
or *Unknown fingerprint presented*. The access is in `trigger.event.data`.

**Blueprints** (*Settings → Automations → Blueprints → Import blueprint*, paste the link):

| Blueprint | Does |
|---|---|
| [Run actions for a category](https://github.com/Avataar120/pyzkaccess/blob/main/blueprints/automation/zkaccess_native/category_actions.yaml) | your actions when a category is presented, optionally by one person |
| [Open the door and disarm](https://github.com/Avataar120/pyzkaccess/blob/main/blueprints/automation/zkaccess_native/open_and_disarm.yaml) | unlock a lock and/or pulse a strike switch, disarm the alarm, light at night |
| [Lock and arm when leaving](https://github.com/Avataar120/pyzkaccess/blob/main/blueprints/automation/zkaccess_native/leave_lock_and_arm.yaml) | lock the doors and arm the alarm (away, home, night or vacation) |
| [Alert on repeated refusals](https://github.com/Avataar120/pyzkaccess/blob/main/blueprints/automation/zkaccess_native/refusals_alert.yaml) | your alert actions after N refusals within M minutes |

**In YAML**:

A known fingerprint, card, code or phone gives `result: granted` when its category has
**Device relay** checked (the device released its own lock output) and `result: action`
otherwise (the device refused on purpose, Home Assistant acts). That setting only changes
the device's own output: react to both. Unknown fingers and cards, people or categories
switched off are always `denied`.

Open with a relay driven by Home Assistant, and disarm the alarm:

```yaml
automation:
  - alias: "Front door - open"
    triggers:
      - trigger: event
        event_type: zkaccess_native_access
        event_data:
          category_type: open
    conditions:
      - "{{ trigger.event.data.result in ['granted', 'action'] }}"
    actions:
      - action: switch.turn_on
        target: { entity_id: switch.front_door_strike }
      - delay: { seconds: 3 }
      - action: switch.turn_off
        target: { entity_id: switch.front_door_strike }
      - action: alarm_control_panel.alarm_disarm
        target: { entity_id: alarm_control_panel.home }
        data: { code: !secret alarm_code }
    mode: queued
```

One automation for every category, with a rule by method (phones open only in the daytime):

```yaml
automation:
  - alias: "Front door - actions"
    triggers:
      - trigger: event
        event_type: zkaccess_native_access
    conditions:
      - "{{ trigger.event.data.result in ['granted', 'action'] }}"
    actions:
      - choose:
          - conditions:
              - "{{ trigger.event.data.category_type == 'open' }}"
              - "{{ trigger.event.data.method != 'phone' or 7 <= now().hour < 22 }}"
            sequence:
              - action: lock.unlock
                target: { entity_id: lock.front_door }
          - conditions: "{{ trigger.event.data.category_type == 'arm' }}"
            sequence:
              - action: lock.lock
                target: { entity_id: lock.front_door }
              - action: alarm_control_panel.alarm_arm_away
                target: { entity_id: alarm_control_panel.home }
                data: { code: !secret alarm_code }
          - conditions: "{{ trigger.event.data.category == 'Garage' }}"
            sequence:
              - action: cover.toggle
                target: { entity_id: cover.garage }
```

Notify on refused attempts:

```yaml
automation:
  - alias: "Front door - refused"
    triggers:
      - trigger: event
        event_type: zkaccess_native_access
        event_data:
          result: denied
    actions:
      - action: notify.mobile_app_phone
        data:
          message: "Refused at the front door: {{ trigger.event.data.event_name }} ({{ trigger.event.data.method }})"
```

More in [examples/home_assistant_automations.yaml](examples/home_assistant_automations.yaml):
cards that never disarm, welcome light for one person after sunset, double badge, three
refusals in a minute with a camera snapshot, reader offline alert, logbook.

## Safety notes (read this)

Lessons learned the hard way while reverse-engineering. The library protects you
against each of them, but you should know them:

1. **Writing a user replaces the whole record.** Sending only a new name erases the
   password and the card number. → `save_user()` reads the record and merges first.
2. **Deleting without a condition erases the whole table.** → `delete_records()` refuses
   unless you pass `allow_wipe=True`.
3. **Some firmware give a new user an internal slot that another user already has.**
   Templates are bound to that slot, so a template written then could identify the wrong person.
   → `save_template()` checks for duplicates and refuses.
4. **Deleting a user does not delete its templates or its door rights.**
   → `delete_user()` cascades by default.
5. **ZKAccess "Add device" with "Clear data in device" checked erases the device**, even
   when it then fails with *"Unknown Device Model"*. Back up first
   (`zkaccess backup device.json`).
6. ZKAccess does not read door authorizations from the device: syncing its database back
   to the device can leave users without access.
7. Events are delivered to every open session: if two programs act on events, both will
   act. Do not manage a device from ZKAccess and this library at the same time.
8. **The reader's relay is reachable from outside.** Wiring a door lock to the relay of a
   reader mounted outdoors lets anyone who tears it off open the door by touching the wires.
   → Keep the lock relay indoors and let Home Assistant open the door (see
   [People and action categories](#people-and-action-categories)).
9. **Some firmware ignore a delete with several conditions** (the MA500 answers OK to
   `Pin` + `FingerID` and removes nothing). → `delete_templates(user, finger_id)` and
   `move_template()` delete by `Pin` only and write the other fingers back.

## Testing without hardware

An emulator speaking the same protocol is included:

```bash
python -m pyzkaccess_native.emulator --port 4370 &     # add --c3 to emulate a C3-400 panel
zkaccess --host 127.0.0.1 user-set 1 --name Test
zkaccess --host 127.0.0.1 users
```

In tests:

```python
from pyzkaccess_native import ZKAccess
from pyzkaccess_native.emulator import Emulator

def test_something():
    with Emulator() as emu, ZKAccess("127.0.0.1", emu.port) as dev:
        emu.state.push_event(14, user_id=1)        # simulate a fingerprint
        assert dev.poll()[0].user_id == 1
```

The emulator reproduces the behaviour observed on real devices (whole-record writes,
device-assigned slots, buffered transfers...), but the real device remains the reference.

## Troubleshooting

| Symptom | Cause / fix |
|---|---|
| `cannot connect` / timeout | wrong IP, device on another VLAN without routing, firewall, or a firmware that accepts a single session while another program is connected. |
| `device error -14` | wrong communication password (`ComPwd`). |
| `device error -13` | command not supported by this firmware. |
| no event received | check the polling loop is running; time zone / authorization of the user (event 23 = access denied). |
| `discover()` finds nothing | broadcasts do not cross routers: use `scan()` with the device's range, or connect by IP. |
| clock drifts | call `set_time()` daily (the integration does it on each connection). |
| `RTLog length N is a multiple of neither 16 nor 36` | unknown real-time log format: please open an issue with the payload printed in the error. |
| events not decoded although the device answers | in Home Assistant, check *Real-time log format* in the integration options (Auto by default; 36 bytes for recent C3 panels). |

Run with `-vv` (CLI) or `logging.getLogger("pyzkaccess_native").setLevel("DEBUG")` to see
every frame. At DEBUG level the library also logs each new real-time log answer split into
records, the table layout, and every table read with its decoded rows. Sensitive data is
masked everywhere, raw `<<` / `>>` frame lines included, so that a debug log can be shared:

- card numbers keep only their last 4 digits (`****3260`, `[card ****3260]` in the real-time log);
- passwords and the device communication password are replaced by `***` or hidden;
- fingerprint templates appear only as their size and a short hash (`<512 bytes sha256:...>`);
- frames that carry records (table reads and writes, real-time log) show their length only
  (`<32 bytes hidden>`): their content is logged decoded and masked on the lines around them.

### Collecting logs for an issue (Home Assistant)

1. **Settings > Devices & services > ZKAccess Native > ⋮ > Enable debug logging.**
2. Reproduce the problem: wait for the error, or present a card / finger / code at the reader.
   One or two minutes are enough.
3. On the same menu, **Disable debug logging**: Home Assistant then downloads the log file
   (`home-assistant_zkaccess_native_....log`) to your computer.
4. Also download **⋮ > Download diagnostics** (personal data is removed).
5. Attach both files to the issue. Card numbers, passwords and templates are masked in the
   debug log (since 0.6.6); it still shows the device IP address and user names: edit them
   out first if you prefer.

Without the UI, add this to `configuration.yaml` and restart, then read **Settings > System >
Logs > Show raw logs** (or the file `home-assistant.log` in the configuration folder):

```yaml
logger:
  default: warning
  logs:
    pyzkaccess_native: debug
    custom_components.zkaccess_native: debug
```

## Contributing

Issues and pull requests are welcome, especially:

- reports from other devices (`zkaccess info`, `zkaccess tables`);
- captures of PullSDK calls that are not documented yet (see the open questions at the
  end of [docs/PROTOCOL.md](docs/PROTOCOL.md)).

```bash
git clone https://github.com/Avataar120/pyzkaccess && cd pyzkaccess
pip install -e ".[test]"
pytest
```

Please never attach real fingerprint templates, passwords or card numbers to an issue.

### Releasing (maintainers)

1. Bump the version in `src/pyzkaccess_native/__init__.py`, and both `version` and the
   `pyzkaccess-native==` requirement in `custom_components/zkaccess_native/manifest.json`.
2. Update `CHANGELOG.md`, commit, then create a GitHub release with tag `vX.Y.Z`.
3. The `Publish to PyPI` workflow builds and uploads the package (PyPI trusted
   publishing, environment `pypi`; no token in the repository). The Marketplace picks up
   the release.

## Legal

This is an independent project, not affiliated with or endorsed by ZKTeco. "ZKTeco" and
"ZKAccess" are trademarks of their owners. The protocol was documented by observing the
network traffic of software and devices legitimately owned by the author, for
interoperability purposes. Released under the [MIT license](LICENSE).
