pyzkaccess-native 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ """Pure-Python client for ZKTeco PullSDK / ZKAccess access-control devices.
2
+
3
+ No DLL, no Windows: talks the device's TCP protocol directly.
4
+ """
5
+ from .client import DeviceInfo, ZKAccess
6
+ from .codec import Field, Table, decode_datetime, encode_datetime
7
+ from .discovery import DiscoveredDevice, discover
8
+ from .errors import DeviceError, ProtocolError, SafetyError, ZKConnectionError, ZKError
9
+ from .events import (AccessEvent, DoorSensor, DoorStatus, EventType, InOutState, VerifyMode,
10
+ event_label)
11
+ from .models import Authorization, Template, User
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "ZKAccess", "DeviceInfo", "discover", "DiscoveredDevice",
17
+ "User", "Template", "Authorization",
18
+ "AccessEvent", "DoorStatus", "DoorSensor", "EventType", "VerifyMode", "InOutState", "event_label",
19
+ "Table", "Field", "encode_datetime", "decode_datetime",
20
+ "ZKError", "ZKConnectionError", "ProtocolError", "DeviceError", "SafetyError",
21
+ "__version__",
22
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,107 @@
1
+ """Full backup and restore of a device's configuration tables, as JSON.
2
+
3
+ Fingerprint templates are restored byte for byte. Device UIDs cannot be chosen
4
+ by the client, so templates are re-bound to the UID the device gives each user
5
+ on restore.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any, Dict, Iterable, List, Optional, Union
14
+
15
+ from .client import ZKAccess
16
+ from .codec import Row
17
+ from .errors import SafetyError
18
+
19
+ FORMAT = "pyzkaccess-native/1"
20
+
21
+ #: Configuration tables, in restore order (time zones before users, users
22
+ #: before templates and authorizations). Log tables are not restored.
23
+ CONFIG_TABLES = ("timezone", "holiday", "user", "templatev10", "template", "userauthorize",
24
+ "firstcard", "multimcard", "inoutfun")
25
+ LOG_TABLES = ("transaction", "oplog")
26
+
27
+
28
+ def _to_json(row: Row) -> Dict[str, Any]:
29
+ return {k: (base64.b64encode(v).decode() if isinstance(v, bytes) else v) for k, v in row.items()}
30
+
31
+
32
+ def backup(dev: ZKAccess, tables: Optional[Iterable[str]] = None,
33
+ include_logs: bool = False) -> Dict[str, Any]:
34
+ """Read the device and return a JSON-serializable snapshot."""
35
+ available = dev.tables()
36
+ names = list(tables) if tables else [t for t in CONFIG_TABLES + (LOG_TABLES if include_logs else ())
37
+ if t in available]
38
+ info = dev.info()
39
+ return {
40
+ "format": FORMAT,
41
+ "created": datetime.now().isoformat(timespec="seconds"),
42
+ "device": {"serial_number": info.serial_number, "firmware": info.firmware,
43
+ "machine_type": info.machine_type},
44
+ "schema": {n: [[f.name, f.type, f.index] for f in available[n].fields] for n in names},
45
+ "tables": {n: [_to_json(r) for r in dev.read_table(n)] for n in names},
46
+ }
47
+
48
+
49
+ def save(snapshot: Dict[str, Any], path: Union[str, Path]) -> None:
50
+ # ensure_ascii keeps undecodable bytes of string fields (surrogate escapes) intact.
51
+ Path(path).write_text(json.dumps(snapshot, indent=1), encoding="utf-8")
52
+
53
+
54
+ def load(path: Union[str, Path]) -> Dict[str, Any]:
55
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
56
+ if data.get("format") != FORMAT:
57
+ raise ValueError(f"not a {FORMAT} backup")
58
+ return data
59
+
60
+
61
+ def _from_json(dev: ZKAccess, table: str, rows: List[Dict[str, Any]]) -> List[Row]:
62
+ binary = {f.name for f in dev.table(table).fields if f.type == "B"}
63
+ known = set(dev.table(table).field_names)
64
+ return [{k: (base64.b64decode(v) if k in binary else v) for k, v in r.items() if k in known}
65
+ for r in rows]
66
+
67
+
68
+ def restore(dev: ZKAccess, snapshot: Dict[str, Any], tables: Optional[Iterable[str]] = None,
69
+ wipe: bool = False) -> Dict[str, int]:
70
+ """Write a snapshot back to the device. Returns the number of records per table.
71
+
72
+ With ``wipe=True`` each restored table is erased first, so the device ends
73
+ up with exactly the snapshot content. Without it, records are merged
74
+ (existing PINs are overwritten, others are kept).
75
+ """
76
+ data = snapshot["tables"]
77
+ names = [t for t in CONFIG_TABLES if t in data and (tables is None or t in tables)]
78
+ names += [t for t in data if t not in names and t not in LOG_TABLES and (tables is None or t in tables)]
79
+ unknown = [t for t in names if t not in dev.tables()]
80
+ if unknown:
81
+ raise SafetyError(f"the device has no table {unknown}")
82
+ done: Dict[str, int] = {}
83
+ with dev._lock:
84
+ if wipe:
85
+ for name in reversed(names):
86
+ dev.delete_records(name, None, allow_wipe=True)
87
+ uids: Dict[int, int] = {}
88
+ for name in names:
89
+ rows = _from_json(dev, name, data[name])
90
+ if name == "user":
91
+ for row in rows:
92
+ row.pop("UID", None)
93
+ dev.write_records(name, [row])
94
+ stored = dev.read_table("user", fields=["UID", "Pin"])
95
+ uids = {u["Pin"]: u["UID"] for u in stored}
96
+ if len(set(uids.values())) != len(uids):
97
+ raise SafetyError("the device assigned duplicate UIDs; templates not restored")
98
+ elif name in ("templatev10", "template"):
99
+ for row in rows:
100
+ if "UID" in row and row.get("Pin") in uids:
101
+ row["UID"] = uids[row["Pin"]]
102
+ dev.write_records(name, [row])
103
+ else:
104
+ for row in rows:
105
+ dev.write_records(name, [row])
106
+ done[name] = len(rows)
107
+ return done
@@ -0,0 +1,244 @@
1
+ """Command line interface: ``zkaccess --host 192.168.1.201 <command>``."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import base64
6
+ import json
7
+ import logging
8
+ import os
9
+ import sys
10
+ from datetime import datetime
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from . import __version__, backup as backup_mod
14
+ from .client import ZKAccess
15
+ from .discovery import discover
16
+ from .errors import ZKError
17
+ from .events import AccessEvent
18
+ from .models import User
19
+
20
+
21
+ def _parse_where(items: Optional[List[str]]) -> Optional[Dict[str, Any]]:
22
+ if not items:
23
+ return None
24
+ out: Dict[str, Any] = {}
25
+ for item in items:
26
+ key, _, value = item.partition("=")
27
+ out[key] = int(value) if value.isdigit() else value
28
+ return out
29
+
30
+
31
+ def _jsonable(value: Any) -> Any:
32
+ if isinstance(value, bytes):
33
+ return base64.b64encode(value).decode()
34
+ if isinstance(value, datetime):
35
+ return value.isoformat()
36
+ return value
37
+
38
+
39
+ def _print_rows(rows: List[Dict[str, Any]], as_json: bool) -> None:
40
+ if as_json:
41
+ print(json.dumps([{k: _jsonable(v) for k, v in r.items()} for r in rows], indent=1,
42
+ ensure_ascii=False))
43
+ return
44
+ if not rows:
45
+ print("(no record)")
46
+ return
47
+ cols = list(rows[0])
48
+
49
+ def cell(v: Any) -> str:
50
+ return f"<{len(v)} bytes>" if isinstance(v, bytes) else str(v)
51
+
52
+ widths = {c: max(len(c), *(len(cell(r.get(c, ""))) for r in rows)) for c in cols}
53
+ print(" ".join(c.ljust(widths[c]) for c in cols))
54
+ for r in rows:
55
+ print(" ".join(cell(r.get(c, "")).ljust(widths[c]) for c in cols))
56
+
57
+
58
+ def build_parser() -> argparse.ArgumentParser:
59
+ p = argparse.ArgumentParser(prog="zkaccess", description="ZKTeco PullSDK / ZKAccess device tool")
60
+ p.add_argument("--host", default=os.environ.get("ZKACCESS_HOST"),
61
+ help="device IP address (or $ZKACCESS_HOST)")
62
+ p.add_argument("--port", type=int, default=int(os.environ.get("ZKACCESS_PORT", 4370)))
63
+ p.add_argument("--password", default=os.environ.get("ZKACCESS_PASSWORD", ""),
64
+ help="communication password (or $ZKACCESS_PASSWORD)")
65
+ p.add_argument("--timeout", type=float, default=5.0)
66
+ p.add_argument("-v", "--verbose", action="count", default=0, help="-v info, -vv frame dump")
67
+ p.add_argument("--version", action="version", version=__version__)
68
+ sub = p.add_subparsers(dest="cmd", required=True)
69
+
70
+ sub.add_parser("discover", help="find devices on the local network (UDP broadcast)")
71
+ sub.add_parser("info", help="device identity and capabilities")
72
+ sub.add_parser("tables", help="list tables and their fields")
73
+
74
+ s = sub.add_parser("params", help="read or write device parameters")
75
+ s.add_argument("items", nargs="+", help="Name to read, or Name=value to write")
76
+
77
+ s = sub.add_parser("time", help="read the device clock, or set it with --set")
78
+ s.add_argument("--set", nargs="?", const="now", metavar="YYYY-MM-DDTHH:MM:SS")
79
+
80
+ s = sub.add_parser("read", help="read a table")
81
+ s.add_argument("table")
82
+ s.add_argument("--where", action="append", metavar="Field=value")
83
+ s.add_argument("--fields", help="comma separated field list")
84
+ s.add_argument("--json", action="store_true")
85
+
86
+ s = sub.add_parser("count", help="number of records in a table")
87
+ s.add_argument("table")
88
+
89
+ s = sub.add_parser("users", help="list users")
90
+ s.add_argument("--json", action="store_true")
91
+
92
+ s = sub.add_parser("user-set", help="create or update a user (other fields are kept)")
93
+ s.add_argument("pin", type=int)
94
+ s.add_argument("--name")
95
+ s.add_argument("--card", type=int)
96
+ s.add_argument("--user-password", dest="user_password", help="keypad password of the user")
97
+
98
+ s = sub.add_parser("user-delete", help="delete a user with its templates and authorizations")
99
+ s.add_argument("pin", type=int)
100
+ s.add_argument("--yes", action="store_true", help="do not ask for confirmation")
101
+
102
+ s = sub.add_parser("grant", help="authorize a user on doors")
103
+ s.add_argument("pin", type=int)
104
+ s.add_argument("--timezone", type=int, default=1)
105
+ s.add_argument("--doors", type=int, default=1, help="door bit mask (1, 2, 4, 8)")
106
+
107
+ s = sub.add_parser("revoke", help="remove every authorization of a user")
108
+ s.add_argument("pin", type=int)
109
+
110
+ s = sub.add_parser("backup", help="save configuration tables to a JSON file")
111
+ s.add_argument("file")
112
+ s.add_argument("--logs", action="store_true", help="also save transaction/oplog tables")
113
+
114
+ s = sub.add_parser("restore", help="write a JSON backup back to the device")
115
+ s.add_argument("file")
116
+ s.add_argument("--wipe", action="store_true", help="erase the tables first (exact copy)")
117
+ s.add_argument("--yes", action="store_true", help="do not ask for confirmation")
118
+
119
+ s = sub.add_parser("events", help="print access events in real time (Ctrl+C to stop)")
120
+ s.add_argument("--status", action="store_true", help="also print door status records")
121
+ s.add_argument("--interval", type=float, default=0.5)
122
+ s.add_argument("--json", action="store_true")
123
+
124
+ s = sub.add_parser("door", help="drive the lock relay")
125
+ s.add_argument("action", choices=["open", "close", "hold"])
126
+ s.add_argument("--door", type=int, default=1)
127
+ s.add_argument("--seconds", type=int, default=5)
128
+
129
+ s = sub.add_parser("aux", help="drive an auxiliary output")
130
+ s.add_argument("output", type=int)
131
+ s.add_argument("seconds", type=int, help="0 = off, 1-254 = pulse, 255 = on")
132
+
133
+ sub.add_parser("cancel-alarm", help="cancel the current alarm")
134
+ sub.add_parser("restart", help="reboot the device")
135
+ return p
136
+
137
+
138
+ def _confirm(question: str, assume_yes: bool) -> bool:
139
+ if assume_yes:
140
+ return True
141
+ return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
142
+
143
+
144
+ def run(args: argparse.Namespace) -> int:
145
+ if args.cmd == "discover":
146
+ devices = discover()
147
+ _print_rows([{"ip": d.ip, "mac": d.mac, "serial": d.serial_number, "name": d.device_name,
148
+ "firmware": d.firmware} for d in devices], False)
149
+ return 0
150
+ if not args.host:
151
+ print("error: --host (or $ZKACCESS_HOST) is required", file=sys.stderr)
152
+ return 2
153
+
154
+ with ZKAccess(args.host, args.port, args.password, args.timeout) as dev:
155
+ cmd = args.cmd
156
+ if cmd == "info":
157
+ info = dev.info()
158
+ for k, v in vars(info).items():
159
+ if k != "raw":
160
+ print(f"{k:20} {v}")
161
+ elif cmd == "tables":
162
+ for t in dev.tables().values():
163
+ print(f"{t.index:3} {t.name:15} " + ", ".join(f"{f.name}:{f.type}" for f in t.fields))
164
+ elif cmd == "params":
165
+ writes = dict(i.split("=", 1) for i in args.items if "=" in i)
166
+ reads = [i for i in args.items if "=" not in i]
167
+ if writes:
168
+ dev.set_params(writes)
169
+ for k, v in dev.get_params(reads or list(writes)).items():
170
+ print(f"{k}={v}")
171
+ elif cmd == "time":
172
+ if args.set:
173
+ when = datetime.now() if args.set == "now" else datetime.fromisoformat(args.set)
174
+ dev.set_time(when)
175
+ device_time = dev.get_time()
176
+ print(f"device: {device_time} local: {datetime.now().replace(microsecond=0)}")
177
+ elif cmd == "read":
178
+ fields = args.fields.split(",") if args.fields else None
179
+ _print_rows(dev.read_table(args.table, fields, _parse_where(args.where)), args.json)
180
+ elif cmd == "count":
181
+ print(dev.count(args.table))
182
+ elif cmd == "users":
183
+ _print_rows([u.to_row() for u in dev.get_users()], args.json)
184
+ elif cmd == "user-set":
185
+ user = dev.save_user(User(args.pin, name=args.name, card_no=args.card, password=args.user_password))
186
+ _print_rows([user.to_row()], False)
187
+ elif cmd == "user-delete":
188
+ if not _confirm(f"Delete user {args.pin}, its templates and authorizations?", args.yes):
189
+ return 1
190
+ dev.delete_user(args.pin)
191
+ elif cmd == "grant":
192
+ dev.grant(args.pin, args.timezone, args.doors)
193
+ elif cmd == "revoke":
194
+ dev.revoke(args.pin)
195
+ elif cmd == "backup":
196
+ snap = backup_mod.backup(dev, include_logs=args.logs)
197
+ backup_mod.save(snap, args.file)
198
+ print(", ".join(f"{k}: {len(v)}" for k, v in snap["tables"].items()))
199
+ elif cmd == "restore":
200
+ snap = backup_mod.load(args.file)
201
+ what = "ERASE and replace" if args.wipe else "merge into"
202
+ if not _confirm(f"{what} the device tables {list(snap['tables'])}?", args.yes):
203
+ return 1
204
+ print(backup_mod.restore(dev, snap, wipe=args.wipe))
205
+ elif cmd == "events":
206
+ try:
207
+ for rec in dev.events(args.interval, include_status=args.status):
208
+ if args.json:
209
+ d = {k: _jsonable(v) for k, v in vars(rec).items() if k != "raw"}
210
+ print(json.dumps(d), flush=True)
211
+ elif isinstance(rec, AccessEvent):
212
+ print(f"{rec.time} door {rec.door} pin {rec.pin:<6} card {rec.card:<10} "
213
+ f"{int(rec.event):3} {rec.label}", flush=True)
214
+ else:
215
+ print(f"{rec.time} status sensors {[int(s) for s in rec.sensors]} "
216
+ f"alarms {rec.alarms.hex()}", flush=True)
217
+ except KeyboardInterrupt:
218
+ pass
219
+ elif cmd == "door":
220
+ {"open": lambda: dev.open_door(args.door, args.seconds),
221
+ "close": lambda: dev.close_door(args.door),
222
+ "hold": lambda: dev.hold_door_open(args.door)}[args.action]()
223
+ elif cmd == "aux":
224
+ dev.set_aux_output(args.output, args.seconds)
225
+ elif cmd == "cancel-alarm":
226
+ dev.cancel_alarm()
227
+ elif cmd == "restart":
228
+ dev.restart()
229
+ return 0
230
+
231
+
232
+ def main(argv: Optional[List[str]] = None) -> int:
233
+ args = build_parser().parse_args(argv)
234
+ logging.basicConfig(level=[logging.WARNING, logging.INFO, logging.DEBUG][min(args.verbose, 2)],
235
+ format="%(levelname)s %(name)s: %(message)s")
236
+ try:
237
+ return run(args)
238
+ except ZKError as ex:
239
+ print(f"error: {ex}", file=sys.stderr)
240
+ return 1
241
+
242
+
243
+ if __name__ == "__main__":
244
+ sys.exit(main())