1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
//! The [`Zk`] device client: connection, command dispatch, and every operation.
//!
//! This is a synchronous, blocking port of `pyzk`'s `ZK` class. All network I/O
//! uses [`std::net`]; to use it from an async runtime, wrap calls in a blocking
//! task (e.g. `tokio::task::spawn_blocking`).
use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use chrono::NaiveDateTime;
use crate::constants as c;
use crate::error::{ZkError, ZkResult};
use crate::helper::ZkHelper;
use crate::protocol::{self, u16_le, u32_le, wr};
use crate::{Attendance, Finger, User};
/// Memory / record counters reported by the device (see [`Zk::read_sizes`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DeviceSizes {
/// Number of enrolled users.
pub users: u32,
/// Number of stored fingerprint templates.
pub fingers: u32,
/// Number of attendance records.
pub records: u32,
/// Number of stored cards.
pub cards: u32,
/// Fingerprint template capacity.
pub fingers_cap: u32,
/// User capacity.
pub users_cap: u32,
/// Attendance record capacity.
pub rec_cap: u32,
/// Fingerprint templates still available.
pub fingers_available: u32,
/// User slots still available.
pub users_available: u32,
/// Attendance record slots still available.
pub records_available: u32,
/// Number of enrolled faces.
pub faces: u32,
/// Face capacity.
pub faces_cap: u32,
}
/// Network parameters reported by the device (see [`Zk::get_network_params`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkParams {
/// Device IP address.
pub ip: String,
/// Network mask.
pub mask: String,
/// Default gateway.
pub gateway: String,
}
/// Outcome of a single command exchange.
struct CmdResponse {
/// `true` if the device acknowledged (OK / data / prepare-data).
status: bool,
/// The raw reply command code.
code: u16,
}
/// The transport socket — either a TCP stream or a connected UDP socket.
enum Transport {
Tcp(TcpStream),
Udp(UdpSocket),
}
impl Transport {
/// Send a buffer in full.
fn send(&mut self, buf: &[u8]) -> std::io::Result<()> {
match self {
Transport::Tcp(s) => s.write_all(buf),
Transport::Udp(s) => s.send(buf).map(|_| ()),
}
}
/// Receive up to `max` bytes in a single read (mirrors Python `recv`).
fn recv(&mut self, max: usize) -> std::io::Result<Vec<u8>> {
let mut buf = vec![0u8; max];
let n = match self {
Transport::Tcp(s) => s.read(&mut buf)?,
Transport::Udp(s) => s.recv(&mut buf)?,
};
buf.truncate(n);
Ok(buf)
}
/// Apply a read timeout to the underlying socket.
fn set_read_timeout(&self, t: Option<Duration>) -> std::io::Result<()> {
match self {
Transport::Tcp(s) => s.set_read_timeout(t),
Transport::Udp(s) => s.set_read_timeout(t),
}
}
}
/// A connection to a single ZKTeco terminal.
///
/// Construct one with [`Zk::builder`], then [`connect`](Zk::connect):
///
/// ```no_run
/// use zkteco::Zk;
/// # fn main() -> zkteco::ZkResult<()> {
/// let mut zk = Zk::builder("192.168.1.201").build();
/// zk.connect()?;
/// for user in zk.get_users()? {
/// println!("{user}");
/// }
/// zk.disconnect()?;
/// # Ok(())
/// # }
/// ```
pub struct Zk {
// --- configuration ---
ip: String,
port: u16,
address: SocketAddr,
timeout: Duration,
password: u32,
force_udp: bool,
omit_ping: bool,
verbose: bool,
// --- live connection state ---
transport: Option<Transport>,
tcp: bool,
session_id: u16,
reply_id: u16,
// --- last-response scratch (set by `send_command`) ---
last_response: u16,
last_header: [u16; 4],
last_data: Vec<u8>,
tcp_length: u32,
// --- public-ish state mirrored from `pyzk` ---
is_connect: bool,
is_enabled: bool,
user_packet_size: usize,
next_uid: u16,
next_user_id: String,
sizes: DeviceSizes,
}
/// Builder for [`Zk`]. Created via [`Zk::builder`].
pub struct ZkBuilder {
ip: String,
port: u16,
timeout: Duration,
password: u32,
force_udp: bool,
omit_ping: bool,
verbose: bool,
}
impl ZkBuilder {
/// Device port (default `4370`).
pub fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Socket read timeout (default 60s).
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Numeric device communication password (default `0`, i.e. none).
pub fn password(mut self, password: u32) -> Self {
self.password = password;
self
}
/// Force the UDP transport instead of TCP (default `false`).
pub fn force_udp(mut self, force_udp: bool) -> Self {
self.force_udp = force_udp;
self
}
/// Skip the ICMP ping reachability check before connecting (default `false`).
pub fn omit_ping(mut self, omit_ping: bool) -> Self {
self.omit_ping = omit_ping;
self
}
/// Emit protocol diagnostics to stderr (default `false`).
pub fn verbose(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}
/// Finish building. Resolution of the address is deferred to
/// [`Zk::connect`]; an unresolved host yields a placeholder address here.
pub fn build(self) -> Zk {
let address = (self.ip.as_str(), self.port)
.to_socket_addrs()
.ok()
.and_then(|mut it| it.next())
.unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], self.port)));
Zk {
ip: self.ip,
port: self.port,
address,
timeout: self.timeout,
password: self.password,
force_udp: self.force_udp,
omit_ping: self.omit_ping,
verbose: self.verbose,
transport: None,
tcp: !self.force_udp,
session_id: 0,
reply_id: c::USHRT_MAX - 1,
last_response: 0,
last_header: [0; 4],
last_data: Vec::new(),
tcp_length: 0,
is_connect: false,
is_enabled: true,
user_packet_size: 28, // default ZK6; upgraded to 72 if TCP works
next_uid: 1,
next_user_id: "1".to_string(),
sizes: DeviceSizes::default(),
}
}
}
impl Zk {
/// Begin configuring a connection to `ip`.
pub fn builder(ip: impl Into<String>) -> ZkBuilder {
ZkBuilder {
ip: ip.into(),
port: 4370,
timeout: Duration::from_secs(60),
password: 0,
force_udp: false,
omit_ping: false,
verbose: false,
}
}
/// `true` while a session is open.
pub fn is_connected(&self) -> bool {
self.is_connect
}
/// `true` while the device is enabled (accepting user interaction).
pub fn is_enabled(&self) -> bool {
self.is_enabled
}
/// The next user index this crate would auto-assign (populated by
/// [`get_users`](Zk::get_users)).
pub fn next_uid(&self) -> u16 {
self.next_uid
}
/// The next free user-id string (populated by [`get_users`](Zk::get_users)).
pub fn next_user_id(&self) -> &str {
&self.next_user_id
}
/// The most recent capacity snapshot (see [`read_sizes`](Zk::read_sizes)).
pub fn sizes(&self) -> DeviceSizes {
self.sizes
}
/// Print a diagnostic line when `verbose` was enabled.
fn log(&self, msg: impl AsRef<str>) {
if self.verbose {
eprintln!("[zkteco] {}", msg.as_ref());
}
}
// ----------------------------------------------------------------------
// Connection lifecycle
// ----------------------------------------------------------------------
/// Open the socket, start a session, and authenticate if required.
pub fn connect(&mut self) -> ZkResult<()> {
// Optional reachability checks, mirroring pyzk.
if !self.omit_ping {
let helper = ZkHelper::new(self.ip.clone(), self.port);
if !helper.test_ping() {
return Err(ZkError::Network(std::io::Error::other(format!(
"can't reach device (ping {})",
self.ip
))));
}
}
if !self.force_udp {
// If TCP is reachable, the device uses the larger 72-byte user record.
let helper = ZkHelper::new(self.ip.clone(), self.port);
if helper.test_tcp() {
self.user_packet_size = 72;
}
}
self.create_socket()?;
self.session_id = 0;
self.reply_id = c::USHRT_MAX - 1;
let resp = self.send_command(c::CMD_CONNECT, &[], 8)?;
// The device echoes the new session id in header field 2.
self.session_id = self.last_header[2];
let resp = if resp.code == c::CMD_ACK_UNAUTH {
self.log("device requires auth, sending comm-key");
let key = protocol::make_commkey(self.password, self.session_id as u32, 50);
self.send_command(c::CMD_AUTH, &key, 8)?
} else {
resp
};
if resp.status {
self.is_connect = true;
Ok(())
} else if resp.code == c::CMD_ACK_UNAUTH {
Err(ZkError::Unauthenticated)
} else {
Err(ZkError::response_with_code("can't connect", resp.code))
}
}
/// Close the session and the socket.
pub fn disconnect(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_EXIT, &[], 8)?;
if resp.status {
self.is_connect = false;
self.transport = None;
Ok(())
} else {
Err(ZkError::response("can't disconnect"))
}
}
/// Re-enable the device (allow user interaction).
pub fn enable_device(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_ENABLEDEVICE, &[], 8)?;
if resp.status {
self.is_enabled = true;
Ok(())
} else {
Err(ZkError::response("can't enable device"))
}
}
/// Disable the device (lock out users during bulk operations).
pub fn disable_device(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_DISABLEDEVICE, &[], 8)?;
if resp.status {
self.is_enabled = false;
Ok(())
} else {
Err(ZkError::response("can't disable device"))
}
}
/// Create the underlying socket according to the chosen transport.
fn create_socket(&mut self) -> ZkResult<()> {
if self.tcp {
let stream = TcpStream::connect_timeout(&self.address, self.timeout)?;
stream.set_read_timeout(Some(self.timeout))?;
stream.set_write_timeout(Some(self.timeout))?;
self.transport = Some(Transport::Tcp(stream));
} else {
let sock = UdpSocket::bind("0.0.0.0:0")?;
sock.connect(self.address)?;
sock.set_read_timeout(Some(self.timeout))?;
self.transport = Some(Transport::Udp(sock));
}
Ok(())
}
// ----------------------------------------------------------------------
// Command dispatch
// ----------------------------------------------------------------------
/// Send one command and read one reply, updating the response scratch state.
///
/// `response_size` is the number of payload bytes to read (the TCP path adds
/// the 8-byte framing header automatically).
fn send_command(
&mut self,
command: u16,
command_string: &[u8],
response_size: usize,
) -> ZkResult<CmdResponse> {
if command != c::CMD_CONNECT && command != c::CMD_AUTH && !self.is_connect {
return Err(ZkError::NotConnected);
}
let buf = protocol::create_header(command, command_string, self.session_id, self.reply_id);
let tcp = self.tcp;
let sock = self.transport.as_mut().ok_or(ZkError::NotConnected)?;
let (header, data) = if tcp {
let top = protocol::create_tcp_top(&buf);
sock.send(&top)?;
let recv = sock.recv(response_size + 8)?;
self.tcp_length = protocol::test_tcp_top(&recv);
if self.tcp_length == 0 {
return Err(ZkError::Parse("TCP packet invalid".into()));
}
if recv.len() < 16 {
return Err(ZkError::Parse("short TCP header".into()));
}
let header = read_header(&recv[8..16]);
// `data_recv` is everything after the TCP top; payload starts after
// its own 8-byte command header.
let data = recv[16..].to_vec();
(header, data)
} else {
sock.send(&buf)?;
let recv = sock.recv(response_size)?;
if recv.len() < 8 {
return Err(ZkError::Parse("short UDP header".into()));
}
let header = read_header(&recv[0..8]);
let data = recv[8..].to_vec();
(header, data)
};
self.last_header = header;
self.last_response = header[0];
self.reply_id = header[3];
self.last_data = data;
let status = matches!(
self.last_response,
c::CMD_ACK_OK | c::CMD_PREPARE_DATA | c::CMD_DATA
);
Ok(CmdResponse {
status,
code: self.last_response,
})
}
/// Send a bare `CMD_ACK_OK` (used to acknowledge real-time event packets).
fn ack_ok(&mut self) -> ZkResult<()> {
let buf = protocol::create_header(c::CMD_ACK_OK, &[], self.session_id, c::USHRT_MAX - 1);
let tcp = self.tcp;
let sock = self.transport.as_mut().ok_or(ZkError::NotConnected)?;
if tcp {
let top = protocol::create_tcp_top(&buf);
sock.send(&top)?;
} else {
sock.send(&buf)?;
}
Ok(())
}
/// Size announced by a `CMD_PREPARE_DATA` reply (0 otherwise).
fn get_data_size(&self) -> usize {
if self.last_response == c::CMD_PREPARE_DATA && self.last_data.len() >= 4 {
u32_le(&self.last_data[0..4]) as usize
} else {
0
}
}
// ----------------------------------------------------------------------
// Device information
// ----------------------------------------------------------------------
/// Firmware version string.
pub fn get_firmware_version(&mut self) -> ZkResult<String> {
let resp = self.send_command(c::CMD_GET_VERSION, &[], 1024)?;
if resp.status {
Ok(decode_until_nul(&self.last_data))
} else {
Err(ZkError::response("can't read firmware version"))
}
}
/// Read a `~Key`-style device option and return its value (text after `=`).
fn read_option(&mut self, key: &[u8]) -> ZkResult<Option<String>> {
let resp = self.send_command(c::CMD_OPTIONS_RRQ, key, 1024)?;
if resp.status {
Ok(Some(decode_option_value(&self.last_data)))
} else {
Ok(None)
}
}
/// Device serial number.
pub fn get_serialnumber(&mut self) -> ZkResult<String> {
self.read_option(b"~SerialNumber\x00")?
.map(|s| s.replace('=', ""))
.ok_or_else(|| ZkError::response("can't read serial number"))
}
/// Platform name.
pub fn get_platform(&mut self) -> ZkResult<String> {
self.read_option(b"~Platform\x00")?
.map(|s| s.replace('=', ""))
.ok_or_else(|| ZkError::response("can't read platform name"))
}
/// MAC address.
pub fn get_mac(&mut self) -> ZkResult<String> {
self.read_option(b"MAC\x00")?
.ok_or_else(|| ZkError::response("can't read mac address"))
}
/// Device name (empty string if unavailable).
pub fn get_device_name(&mut self) -> ZkResult<String> {
Ok(self.read_option(b"~DeviceName\x00")?.unwrap_or_default())
}
/// Face-engine version (0 if none, `None` if the option is missing).
pub fn get_face_version(&mut self) -> ZkResult<Option<u32>> {
Ok(self
.read_option(b"ZKFaceVersion\x00")?
.map(|s| s.trim().parse().unwrap_or(0)))
}
/// Fingerprint algorithm version.
pub fn get_fp_version(&mut self) -> ZkResult<u32> {
self.read_option(b"~ZKFPVersion\x00")?
.map(|s| s.replace('=', "").trim().parse().unwrap_or(0))
.ok_or_else(|| ZkError::response("can't read fingerprint version"))
}
/// Read network parameters (IP / mask / gateway).
pub fn get_network_params(&mut self) -> ZkResult<NetworkParams> {
let ip = self
.read_option(b"IPAddress\x00")?
.unwrap_or_else(|| self.ip.clone());
let mask = self.read_option(b"NetMask\x00")?.unwrap_or_default();
let gateway = self.read_option(b"GATEIPAddress\x00")?.unwrap_or_default();
Ok(NetworkParams { ip, mask, gateway })
}
/// Configured user-id (PIN) width in characters.
pub fn get_pin_width(&mut self) -> ZkResult<u8> {
let resp = self.send_command(c::CMD_GET_PINWIDTH, b" P", 9)?;
if resp.status && !self.last_data.is_empty() {
// First byte before the NUL terminator.
Ok(self.last_data[0])
} else {
Err(ZkError::response("can't get pin width"))
}
}
/// Read device memory / record counters into [`DeviceSizes`] (also cached on
/// `self`, see [`sizes`](Zk::sizes)).
pub fn read_sizes(&mut self) -> ZkResult<DeviceSizes> {
let resp = self.send_command(c::CMD_GET_FREE_SIZES, &[], 1024)?;
if !resp.status {
return Err(ZkError::response("can't read sizes"));
}
let data = self.last_data.clone();
let mut sizes = DeviceSizes::default();
// First 80 bytes = 20 little-endian i32 fields; we only need a subset.
if data.len() >= 80 {
let field = |i: usize| u32_le(&data[i * 4..i * 4 + 4]);
sizes.users = field(4);
sizes.fingers = field(6);
sizes.records = field(8);
sizes.cards = field(12);
sizes.fingers_cap = field(14);
sizes.users_cap = field(15);
sizes.rec_cap = field(16);
sizes.fingers_available = field(17);
sizes.users_available = field(18);
sizes.records_available = field(19);
// Optional 12-byte face block immediately after.
if data.len() >= 92 {
sizes.faces = u32_le(&data[80..84]);
sizes.faces_cap = u32_le(&data[88..92]);
}
}
self.sizes = sizes;
Ok(sizes)
}
// ----------------------------------------------------------------------
// Device control
// ----------------------------------------------------------------------
/// Read the device clock.
pub fn get_time(&mut self) -> ZkResult<NaiveDateTime> {
let resp = self.send_command(c::CMD_GET_TIME, &[], 1032)?;
if resp.status && self.last_data.len() >= 4 {
Ok(protocol::decode_time(u32_le(&self.last_data[0..4])))
} else {
Err(ZkError::response("can't get time"))
}
}
/// Set the device clock.
pub fn set_time(&mut self, timestamp: NaiveDateTime) -> ZkResult<()> {
let cmd = wr(|w| {
w.u32(protocol::encode_time(×tamp));
});
self.ok_or(c::CMD_SET_TIME, &cmd, "can't set time")
}
/// Restart the device (ends the session).
pub fn restart(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_RESTART, &[], 8)?;
if resp.status {
self.is_connect = false;
self.next_uid = 1;
Ok(())
} else {
Err(ZkError::response("can't restart device"))
}
}
/// Power the device off (ends the session).
pub fn poweroff(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_POWEROFF, &[], 1032)?;
if resp.status {
self.is_connect = false;
self.next_uid = 1;
Ok(())
} else {
Err(ZkError::response("can't poweroff"))
}
}
/// Refresh the device's internal data after writes.
pub fn refresh_data(&mut self) -> ZkResult<()> {
self.ok_or(c::CMD_REFRESHDATA, &[], "can't refresh data")
}
/// Clear the device's open data buffer.
pub fn free_data(&mut self) -> ZkResult<()> {
self.ok_or(c::CMD_FREE_DATA, &[], "can't free data")
}
/// Play a built-in voice prompt / beep by index (see the device manual for
/// the index table). Returns `true` if accepted.
pub fn test_voice(&mut self, index: u32) -> ZkResult<bool> {
let cmd = wr(|w| {
w.u32(index);
});
Ok(self.send_command(c::CMD_TESTVOICE, &cmd, 8)?.status)
}
/// Unlock the door for `seconds` seconds.
pub fn unlock(&mut self, seconds: u32) -> ZkResult<()> {
// The device expects the delay in tenths of a second.
let cmd = wr(|w| {
w.u32(seconds * 10);
});
self.ok_or(c::CMD_UNLOCK, &cmd, "can't open door")
}
/// Query the door/lock state. Returns `true` if the device acknowledges.
pub fn get_lock_state(&mut self) -> ZkResult<bool> {
Ok(self.send_command(c::CMD_DOORSTATE_RRQ, &[], 8)?.status)
}
/// Write `text` to a line of the device LCD.
pub fn write_lcd(&mut self, line_number: i16, text: &str) -> ZkResult<()> {
let cmd = wr(|w| {
w.u16(line_number as u16) // '<h'
.u8(0) // 'b'
.u8(b' ')
.bytes(text.as_bytes());
});
self.ok_or(c::CMD_WRITE_LCD, &cmd, "can't write lcd")
}
/// Clear the device LCD.
pub fn clear_lcd(&mut self) -> ZkResult<()> {
self.ok_or(c::CMD_CLEAR_LCD, &[], "can't clear lcd")
}
/// Register for real-time events (bitmask of `EF_*`).
pub fn reg_event(&mut self, flags: u32) -> ZkResult<()> {
let cmd = wr(|w| {
w.u32(flags);
});
let resp = self.send_command(c::CMD_REG_EVENT, &cmd, 8)?;
if resp.status {
Ok(())
} else {
Err(ZkError::response(format!("can't reg events {flags}")))
}
}
/// Cancel an in-progress fingerprint capture.
pub fn cancel_capture(&mut self) -> ZkResult<bool> {
Ok(self.send_command(c::CMD_CANCELCAPTURE, &[], 8)?.status)
}
/// Enter verify state (used around enroll / live capture).
pub fn verify_user(&mut self) -> ZkResult<()> {
self.ok_or(c::CMD_STARTVERIFY, &[], "can't verify")
}
/// Enable SDK build mode 1 (some devices need this before bulk reads).
pub fn set_sdk_build_1(&mut self) -> ZkResult<bool> {
Ok(self
.send_command(c::CMD_OPTIONS_WRQ, b"SDKBuild=1", 8)?
.status)
}
/// Helper: send a command and map a non-ack into a [`ZkError::Response`].
fn ok_or(&mut self, command: u16, command_string: &[u8], err: &str) -> ZkResult<()> {
if self.send_command(command, command_string, 8)?.status {
Ok(())
} else {
Err(ZkError::response(err.to_string()))
}
}
// ----------------------------------------------------------------------
// Users
// ----------------------------------------------------------------------
/// Read all enrolled users.
pub fn get_users(&mut self) -> ZkResult<Vec<User>> {
self.read_sizes()?;
if self.sizes.users == 0 {
self.next_uid = 1;
self.next_user_id = "1".to_string();
return Ok(Vec::new());
}
let (userdata, size) = self.read_with_buffer(c::CMD_USERTEMP_RRQ, c::FCT_USER as i32, 0)?;
if size <= 4 {
return Ok(Vec::new());
}
let total_size = u32_le(&userdata[0..4]) as usize;
// Detect record width from the total payload.
let packet_size = total_size / self.sizes.users as usize;
if packet_size == 28 || packet_size == 72 {
self.user_packet_size = packet_size;
}
let body = &userdata[4..];
let mut users = Vec::new();
let mut max_uid: u16 = 0;
if self.user_packet_size == 28 {
let mut off = 0;
while off + 28 <= body.len() {
let rec: &[u8; 28] = body[off..off + 28].try_into().unwrap();
let user = User::parse_zk6(rec);
max_uid = max_uid.max(user.uid);
users.push(user);
off += 28;
}
} else {
let mut off = 0;
while off + 72 <= body.len() {
let rec: &[u8; 72] = body[off..off + 72].try_into().unwrap();
let user = User::parse_zk8(rec);
max_uid = max_uid.max(user.uid);
users.push(user);
off += 72;
}
}
// Compute the next free uid / user_id, skipping any already in use.
let mut max = max_uid.wrapping_add(1);
self.next_uid = max;
self.next_user_id = max.to_string();
loop {
let candidate = self.next_user_id.clone();
if users.iter().any(|u| u.user_id == candidate) {
max = max.wrapping_add(1);
self.next_user_id = max.to_string();
} else {
break;
}
}
Ok(users)
}
/// Create or update a user.
///
/// If `user.uid` is `0`, the next free uid / user-id is assigned (call
/// [`get_users`](Zk::get_users) first so the counters are populated).
pub fn set_user(&mut self, user: &User) -> ZkResult<()> {
let mut user = user.clone();
if user.uid == 0 {
user.uid = self.next_uid;
if user.user_id.is_empty() {
user.user_id = self.next_user_id.clone();
}
}
if user.user_id.is_empty() {
user.user_id = user.uid.to_string();
}
// Only DEFAULT / ADMIN privileges are valid as upload values.
if user.privilege != crate::user::USER_DEFAULT && user.privilege != crate::user::USER_ADMIN
{
user.privilege = crate::user::USER_DEFAULT;
}
let cmd = if self.user_packet_size == 28 {
// '<H B 5s 8s I x B H I'
let group = user.group_id.parse::<u8>().unwrap_or(0);
let user_id = user.user_id.parse::<u32>().unwrap_or(0);
wr(|w| {
w.u16(user.uid)
.u8(user.privilege)
.fixed(user.password.as_bytes(), 5)
.fixed(user.name.as_bytes(), 8)
.u32(user.card)
.pad(1)
.u8(group)
.u16(0)
.u32(user_id);
})
} else {
// '<H B 8s 24s 4s x 7s x 24s'
wr(|w| {
w.u16(user.uid)
.u8(user.privilege)
.fixed(user.password.as_bytes(), 8)
.fixed(user.name.as_bytes(), 24)
.bytes(&user.card.to_le_bytes()) // 4s
.pad(1)
.fixed(user.group_id.as_bytes(), 7)
.pad(1)
.fixed(user.user_id.as_bytes(), 24);
})
};
let resp = self.send_command(c::CMD_USER_WRQ, &cmd, 1024)?;
if !resp.status {
return Err(ZkError::response("can't set user"));
}
self.refresh_data()?;
if self.next_uid == user.uid {
self.next_uid = self.next_uid.wrapping_add(1);
}
if self.next_user_id == user.user_id {
self.next_user_id = self.next_uid.to_string();
}
Ok(())
}
/// Delete a user by internal `uid`. If `uid` is 0, resolves it from
/// `user_id` (which requires a [`get_users`](Zk::get_users) lookup).
pub fn delete_user(&mut self, uid: u16, user_id: &str) -> ZkResult<()> {
let uid = self.resolve_uid(uid, user_id)?;
let Some(uid) = uid else {
return Ok(()); // nothing to delete
};
let cmd = wr(|w| {
w.u16(uid);
});
let resp = self.send_command(c::CMD_DELETE_USER, &cmd, 8)?;
if !resp.status {
return Err(ZkError::response("can't delete user"));
}
self.refresh_data()?;
if uid == self.next_uid.wrapping_sub(1) {
self.next_uid = uid;
}
Ok(())
}
/// Clear ALL data on the device (users, attendance, templates).
pub fn clear_data(&mut self) -> ZkResult<()> {
let resp = self.send_command(c::CMD_CLEAR_DATA, &[], 8)?;
if resp.status {
self.next_uid = 1;
Ok(())
} else {
Err(ZkError::response("can't clear data"))
}
}
/// Resolve a `uid`: if non-zero use it, else look it up by `user_id`.
/// Returns `Ok(None)` when the user could not be found.
fn resolve_uid(&mut self, uid: u16, user_id: &str) -> ZkResult<Option<u16>> {
if uid != 0 {
return Ok(Some(uid));
}
let users = self.get_users()?;
Ok(users
.into_iter()
.find(|u| u.user_id == user_id)
.map(|u| u.uid))
}
// ----------------------------------------------------------------------
// Attendance
// ----------------------------------------------------------------------
/// Read all attendance records.
pub fn get_attendance(&mut self) -> ZkResult<Vec<Attendance>> {
self.read_sizes()?;
if self.sizes.records == 0 {
return Ok(Vec::new());
}
let users = self.get_users()?;
let (data, size) = self.read_with_buffer(c::CMD_ATTLOG_RRQ, 0, 0)?;
if size < 4 {
return Ok(Vec::new());
}
let total_size = u32_le(&data[0..4]) as usize;
let record_size = total_size / self.sizes.records.max(1) as usize;
let body = &data[4..];
let mut out = Vec::new();
// The on-wire record layout depends on firmware: 8, 16, or 40 bytes.
match record_size {
8 => {
let mut off = 0;
while off + 8 <= body.len() {
let r = &body[off..off + 8];
let uid = u16_le(&r[0..2]);
let status = r[2];
let timestamp = protocol::decode_time(u32_le(&r[3..7]));
let punch = r[7];
let user_id = users
.iter()
.find(|u| u.uid == uid)
.map(|u| u.user_id.clone())
.unwrap_or_else(|| uid.to_string());
out.push(Attendance::new(
user_id, timestamp, status, punch, uid as u32,
));
off += 8;
}
}
16 => {
let mut off = 0;
while off + 16 <= body.len() {
let r = &body[off..off + 16];
let user_id_num = u32_le(&r[0..4]);
let timestamp = protocol::decode_time(u32_le(&r[4..8]));
let status = r[8];
let punch = r[9];
// r[10..12] reserved, r[12..16] workcode
let user_id = user_id_num.to_string();
let uid = users
.iter()
.find(|u| u.user_id == user_id)
.map(|u| u.uid as u32)
.unwrap_or(user_id_num);
out.push(Attendance::new(user_id, timestamp, status, punch, uid));
off += 16;
}
}
_ => {
// 40-byte (and larger) variant.
let rec = record_size.max(40);
let mut off = 0;
// Some firmwares prefix the block with this marker.
const MARKER: &[u8] = b"\xff255\x00\x00\x00\x00\x00";
while off + 40 <= body.len() {
if body[off..].starts_with(MARKER) {
off += MARKER.len();
if off + 40 > body.len() {
break;
}
}
let r = &body[off..off + 40];
let uid = u16_le(&r[0..2]);
let user_id = decode_until_nul(&r[2..26]);
let status = r[26];
let timestamp = protocol::decode_time(u32_le(&r[27..31]));
let punch = r[31];
out.push(Attendance::new(
user_id, timestamp, status, punch, uid as u32,
));
off += rec;
}
}
}
Ok(out)
}
/// Clear all attendance records.
pub fn clear_attendance(&mut self) -> ZkResult<()> {
self.ok_or(c::CMD_CLEAR_ATTLOG, &[], "can't clear attendance")
}
// ----------------------------------------------------------------------
// Fingerprint templates
// ----------------------------------------------------------------------
/// Read all fingerprint templates.
pub fn get_templates(&mut self) -> ZkResult<Vec<Finger>> {
self.read_sizes()?;
if self.sizes.fingers == 0 {
return Ok(Vec::new());
}
let (data, size) = self.read_with_buffer(c::CMD_DB_RRQ, c::FCT_FINGERTMP as i32, 0)?;
if size < 4 {
return Ok(Vec::new());
}
let mut total_size = u32_le(&data[0..4]) as i64;
let mut body = &data[4..];
let mut out = Vec::new();
while total_size > 0 && body.len() >= 6 {
// Per-record header: size (incl. 6-byte header), uid, fid, valid.
let rec_size = u16_le(&body[0..2]) as usize;
if rec_size < 6 || rec_size > body.len() {
break;
}
let uid = u16_le(&body[2..4]);
let fid = body[4];
let valid = body[5];
let template = body[6..rec_size].to_vec();
out.push(Finger::new(uid, fid, valid, template));
body = &body[rec_size..];
total_size -= rec_size as i64;
}
Ok(out)
}
/// Fetch a single fingerprint template for `(uid, finger_id)`.
pub fn get_user_template(&mut self, uid: u16, finger_id: u8) -> ZkResult<Option<Finger>> {
for _ in 0..3 {
let cmd = wr(|w| {
w.u16(uid).u8(finger_id);
});
self.send_command(c::CMD_GET_USERTEMP, &cmd, 1024 + 8)?;
if let Some(data) = self.receive_chunk()? {
if data.is_empty() {
continue;
}
// Drop the trailing status byte, plus a 6-byte zero pad if present.
let mut resp = &data[..data.len() - 1];
if resp.len() >= 6 && resp[resp.len() - 6..] == [0u8; 6] {
resp = &resp[..resp.len() - 6];
}
return Ok(Some(Finger::new(uid, finger_id, 1, resp.to_vec())));
}
}
Ok(None)
}
/// Delete a single template. If `uid` is 0 it is resolved from `user_id`.
pub fn delete_user_template(
&mut self,
uid: u16,
finger_id: u8,
user_id: &str,
) -> ZkResult<bool> {
// TCP devices support deletion directly by user_id string.
if self.tcp && !user_id.is_empty() {
let cmd = wr(|w| {
w.fixed(user_id.as_bytes(), 24).u8(finger_id);
});
return Ok(self.send_command(c::CMD_DEL_USER_TEMP, &cmd, 8)?.status);
}
let Some(uid) = self.resolve_uid(uid, user_id)? else {
return Ok(false);
};
let cmd = wr(|w| {
w.u16(uid).u8(finger_id);
});
Ok(self.send_command(c::CMD_DELETE_USERTEMP, &cmd, 8)?.status)
}
/// Interactively enroll a fingerprint for an existing user.
///
/// This puts the device into enrollment mode; the person must press their
/// finger on the sensor (typically three times). Returns `true` if a template
/// was captured. If `user_id` is empty it is resolved from `uid`.
///
/// Note: this blocks while waiting for the person to interact with the device
/// (the read timeout is temporarily raised to 60s, matching `pyzk`).
pub fn enroll_user(&mut self, uid: u16, finger_id: u8, user_id: &str) -> ZkResult<bool> {
// Resolve the user_id string we must send.
let user_id = if user_id.is_empty() {
let users = self.get_users()?;
match users.into_iter().find(|u| u.uid == uid) {
Some(u) => u.user_id,
None => return Ok(false),
}
} else {
user_id.to_string()
};
let command_string = if self.tcp {
// '<24s b b' = user_id, finger id, flag(1)
wr(|w| {
w.fixed(user_id.as_bytes(), 24).u8(finger_id).u8(1);
})
} else {
// '<I b' = numeric user_id, finger id
wr(|w| {
w.u32(user_id.parse::<u32>().unwrap_or(0)).u8(finger_id);
})
};
self.cancel_capture()?;
let resp = self.send_command(c::CMD_STARTENROLL, &command_string, 8)?;
if !resp.status {
return Err(ZkError::response(format!(
"can't enroll user #{uid} [{finger_id}]"
)));
}
// Wait (longer) for the multi-press enrollment handshake.
if let Some(sock) = self.transport.as_ref() {
sock.set_read_timeout(Some(Duration::from_secs(60)))?;
}
// The reply offset of the status word differs between transports.
let res_off = if self.tcp { 16 } else { 8 };
let pad_to = if self.tcp { 24 } else { 16 };
let mut done = false;
let mut attempts = 3;
while attempts > 0 {
// First event of the press cycle.
let recv = self.recv_event(1032)?;
self.ack_ok()?;
let res = u16_at_padded(&recv, res_off, pad_to);
// res 4/6 = timeout/failure on either transport; on TCP res 0 also
// ends the first phase.
if res == 6 || res == 4 || (self.tcp && res == 0) {
break;
}
// Second event.
let recv = self.recv_event(1032)?;
self.ack_ok()?;
let res = u16_at_padded(&recv, res_off, pad_to);
if res == 6 || res == 4 {
break;
} else if res == 0x64 {
attempts -= 1;
}
}
if attempts == 0 {
let recv = self.recv_event(1032)?;
self.ack_ok()?;
let res = u16_at_padded(&recv, res_off, pad_to);
match res {
5 => self.log("finger duplicate"),
6 | 4 => self.log("possible timeout"),
0 => {
self.log("enroll ok");
done = true;
}
_ => {}
}
}
// Restore normal state.
if let Some(sock) = self.transport.as_ref() {
sock.set_read_timeout(Some(self.timeout))?;
}
self.reg_event(0)?;
self.cancel_capture()?;
self.verify_user()?;
Ok(done)
}
/// Receive one real-time event packet (single read), used during enrollment.
fn recv_event(&mut self, max: usize) -> ZkResult<Vec<u8>> {
let sock = self.transport.as_mut().ok_or(ZkError::NotConnected)?;
Ok(sock.recv(max)?)
}
/// Save a user together with their fingerprint templates (high-rate upload).
pub fn save_user_template(&mut self, user: &User, fingers: &[Finger]) -> ZkResult<()> {
self.save_user_templates(&[(user.clone(), fingers.to_vec())])
}
/// Save multiple users and their templates in a single buffered upload.
///
/// (`pyzk`'s `HR_save_usertemplates`.)
pub fn save_user_templates(&mut self, items: &[(User, Vec<Finger>)]) -> ZkResult<()> {
let mut upack = Vec::new();
let mut fpack = Vec::new();
let mut table = Vec::new();
const FNUM: u8 = 0x10;
let mut tstart: u32 = 0;
for (user, fingers) in items {
if self.user_packet_size == 28 {
upack.extend_from_slice(&user.repack29());
} else {
upack.extend_from_slice(&user.repack73());
}
for finger in fingers {
let tfp = finger.repack_only();
// Table entry: '<b H b I' = tag(2), uid, FNUM+fid, offset.
table.extend_from_slice(&wr(|w| {
w.u8(2).u16(user.uid).u8(FNUM + finger.fid).u32(tstart);
}));
tstart += tfp.len() as u32;
fpack.extend_from_slice(&tfp);
}
}
let head = wr(|w| {
w.u32(upack.len() as u32)
.u32(table.len() as u32)
.u32(fpack.len() as u32);
});
let mut packet = head;
packet.extend_from_slice(&upack);
packet.extend_from_slice(&table);
packet.extend_from_slice(&fpack);
self.send_with_buffer(&packet)?;
let cmd = wr(|w| {
w.u32(12).u16(0).u16(8);
});
let resp = self.send_command(c::CMD_SAVE_USERTEMPS, &cmd, 8)?;
if !resp.status {
return Err(ZkError::response("can't save usertemplates"));
}
self.refresh_data()
}
/// Stream a buffer to the device in ≤1024-byte chunks (prepare + data).
fn send_with_buffer(&mut self, buffer: &[u8]) -> ZkResult<()> {
const MAX_CHUNK: usize = 1024;
self.free_data()?;
let prep = wr(|w| {
w.u32(buffer.len() as u32);
});
let resp = self.send_command(c::CMD_PREPARE_DATA, &prep, 8)?;
if !resp.status {
return Err(ZkError::response("can't prepare data"));
}
let mut start = 0;
while start < buffer.len() {
let end = (start + MAX_CHUNK).min(buffer.len());
let resp = self.send_command(c::CMD_DATA, &buffer[start..end], 8)?;
if !resp.status {
return Err(ZkError::response("can't send chunk"));
}
start = end;
}
Ok(())
}
// ----------------------------------------------------------------------
// Buffered (chunked) reads — the intricate part of the protocol
// ----------------------------------------------------------------------
/// Read a dataset using the buffered protocol (`CMD_PREPARE_BUFFER` /
/// `CMD_READ_BUFFER`). Returns the assembled bytes and their length.
fn read_with_buffer(&mut self, command: u16, fct: i32, ext: i32) -> ZkResult<(Vec<u8>, usize)> {
// TCP can request larger chunks than UDP.
let max_chunk: usize = if self.tcp { 0xFFC0 } else { 16 * 1024 };
let command_string = wr(|w| {
w.u8(1).u16(command).u32(fct as u32).u32(ext as u32);
});
let resp = self.send_command(c::CMD_PREPARE_BUFFER, &command_string, 1024)?;
if !resp.status {
return Err(ZkError::NotSupported("buffered read".into()));
}
// Small datasets arrive inline as a single DATA reply.
if resp.code == c::CMD_DATA {
if self.tcp {
let have = self.last_data.len();
let want = (self.tcp_length as usize).saturating_sub(8);
if have < want {
let need = want - have;
let more = self.receive_raw_data(need)?;
let mut all = self.last_data.clone();
all.extend_from_slice(&more);
let len = all.len();
return Ok((all, len));
} else {
let all = self.last_data.clone();
let len = all.len();
return Ok((all, len));
}
} else {
let all = self.last_data.clone();
let len = all.len();
return Ok((all, len));
}
}
// Otherwise PREPARE_DATA announced a total size at offset 1.
if self.last_data.len() < 5 {
return Err(ZkError::Parse("short prepare-buffer reply".into()));
}
let size = u32_le(&self.last_data[1..5]) as usize;
let remain = size % max_chunk;
let packets = (size - remain) / max_chunk;
let mut data = Vec::with_capacity(size);
let mut start = 0usize;
for _ in 0..packets {
let chunk = self.read_chunk(start, max_chunk)?;
data.extend_from_slice(&chunk);
start += max_chunk;
}
if remain > 0 {
let chunk = self.read_chunk(start, remain)?;
data.extend_from_slice(&chunk);
start += remain;
}
self.free_data()?;
Ok((data, start))
}
/// Read one chunk `[start, start+size)` from the prepared buffer, retrying.
fn read_chunk(&mut self, start: usize, size: usize) -> ZkResult<Vec<u8>> {
let command_string = wr(|w| {
w.u32(start as u32).u32(size as u32);
});
let response_size = if self.tcp { size + 32 } else { 1024 + 8 };
for _ in 0..3 {
self.send_command(c::CMD_READ_BUFFER, &command_string, response_size)?;
if let Some(chunk) = self.receive_chunk()? {
return Ok(chunk);
}
}
Err(ZkError::response(format!(
"can't read chunk {start}:[{size}]"
)))
}
/// Read exactly `size` bytes from the socket (loops until satisfied).
fn receive_raw_data(&mut self, mut size: usize) -> ZkResult<Vec<u8>> {
let sock = self.transport.as_mut().ok_or(ZkError::NotConnected)?;
let mut out = Vec::with_capacity(size);
while size > 0 {
let part = sock.recv(size)?;
if part.is_empty() {
break; // connection closed
}
size = size.saturating_sub(part.len());
out.extend_from_slice(&part);
}
Ok(out)
}
/// Receive one logical chunk following a DATA / PREPARE_DATA reply.
///
/// Returns `Ok(None)` on an unexpected/broken response (the caller retries).
fn receive_chunk(&mut self) -> ZkResult<Option<Vec<u8>>> {
match self.last_response {
c::CMD_DATA => {
// The DATA payload may be complete already, or need topping up to
// the declared TCP length.
if self.tcp {
let have = self.last_data.len();
let want = (self.tcp_length as usize).saturating_sub(8);
if have < want {
let more = self.receive_raw_data(want - have)?;
let mut all = self.last_data.clone();
all.extend_from_slice(&more);
Ok(Some(all))
} else {
Ok(Some(self.last_data.clone()))
}
} else {
Ok(Some(self.last_data.clone()))
}
}
c::CMD_PREPARE_DATA => {
let size = self.get_data_size();
if self.tcp {
self.receive_chunk_tcp(size)
} else {
self.receive_chunk_udp(size as i64)
}
}
other => {
self.log(format!("invalid response {other}"));
Ok(None)
}
}
}
/// UDP variant: read DATA packets until the closing ACK_OK.
fn receive_chunk_udp(&mut self, mut size: i64) -> ZkResult<Option<Vec<u8>>> {
let sock = self.transport.as_mut().ok_or(ZkError::NotConnected)?;
let mut data = Vec::new();
loop {
let recv = sock.recv(1024 + 8)?;
if recv.len() < 8 {
break;
}
let response = u16_le(&recv[0..2]);
if response == c::CMD_DATA {
data.extend_from_slice(&recv[8..]);
size -= 1024;
} else if response == c::CMD_ACK_OK {
break;
} else {
self.log("broken udp chunk");
break;
}
if size <= 0 {
// keep draining until ACK as pyzk does; guard against runaway
}
}
Ok(Some(data))
}
/// TCP variant: gather `size` bytes of DATA, then confirm the trailing
/// ACK_OK. Mirrors `pyzk`'s `__recieve_chunk` prepare-data branch.
fn receive_chunk_tcp(&mut self, size: usize) -> ZkResult<Option<Vec<u8>>> {
// Start from whatever followed the PREPARE_DATA reply (after its 8-byte
// size header), topping up from the socket if needed.
let mut data_recv = self.last_data[8.min(self.last_data.len())..].to_vec();
if data_recv.len() < size {
let more = self.receive_raw_data(size + 32 - data_recv.len().min(size + 32))?;
data_recv.extend_from_slice(&more);
}
let (resp, mut broken_header) = self.receive_tcp_data(data_recv, size as i64)?;
// The device then sends a framed CMD_ACK_OK we must consume.
if broken_header.len() < 16 {
let need = 16 - broken_header.len();
let more = self.receive_raw_data(need)?;
broken_header.extend_from_slice(&more);
}
if protocol::test_tcp_top(&broken_header) == 0 {
self.log("invalid chunk tcp ACK OK");
return Ok(None);
}
if broken_header.len() >= 16 {
let response = u16_le(&broken_header[8..10]);
if response == c::CMD_ACK_OK {
return Ok(Some(resp));
}
}
Ok(None)
}
/// Recursively reassemble a TCP DATA payload of `size` bytes, returning the
/// data plus any trailing "broken header" bytes belonging to the next packet.
///
/// Faithful port of `pyzk`'s `__recieve_tcp_data`.
fn receive_tcp_data(
&mut self,
mut data_recv: Vec<u8>,
mut size: i64,
) -> ZkResult<(Vec<u8>, Vec<u8>)> {
let mut data = Vec::new();
let tcp_length = protocol::test_tcp_top(&data_recv) as i64;
if tcp_length <= 0 {
return Ok((Vec::new(), Vec::new()));
}
// This framed packet carries fewer bytes than we still need: take what it
// has, then recurse to fetch the remainder in a fresh frame.
if (tcp_length - 8) < size {
let (resp, bh) = self.receive_tcp_data(data_recv.clone(), tcp_length - 8)?;
let got = resp.len() as i64;
data.extend_from_slice(&resp);
size -= got;
let mut next = bh;
let more = self.receive_raw_data((size + 16).max(0) as usize)?;
next.extend_from_slice(&more);
let (resp2, bh2) = self.receive_tcp_data(next, size)?;
data.extend_from_slice(&resp2);
return Ok((data, bh2));
}
let received = data_recv.len() as i64;
if received < 16 {
return Ok((Vec::new(), Vec::new()));
}
let response = u16_le(&data_recv[8..10]);
if received >= size + 32 {
// The whole payload (and the next packet's header) is already here.
if response == c::CMD_DATA {
let end = (size + 16) as usize;
let resp = data_recv[16..end].to_vec();
let rest = data_recv[end..].to_vec();
return Ok((resp, rest));
}
return Ok((Vec::new(), Vec::new()));
}
// Partial: take the data present, fetch the rest raw.
let avail_end = (size + 16).min(received) as usize;
data.extend_from_slice(&data_recv[16..avail_end]);
size -= received - 16;
let mut broken_header = Vec::new();
if size < 0 {
// We over-read into the next packet's header; keep those bytes.
let keep = (-size) as usize;
let len = data_recv.len();
broken_header = data_recv.split_off(len - keep);
}
if size > 0 {
let more = self.receive_raw_data(size as usize)?;
data.extend_from_slice(&more);
}
Ok((data, broken_header))
}
// ----------------------------------------------------------------------
// Live capture
// ----------------------------------------------------------------------
/// Start capturing attendance punches in real time.
///
/// Returns a [`LiveCapture`] iterator. Each `next()` yields:
/// - `Some(Ok(Some(att)))` — a punch,
/// - `Some(Ok(None))` — a timeout "tick" (lets you poll the stop flag),
/// - `Some(Err(_))` — a fatal error,
/// - `None` — the capture was stopped.
///
/// `poll_timeout` controls how often a tick is produced.
pub fn live_capture(&mut self, poll_timeout: Duration) -> ZkResult<LiveCapture<'_>> {
let users = self.get_users()?;
self.cancel_capture()?;
self.verify_user()?;
let was_enabled = self.is_enabled;
if !self.is_enabled {
self.enable_device()?;
}
self.reg_event(c::EF_ATTLOG)?;
if let Some(sock) = self.transport.as_ref() {
sock.set_read_timeout(Some(poll_timeout))?;
}
Ok(LiveCapture {
zk: self,
users,
pending: VecDeque::new(),
stop: Arc::new(AtomicBool::new(false)),
was_enabled,
finished: false,
})
}
}
impl std::fmt::Display for Zk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = self.sizes;
write!(
f,
"ZK {}://{}:{} users[{}]:{}/{} fingers:{}/{} records:{}/{} faces:{}/{}",
if self.tcp { "tcp" } else { "udp" },
self.ip,
self.port,
self.user_packet_size,
s.users,
s.users_cap,
s.fingers,
s.fingers_cap,
s.records,
s.rec_cap,
s.faces,
s.faces_cap
)
}
}
/// Real-time attendance capture session (see [`Zk::live_capture`]).
///
/// Implements [`Iterator`]; dropping it restores the socket timeout, unregisters
/// events, and re-disables the device if it was disabled before capture.
pub struct LiveCapture<'a> {
zk: &'a mut Zk,
users: Vec<User>,
pending: VecDeque<Attendance>,
stop: Arc<AtomicBool>,
was_enabled: bool,
finished: bool,
}
impl LiveCapture<'_> {
/// A shared flag that, when set to `true`, ends the capture on the next tick.
/// Clone it and move it to another thread to stop capture from outside.
pub fn stop_handle(&self) -> Arc<AtomicBool> {
Arc::clone(&self.stop)
}
/// Request that the capture stop.
pub fn stop(&self) {
self.stop.store(true, Ordering::SeqCst);
}
/// Parse all events in one real-time packet into the pending queue.
fn parse_events(&mut self, mut data: &[u8]) {
// Each event is one of several fixed widths; the user-id field may be a
// numeric id or a fixed 24-byte string depending on firmware.
while data.len() >= 10 {
let (user_id, status, punch, timehex, consumed): (String, u8, u8, [u8; 6], usize) =
match data.len() {
10 => (
u16_le(&data[0..2]).to_string(),
data[2],
data[3],
copy6(&data[4..10]),
10,
),
12 => (
u32_le(&data[0..4]).to_string(),
data[4],
data[5],
copy6(&data[6..12]),
12,
),
14 => (
u16_le(&data[0..2]).to_string(),
data[2],
data[3],
copy6(&data[4..10]),
14,
),
32 => (
decode_until_nul(&data[0..24]),
data[24],
data[25],
copy6(&data[26..32]),
32,
),
36 => (
decode_until_nul(&data[0..24]),
data[24],
data[25],
copy6(&data[26..32]),
36,
),
37 => (
decode_until_nul(&data[0..24]),
data[24],
data[25],
copy6(&data[26..32]),
37,
),
_ => (
// 52+ bytes
decode_until_nul(&data[0..24]),
data[24],
data[25],
copy6(&data[26..32]),
52,
),
};
data = &data[consumed.min(data.len())..];
let timestamp = protocol::decode_timehex(&timehex);
let uid = self
.users
.iter()
.find(|u| u.user_id == user_id)
.map(|u| u.uid as u32)
.unwrap_or_else(|| user_id.parse::<u32>().unwrap_or(0));
self.pending
.push_back(Attendance::new(user_id, timestamp, status, punch, uid));
}
}
}
impl Iterator for LiveCapture<'_> {
type Item = ZkResult<Option<Attendance>>;
fn next(&mut self) -> Option<Self::Item> {
if self.finished || self.stop.load(Ordering::SeqCst) {
self.finished = true;
return None;
}
// Drain already-parsed events first.
if let Some(att) = self.pending.pop_front() {
return Some(Ok(Some(att)));
}
// Otherwise read one real-time packet.
let recv = {
let sock = match self.zk.transport.as_mut() {
Some(s) => s,
None => {
self.finished = true;
return Some(Err(ZkError::NotConnected));
}
};
sock.recv(1032)
};
match recv {
Ok(packet) => {
if let Err(e) = self.zk.ack_ok() {
return Some(Err(e));
}
// Split off framing depending on transport.
let (header_cmd, payload): (u16, &[u8]) = if self.zk.tcp {
if packet.len() < 16 {
return Some(Ok(None));
}
(u16_le(&packet[8..10]), &packet[16..])
} else {
if packet.len() < 8 {
return Some(Ok(None));
}
(u16_le(&packet[0..2]), &packet[8..])
};
if header_cmd != c::CMD_REG_EVENT || payload.is_empty() {
// Not an attendance event — emit a tick.
return Some(Ok(None));
}
let payload = payload.to_vec();
self.parse_events(&payload);
match self.pending.pop_front() {
Some(att) => Some(Ok(Some(att))),
None => Some(Ok(None)),
}
}
Err(e) if is_timeout(&e) => Some(Ok(None)), // tick
Err(e) => Some(Err(ZkError::Network(e))),
}
}
}
impl Drop for LiveCapture<'_> {
fn drop(&mut self) {
// Best-effort cleanup, mirroring pyzk's finally block. Errors are ignored
// because Drop cannot return them.
if let Some(sock) = self.zk.transport.as_ref() {
let _ = sock.set_read_timeout(Some(self.zk.timeout));
}
let _ = self.zk.reg_event(0);
if !self.was_enabled {
let _ = self.zk.disable_device();
}
}
}
/// Parse the 4-element `<4H>` command header.
fn read_header(b: &[u8]) -> [u16; 4] {
[
u16_le(&b[0..2]),
u16_le(&b[2..4]),
u16_le(&b[4..6]),
u16_le(&b[6..8]),
]
}
/// Decode bytes up to the first NUL as a UTF-8 (lossy) string.
fn decode_until_nul(b: &[u8]) -> String {
let end = b.iter().position(|&x| x == 0).unwrap_or(b.len());
String::from_utf8_lossy(&b[..end]).into_owned()
}
/// Decode a device option value: the text after the first `=`, up to NUL.
fn decode_option_value(b: &[u8]) -> String {
// Find first '=' and take the remainder up to NUL.
let after_eq = match b.iter().position(|&x| x == b'=') {
Some(i) => &b[i + 1..],
None => b,
};
decode_until_nul(after_eq)
}
/// Read a little-endian `u16` at `offset`, treating the buffer as if it were
/// zero-padded to at least `pad_to` bytes (mirrors `pyzk`'s `ljust` reads of
/// enrollment status words from short packets).
fn u16_at_padded(buf: &[u8], offset: usize, pad_to: usize) -> u16 {
let mut padded = buf.to_vec();
if padded.len() < pad_to {
padded.resize(pad_to, 0);
}
if offset + 2 <= padded.len() {
u16_le(&padded[offset..offset + 2])
} else {
0
}
}
/// Copy a 6-byte time-hex field into a fixed array.
fn copy6(b: &[u8]) -> [u8; 6] {
let mut out = [0u8; 6];
out.copy_from_slice(&b[0..6]);
out
}
/// `true` if an I/O error represents a socket read timeout.
fn is_timeout(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
)
}