zklib-ts 1.0.0-development

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,2694 @@
1
+ import { Socket } from 'net';
2
+ import { appendFile } from 'fs';
3
+ import * as dgram from 'node:dgram';
4
+
5
+ const COMMANDS = {
6
+ CMD_CONNECT: 1000,
7
+ CMD_EXIT: 1001,
8
+ CMD_ENABLEDEVICE: 1002,
9
+ CMD_DISABLEDEVICE: 1003,
10
+ CMD_RESTART: 1004,
11
+ CMD_POWEROFF: 1005,
12
+ CMD_SLEEP: 1006,
13
+ CMD_RESUME: 1007,
14
+ CMD_CAPTUREFINGER: 1009,
15
+ CMD_TEST_TEMP: 1011,
16
+ CMD_CAPTUREIMAGE: 1012,
17
+ CMD_REFRESHDATA: 1013,
18
+ CMD_REFRESHOPTION: 1014,
19
+ CMD_TESTVOICE: 1017,
20
+ CMD_GET_VERSION: 1100,
21
+ CMD_CHANGE_SPEED: 1101,
22
+ CMD_AUTH: 1102,
23
+ CMD_PREPARE_DATA: 1500,
24
+ CMD_DATA: 1501,
25
+ CMD_FREE_DATA: 1502,
26
+ CMD_DATA_WRRQ: 1503,
27
+ CMD_DATA_RDY: 1504,
28
+ CMD_DB_RRQ: 7,
29
+ CMD_USER_WRQ: 8,
30
+ CMD_USERTEMP_RRQ: 9,
31
+ CMD_USERTEMP_WRQ: 10,
32
+ CMD_OPTIONS_RRQ: 11,
33
+ CMD_OPTIONS_WRQ: 12,
34
+ CMD_ATTLOG_RRQ: 13,
35
+ CMD_CLEAR_DATA: 14,
36
+ CMD_CLEAR_ATTLOG: 15,
37
+ CMD_DELETE_USER: 18,
38
+ CMD_DELETE_USERTEMP: 19,
39
+ CMD_CLEAR_ADMIN: 20,
40
+ CMD_USERGRP_RRQ: 21,
41
+ CMD_USERGRP_WRQ: 22,
42
+ CMD_USERTZ_RRQ: 23,
43
+ CMD_USERTZ_WRQ: 24,
44
+ CMD_GRPTZ_RRQ: 25,
45
+ CMD_GRPTZ_WRQ: 26,
46
+ CMD_TZ_RRQ: 27,
47
+ CMD_TZ_WRQ: 28,
48
+ CMD_ULG_RRQ: 29,
49
+ CMD_ULG_WRQ: 30,
50
+ CMD_UNLOCK: 31,
51
+ CMD_CLEAR_ACC: 32,
52
+ CMD_CLEAR_OPLOG: 33,
53
+ CMD_OPLOG_RRQ: 34,
54
+ CMD_GET_FREE_SIZES: 50,
55
+ CMD_ENABLE_CLOCK: 57,
56
+ CMD_STARTVERIFY: 60,
57
+ CMD_STARTENROLL: 61,
58
+ CMD_CANCELCAPTURE: 62,
59
+ CMD_STATE_RRQ: 64,
60
+ CMD_WRITE_LCD: 66,
61
+ CMD_CLEAR_LCD: 67,
62
+ CMD_GET_PINWIDTH: 69,
63
+ CMD_SMS_WRQ: 70,
64
+ CMD_SMS_RRQ: 71,
65
+ CMD_DELETE_SMS: 72,
66
+ CMD_UDATA_WRQ: 73,
67
+ CMD_DELETE_UDATA: 74,
68
+ CMD_DOORSTATE_RRQ: 75,
69
+ CMD_WRITE_MIFARE: 76,
70
+ CMD_EMPTY_MIFARE: 78,
71
+ CMD_VERIFY_WRQ: 79,
72
+ CMD_VERIFY_RRQ: 80,
73
+ CMD_TMP_WRITE: 87,
74
+ CMD_GET_USERTEMP: 88,
75
+ CMD_CHECKSUM_BUFFER: 119,
76
+ CMD_DEL_FPTMP: 134,
77
+ CMD_GET_TIME: 201,
78
+ CMD_SET_TIME: 202,
79
+ CMD_REG_EVENT: 500,
80
+ CMD_ACK_OK: 2000,
81
+ CMD_ACK_ERROR: 2001,
82
+ CMD_ACK_DATA: 2002,
83
+ CMD_ACK_RETRY: 2003,
84
+ CMD_ACK_REPEAT: 2004,
85
+ CMD_ACK_UNAUTH: 2005,
86
+ CMD_ACK_UNKNOWN: 65535,
87
+ CMD_ACK_ERROR_CMD: 65533,
88
+ CMD_ACK_ERROR_INIT: 65532,
89
+ CMD_ACK_ERROR_DATA: 65531,
90
+ EF_ATTLOG: 1,
91
+ EF_FINGER: 2,
92
+ EF_ENROLLUSER: 4,
93
+ EF_ENROLLFINGER: 8,
94
+ EF_BUTTON: 16,
95
+ EF_UNLOCK: 32,
96
+ EF_VERIFY: 128,
97
+ EF_FPFTR: 256,
98
+ EF_ALARM: 512
99
+ };
100
+ const USHRT_MAX = 65535;
101
+ const MAX_CHUNK = 65472;
102
+ const REQUEST_DATA = {
103
+ DISABLE_DEVICE: Buffer.from([0, 0, 0, 0]),
104
+ GET_REAL_TIME_EVENT: Buffer.from([0x01, 0x00, 0x00, 0x00]),
105
+ GET_ATTENDANCE_LOGS: Buffer.from([0x01, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
106
+ GET_USERS: Buffer.from([0x01, 0x09, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
107
+ GET_TEMPLATES: Buffer.from([0x01, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
108
+ };
109
+
110
+ /**
111
+ *
112
+ * @param {number} time
113
+ */
114
+ const decode = time => {
115
+ const second = time % 60;
116
+ time = (time - second) / 60;
117
+ const minute = time % 60;
118
+ time = (time - minute) / 60;
119
+ const hour = time % 24;
120
+ time = (time - hour) / 24;
121
+ const day = time % 31 + 1;
122
+ time = (time - (day - 1)) / 31;
123
+ const month = time % 12;
124
+ time = (time - month) / 12;
125
+ const year = time + 2000;
126
+ return new Date(year, month, day, hour, minute, second);
127
+ };
128
+ /**
129
+ *
130
+ * @param {Date} date
131
+ */
132
+ const encode = date => {
133
+ return (((date.getFullYear() % 100) * 12 * 31 + date.getMonth() * 31 + date.getDate() - 1) * (24 * 60 * 60) +
134
+ (date.getHours() * 60 + date.getMinutes()) * 60 +
135
+ date.getSeconds());
136
+ };
137
+ var timeParser = { encode, decode };
138
+
139
+ const parseCurrentTime = () => {
140
+ const currentTime = new Date();
141
+ return {
142
+ year: currentTime.getFullYear(),
143
+ month: currentTime.getMonth() + 1,
144
+ day: currentTime.getDate(),
145
+ hour: currentTime.getHours(),
146
+ second: currentTime.getSeconds()
147
+ };
148
+ };
149
+ const log = (text) => {
150
+ const currentTime = parseCurrentTime();
151
+ const fileName = `${currentTime.day}`.padStart(2, '0') +
152
+ `${currentTime.month}`.padStart(2, '0') +
153
+ `${currentTime.year}.err.log`;
154
+ const logMessage = `\n [${currentTime.hour}:${currentTime.second}] ${text}`;
155
+ appendFile(fileName, logMessage, () => { });
156
+ };
157
+
158
+ /**
159
+ * Represents a User as is from ZkDevice and contain methods
160
+ * */
161
+ class User {
162
+ uid;
163
+ name;
164
+ privilege;
165
+ password;
166
+ group_id;
167
+ user_id;
168
+ card;
169
+ /**
170
+ * Creates a new User instance
171
+ * @param uid User ID
172
+ * @param name User name
173
+ * @param privilege Privilege level
174
+ * @param password User password (default: "")
175
+ * @param group_id Group ID (default: "")
176
+ * @param user_id Alternate user ID (default: "")
177
+ * @param card Card number (default: 0)
178
+ */
179
+ constructor(uid, name, privilege, password = "", group_id = "", user_id = "", card = 0) {
180
+ this.uid = uid;
181
+ this.name = name;
182
+ this.privilege = privilege;
183
+ this.password = password;
184
+ this.group_id = group_id;
185
+ this.user_id = user_id;
186
+ this.card = card;
187
+ }
188
+ ensureEncoding(string) {
189
+ try {
190
+ return decodeURIComponent(string);
191
+ }
192
+ catch (e) {
193
+ return unescape(string);
194
+ }
195
+ }
196
+ repack29() {
197
+ // Pack format: <BHB5s8sIxBhI (total 29 bytes)
198
+ const buf = Buffer.alloc(29);
199
+ let offset = 0;
200
+ buf.writeUInt8(2, offset);
201
+ offset += 1;
202
+ buf.writeUInt16LE(this.uid, offset);
203
+ offset += 2;
204
+ buf.writeUInt8(this.privilege, offset);
205
+ offset += 1;
206
+ const passwordBuf = Buffer.from(this.ensureEncoding(this.password));
207
+ passwordBuf.copy(buf, offset, 0, 5);
208
+ offset += 5;
209
+ const nameBuf = Buffer.from(this.ensureEncoding(this.name));
210
+ nameBuf.copy(buf, offset, 0, 8);
211
+ offset += 8;
212
+ buf.writeUInt32LE(this.card, offset);
213
+ offset += 4;
214
+ offset += 1; // padding byte
215
+ buf.writeUInt8(0, offset);
216
+ offset += 1;
217
+ buf.writeUInt32LE(parseInt(this.user_id) || 0, offset);
218
+ return buf;
219
+ }
220
+ repack73() {
221
+ // Pack format: <BHB8s24sIB7sx24s (total 73 bytes)
222
+ const buf = Buffer.alloc(73);
223
+ let offset = 0;
224
+ buf.writeUInt8(2, offset);
225
+ offset += 1;
226
+ buf.writeUInt16LE(this.uid, offset);
227
+ offset += 2;
228
+ buf.writeUInt8(this.privilege, offset);
229
+ offset += 1;
230
+ const passwordBuf = Buffer.from(this.ensureEncoding(this.password));
231
+ passwordBuf.copy(buf, offset, 0, 8);
232
+ offset += 8;
233
+ const nameBuf = Buffer.from(this.ensureEncoding(this.name));
234
+ nameBuf.copy(buf, offset, 0, 24);
235
+ offset += 24;
236
+ buf.writeUInt32LE(this.card, offset);
237
+ offset += 4;
238
+ buf.writeUInt8(1, offset);
239
+ offset += 1;
240
+ const groupBuf = Buffer.from(this.ensureEncoding(String(this.group_id)));
241
+ groupBuf.copy(buf, offset, 0, 7);
242
+ offset += 8;
243
+ const userIdBuf = Buffer.from(this.ensureEncoding(String(this.user_id)));
244
+ userIdBuf.copy(buf, offset, 0, 24);
245
+ return buf;
246
+ }
247
+ }
248
+
249
+ class Attendance {
250
+ sn;
251
+ user_id;
252
+ record_time;
253
+ type;
254
+ state;
255
+ _ip;
256
+ constructor(sn, user_id, record_time, type, state) {
257
+ this.sn = sn;
258
+ this.user_id = user_id;
259
+ this.record_time = record_time;
260
+ this.type = type;
261
+ this.state = state;
262
+ }
263
+ set ip(value) {
264
+ this._ip = value;
265
+ }
266
+ }
267
+
268
+ const parseHexToTime = (hex) => {
269
+ const time = {
270
+ year: hex.readUIntLE(0, 1),
271
+ month: hex.readUIntLE(1, 1),
272
+ date: hex.readUIntLE(2, 1),
273
+ hour: hex.readUIntLE(3, 1),
274
+ minute: hex.readUIntLE(4, 1),
275
+ second: hex.readUIntLE(5, 1)
276
+ };
277
+ return new Date(2000 + time.year, time.month - 1, time.date, time.hour, time.minute, time.second);
278
+ };
279
+ const createChkSum = (buf) => {
280
+ let chksum = 0;
281
+ for (let i = 0; i < buf.length; i += 2) {
282
+ if (i === buf.length - 1) {
283
+ chksum += buf[i];
284
+ }
285
+ else {
286
+ chksum += buf.readUInt16LE(i);
287
+ }
288
+ chksum %= USHRT_MAX;
289
+ }
290
+ chksum = USHRT_MAX - chksum - 1;
291
+ return chksum;
292
+ };
293
+ const createUDPHeader = (command, sessionId, replyId, data) => {
294
+ const dataBuffer = Buffer.from(data);
295
+ const buf = Buffer.alloc(8 + dataBuffer.length);
296
+ buf.writeUInt16LE(command, 0);
297
+ buf.writeUInt16LE(0, 2);
298
+ buf.writeUInt16LE(sessionId, 4);
299
+ buf.writeUInt16LE(replyId, 6);
300
+ dataBuffer.copy(buf, 8);
301
+ const chksum2 = createChkSum(buf);
302
+ buf.writeUInt16LE(chksum2, 2);
303
+ replyId = (replyId + 1) % USHRT_MAX;
304
+ buf.writeUInt16LE(replyId, 6);
305
+ return buf;
306
+ };
307
+ const createTCPHeader = (command, sessionId, replyId, data) => {
308
+ const dataBuffer = Buffer.from(data);
309
+ const buf = Buffer.alloc(8 + dataBuffer.length);
310
+ buf.writeUInt16LE(command, 0);
311
+ buf.writeUInt16LE(0, 2);
312
+ buf.writeUInt16LE(sessionId, 4);
313
+ buf.writeUInt16LE(replyId, 6);
314
+ dataBuffer.copy(buf, 8);
315
+ const chksum2 = createChkSum(buf);
316
+ buf.writeUInt16LE(chksum2, 2);
317
+ replyId = (replyId + 1) % USHRT_MAX;
318
+ buf.writeUInt16LE(replyId, 6);
319
+ const prefixBuf = Buffer.from([0x50, 0x50, 0x82, 0x7d, 0x13, 0x00, 0x00, 0x00]);
320
+ prefixBuf.writeUInt16LE(buf.length, 4);
321
+ return Buffer.concat([prefixBuf, buf]);
322
+ };
323
+ const removeTcpHeader = (buf) => {
324
+ if (buf.length < 8) {
325
+ return buf;
326
+ }
327
+ if (buf.compare(Buffer.from([0x50, 0x50, 0x82, 0x7d]), 0, 4, 0, 4) !== 0) {
328
+ return buf;
329
+ }
330
+ return buf.slice(8);
331
+ };
332
+ const parseTimeToDate = (time) => {
333
+ const second = time % 60;
334
+ time = (time - second) / 60;
335
+ const minute = time % 60;
336
+ time = (time - minute) / 60;
337
+ const hour = time % 24;
338
+ time = (time - hour) / 24;
339
+ const day = time % 31 + 1;
340
+ time = (time - (day - 1)) / 31;
341
+ const month = time % 12;
342
+ time = (time - month) / 12;
343
+ const year = time + 2000;
344
+ return new Date(year, month, day, hour, minute, second);
345
+ };
346
+ const decodeUserData28 = (userData) => {
347
+ return {
348
+ uid: userData.readUIntLE(0, 2),
349
+ privilege: userData.readUIntLE(2, 1),
350
+ name: userData
351
+ .slice(8, 8 + 8)
352
+ .toString('ascii')
353
+ .split('\0')
354
+ .shift() || '',
355
+ user_id: userData.readUIntLE(24, 4).toString(),
356
+ };
357
+ };
358
+ const decodeUserData72 = (userData) => {
359
+ return new User(userData.readUIntLE(0, 2), userData
360
+ .slice(11)
361
+ .toString('ascii')
362
+ .split('\0')
363
+ .shift() || '', userData.readUIntLE(2, 1), userData
364
+ .subarray(3, 3 + 8)
365
+ .toString('ascii')
366
+ .split('\0')
367
+ .shift() || '', userData.readUIntLE(39, 1), userData
368
+ .slice(48, 48 + 9)
369
+ .toString('ascii')
370
+ .split('\0')
371
+ .shift() || '', userData.readUIntLE(35, 4));
372
+ };
373
+ const decodeRecordData40 = (recordData) => {
374
+ return new Attendance(recordData.readUIntLE(0, 2), recordData
375
+ .slice(2, 2 + 9)
376
+ .toString('ascii')
377
+ .split('\0')
378
+ .shift() || '', parseTimeToDate(recordData.readUInt32LE(27)), recordData.readUIntLE(26, 1), recordData.readUIntLE(31, 1));
379
+ };
380
+ const decodeRecordData16 = (recordData) => {
381
+ return {
382
+ user_id: recordData.readUIntLE(0, 2).toString(),
383
+ record_time: parseTimeToDate(recordData.readUInt32LE(4))
384
+ };
385
+ };
386
+ const decodeRecordRealTimeLog18 = (recordData) => {
387
+ const user_id = recordData.readUIntLE(8, 1).toString();
388
+ const record_time = parseHexToTime(recordData.subarray(12, 18));
389
+ return { user_id, record_time };
390
+ };
391
+ const decodeRecordRealTimeLog52 = (recordData) => {
392
+ const payload = removeTcpHeader(recordData);
393
+ const recvData = payload.subarray(8);
394
+ const user_id = recvData.slice(0, 9)
395
+ .toString('ascii')
396
+ .split('\0')
397
+ .shift() || '';
398
+ const record_time = parseHexToTime(recvData.subarray(26, 26 + 6));
399
+ return { user_id, record_time };
400
+ };
401
+ const decodeUDPHeader = (header) => {
402
+ return {
403
+ commandId: header.readUIntLE(0, 2),
404
+ checkSum: header.readUIntLE(2, 2),
405
+ sessionId: header.readUIntLE(4, 2),
406
+ replyId: header.readUIntLE(6, 2)
407
+ };
408
+ };
409
+ const decodeTCPHeader = (header) => {
410
+ const recvData = header.subarray(8);
411
+ const payloadSize = header.readUIntLE(4, 2);
412
+ return {
413
+ commandId: recvData.readUIntLE(0, 2),
414
+ checkSum: recvData.readUIntLE(2, 2),
415
+ sessionId: recvData.readUIntLE(4, 2),
416
+ replyId: recvData.readUIntLE(6, 2),
417
+ payloadSize
418
+ };
419
+ };
420
+ const exportErrorMessage = (commandValue) => {
421
+ const keys = Object.keys(COMMANDS);
422
+ for (const key of keys) {
423
+ if (COMMANDS[key] === commandValue) {
424
+ return key.toString();
425
+ }
426
+ }
427
+ return 'AN UNKNOWN ERROR';
428
+ };
429
+ const checkNotEventTCP = (data) => {
430
+ try {
431
+ const cleanedData = removeTcpHeader(data);
432
+ const commandId = cleanedData.readUIntLE(0, 2);
433
+ const event = cleanedData.readUIntLE(4, 2);
434
+ return event === COMMANDS.EF_ATTLOG && commandId === COMMANDS.CMD_REG_EVENT;
435
+ }
436
+ catch (err) {
437
+ log(`[228] : ${err.toString()} ,${data.toString('hex')} `);
438
+ return false;
439
+ }
440
+ };
441
+ const checkNotEventUDP = (data) => {
442
+ const { commandId } = decodeUDPHeader(data.subarray(0, 8));
443
+ return commandId === COMMANDS.CMD_REG_EVENT;
444
+ };
445
+ const makeKey = (key, sessionId) => {
446
+ let k = 0;
447
+ for (let i = 0; i < 32; i++) {
448
+ if ((key & (1 << i)) !== 0) {
449
+ k = (k << 1) | 1;
450
+ }
451
+ else {
452
+ k = k << 1;
453
+ }
454
+ }
455
+ k += sessionId;
456
+ let hex = k.toString(16).padStart(8, "0");
457
+ let response = new Uint8Array(4);
458
+ let index = 3;
459
+ while (hex.length > 0) {
460
+ response[index] = parseInt(hex.substring(0, 2), 16);
461
+ index--;
462
+ hex = hex.substring(2);
463
+ }
464
+ response[0] ^= 'Z'.charCodeAt(0);
465
+ response[1] ^= 'K'.charCodeAt(0);
466
+ response[2] ^= 'S'.charCodeAt(0);
467
+ response[3] ^= 'O'.charCodeAt(0);
468
+ let finalKey = response[0] +
469
+ (response[1] << 8) +
470
+ (response[2] << 16) +
471
+ (response[3] << 24);
472
+ let swp = finalKey >>> 16;
473
+ finalKey = (finalKey << 16) | swp;
474
+ return finalKey >>> 0;
475
+ };
476
+ const authKey = (comKey, sessionId) => {
477
+ let k = makeKey(comKey, sessionId) >>> 0;
478
+ let rand = Math.floor(Math.random() * 256);
479
+ let hex = k.toString(16).padStart(8, "0");
480
+ let response = new Uint8Array(4);
481
+ let index = 3;
482
+ while (index >= 0) {
483
+ response[index] = parseInt(hex.substring(0, 2), 16);
484
+ index--;
485
+ hex = hex.substring(2);
486
+ }
487
+ response[0] ^= rand;
488
+ response[1] ^= rand;
489
+ response[2] = rand;
490
+ response[3] ^= rand;
491
+ return Array.from(response);
492
+ };
493
+
494
+ /**
495
+ * Represents a fingerprint template with associated metadata
496
+ */
497
+ class Finger {
498
+ uid;
499
+ fid;
500
+ valid;
501
+ template;
502
+ size;
503
+ mark;
504
+ /**
505
+ * Creates a new Finger instance
506
+ * @param uid User internal reference
507
+ * @param fid Finger ID (value >= 0 && value <= 9)
508
+ * @param valid Flag indicating 0 = invalid | 1 = valid | 3 = duress
509
+ * @param template Fingerprint template data buffer
510
+ */
511
+ constructor(uid, fid, valid, template) {
512
+ this.uid = Number(uid);
513
+ this.fid = Number(fid);
514
+ this.valid = Number(valid);
515
+ this.template = template;
516
+ this.size = template.length;
517
+ // Create mark showing first and last 8 bytes as hex
518
+ const start = template.slice(0, 8).toString('hex');
519
+ const end = template.slice(-8).toString('hex');
520
+ this.mark = `${start}...${end}`;
521
+ }
522
+ /**
523
+ * Packs the fingerprint data with metadata into a Buffer
524
+ * @returns Buffer containing packed fingerprint data
525
+ */
526
+ repack() {
527
+ // pack("HHbb%is" % (self.size), self.size+6, self.uid, self.fid, self.valid, self.template)
528
+ const buf = Buffer.alloc(6 + this.size); // HHbb = 6 bytes + template size
529
+ let offset = 0;
530
+ buf.writeUInt16LE(this.size + 6, offset);
531
+ offset += 2;
532
+ buf.writeUInt16LE(this.uid, offset);
533
+ offset += 2;
534
+ buf.writeUInt8(this.fid, offset);
535
+ offset += 1;
536
+ buf.writeUInt8(this.valid, offset);
537
+ offset += 1;
538
+ this.template.copy(buf, offset);
539
+ return buf;
540
+ }
541
+ /**
542
+ * Packs only the fingerprint template data into a Buffer
543
+ * @returns Buffer containing just the template data
544
+ */
545
+ repackOnly() {
546
+ // pack("H%is" % (self.size), self.size, self.template)
547
+ const buf = Buffer.alloc(2 + this.size); // H = 2 bytes + template size
548
+ buf.writeUInt16LE(this.size, 0);
549
+ this.template.copy(buf, 2);
550
+ return buf;
551
+ }
552
+ /**
553
+ * Compares this fingerprint with another for equality
554
+ * @param other Another Finger instance to compare with
555
+ * @returns true if all properties and template data match
556
+ */
557
+ equals(other) {
558
+ if (!(other instanceof Finger))
559
+ return false;
560
+ return this.uid === other.uid &&
561
+ this.fid === other.fid &&
562
+ this.valid === other.valid &&
563
+ this.template.equals(other.template);
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Error types for device communication
569
+ */
570
+ const ERROR_TYPES = {
571
+ ECONNRESET: 'ECONNRESET',
572
+ ECONNREFUSED: 'ECONNREFUSED'};
573
+ /**
574
+ * Custom error class for device communication errors
575
+ */
576
+ class ZkError {
577
+ err;
578
+ ip;
579
+ command;
580
+ /**
581
+ * Creates a new ZkError instance
582
+ * @param err The error object
583
+ * @param command The command that caused the error
584
+ * @param ip The IP address of the device
585
+ */
586
+ constructor(err, command, ip) {
587
+ this.err = err;
588
+ this.ip = ip;
589
+ this.command = command;
590
+ }
591
+ /**
592
+ * Gets a user-friendly error message
593
+ * @returns A formatted error message
594
+ */
595
+ toast() {
596
+ if (this.err.code === ERROR_TYPES.ECONNRESET) {
597
+ return 'Another device is connecting to the device so the connection is interrupted';
598
+ }
599
+ else if (this.err.code === ERROR_TYPES.ECONNREFUSED) {
600
+ return 'IP of the device is refused';
601
+ }
602
+ return this.err.message;
603
+ }
604
+ /**
605
+ * Gets detailed error information
606
+ * @returns An object containing error details
607
+ */
608
+ getError() {
609
+ return {
610
+ err: {
611
+ message: this.err.message,
612
+ code: this.err.code
613
+ },
614
+ ip: this.ip,
615
+ command: this.command
616
+ };
617
+ }
618
+ }
619
+
620
+ class ZTCP {
621
+ /**
622
+ * @param_ip ip address of device
623
+ * @param_port port number of device
624
+ * @param_timeout connection timout
625
+ * @param_comm_key communication key of device (if the case)
626
+ * @return Zkteco TCP socket connection instance
627
+ */
628
+ ip;
629
+ port;
630
+ timeout;
631
+ sessionId = 0;
632
+ replyId = 0;
633
+ socket;
634
+ comm_key;
635
+ user_count = 0;
636
+ fp_count = 0;
637
+ pwd_count = 0;
638
+ oplog_count = 0;
639
+ attlog_count = 0;
640
+ fp_cap = 0;
641
+ user_cap = 0;
642
+ attlog_cap = 0;
643
+ fp_av = 0;
644
+ user_av = 0;
645
+ attlog_av = 0;
646
+ face_count = 0;
647
+ face_cap = 0;
648
+ userPacketSize = 72;
649
+ verbose = false;
650
+ constructor(ip, port, timeout, comm_key, verbose) {
651
+ this.ip = ip;
652
+ this.port = port;
653
+ this.timeout = timeout;
654
+ this.replyId = 0;
655
+ this.comm_key = comm_key;
656
+ this.verbose = verbose;
657
+ }
658
+ createSocket(cbError, cbClose) {
659
+ return new Promise((resolve, reject) => {
660
+ this.socket = new Socket();
661
+ // Handle socket error
662
+ this.socket.once('error', (err) => {
663
+ this.socket = undefined; // Ensure socket reference is cleared
664
+ reject(err);
665
+ if (typeof cbError === 'function')
666
+ cbError(err);
667
+ });
668
+ // Handle successful connection
669
+ this.socket.once('connect', () => {
670
+ resolve(this.socket);
671
+ });
672
+ // Handle socket closure
673
+ this.socket.once('close', () => {
674
+ this.socket = undefined; // Ensure socket reference is cleared
675
+ if (typeof cbClose === 'function')
676
+ cbClose('tcp');
677
+ });
678
+ // Set socket timeout if provided
679
+ if (this.timeout) {
680
+ this.socket.setTimeout(this.timeout);
681
+ }
682
+ // Initiate connection
683
+ this.socket.connect(this.port, this.ip);
684
+ });
685
+ }
686
+ async connect() {
687
+ try {
688
+ let reply = await this.executeCmd(COMMANDS.CMD_CONNECT, '');
689
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
690
+ return true;
691
+ }
692
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_UNAUTH) {
693
+ const hashedCommkey = authKey(this.comm_key, this.sessionId);
694
+ reply = await this.executeCmd(COMMANDS.CMD_AUTH, hashedCommkey);
695
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
696
+ return true;
697
+ }
698
+ else {
699
+ throw new Error("error de authenticacion");
700
+ }
701
+ }
702
+ else {
703
+ // No reply received; throw an error
704
+ throw new Error('NO_REPLY_ON_CMD_CONNECT');
705
+ }
706
+ }
707
+ catch (err) {
708
+ // Log the error for debugging, if necessary
709
+ console.error('Failed to connect:', err);
710
+ // Re-throw the error for handling by the caller
711
+ throw err;
712
+ }
713
+ }
714
+ async closeSocket() {
715
+ return new Promise((resolve, reject) => {
716
+ // If no socket is present, resolve immediately
717
+ if (!this.socket) {
718
+ return resolve(true);
719
+ }
720
+ // Clean up listeners to avoid potential memory leaks or duplicate handling
721
+ this.socket.removeAllListeners('data');
722
+ // Set a timeout to handle cases where socket.end might not resolve
723
+ const timer = setTimeout(() => {
724
+ this.socket.destroy(); // Forcibly close the socket if not closed properly
725
+ resolve(true); // Resolve even if the socket was not closed properly
726
+ }, 2000);
727
+ // Close the socket and clear the timeout upon successful completion
728
+ this.socket.end(() => {
729
+ clearTimeout(timer);
730
+ resolve(true); // Resolve once the socket has ended
731
+ });
732
+ // Handle socket errors during closing
733
+ this.socket.once('error', (err) => {
734
+ clearTimeout(timer);
735
+ reject(err); // Reject the promise with the error
736
+ });
737
+ });
738
+ }
739
+ writeMessage(msg, connect) {
740
+ return new Promise((resolve, reject) => {
741
+ // Check if the socket is initialized
742
+ if (!this.socket) {
743
+ return reject(new Error('Socket is not initialized'));
744
+ }
745
+ // Define a variable for the timeout reference
746
+ let timer = null;
747
+ // Handle incoming data
748
+ const onData = (data) => {
749
+ // Check if the socket is still valid before trying to remove the listener
750
+ if (this.socket) {
751
+ this.socket.removeListener('data', onData); // Remove the data event listener
752
+ }
753
+ clearTimeout(timer); // Clear the timeout once data is received
754
+ resolve(data); // Resolve the promise with the received data
755
+ };
756
+ // Attach the data event listener
757
+ this.socket.once('data', onData);
758
+ // Attempt to write the message to the socket
759
+ this.socket.write(msg, null, (err) => {
760
+ if (err) {
761
+ // Check if the socket is still valid before trying to remove the listener
762
+ if (this.socket) {
763
+ this.socket.removeListener('data', onData); // Clean up listener on write error
764
+ }
765
+ return reject(err); // Reject the promise with the write error
766
+ }
767
+ // If a timeout is set, configure it
768
+ if (this.timeout) {
769
+ timer = setTimeout(() => {
770
+ // Check if the socket is still valid before trying to remove the listener
771
+ if (this.socket) {
772
+ this.socket.removeListener('data', onData); // Remove listener on timeout
773
+ }
774
+ reject(new Error('TIMEOUT_ON_WRITING_MESSAGE')); // Reject the promise on timeout
775
+ }, connect ? 2000 : this.timeout);
776
+ }
777
+ });
778
+ });
779
+ }
780
+ async requestData(msg) {
781
+ try {
782
+ return await new Promise((resolve, reject) => {
783
+ let timer = null;
784
+ let replyBuffer = Buffer.from([]);
785
+ // Internal callback to handle data reception
786
+ const internalCallback = (data_1) => {
787
+ if (this.socket) {
788
+ this.socket.removeListener('data', handleOnData); // Clean up listener
789
+ }
790
+ if (timer)
791
+ clearTimeout(timer); // Clear the timeout
792
+ resolve(data_1); // Resolve the promise with the data
793
+ };
794
+ // Handle incoming data
795
+ const handleOnData = (data_3) => {
796
+ replyBuffer = Buffer.concat([replyBuffer, data_3]); // Accumulate data
797
+ // Check if the data is a valid TCP event
798
+ if (checkNotEventTCP(data_3))
799
+ return;
800
+ // Decode the TCP header
801
+ const header = decodeTCPHeader(replyBuffer.subarray(0, 16));
802
+ if (this.verbose) {
803
+ console.log("linea 232: replyId: ", header.replyId, " command: ", header.commandId, Object.keys(COMMANDS).find(c => COMMANDS[c] == header.commandId));
804
+ }
805
+ // Handle based on command ID
806
+ if (header.commandId === COMMANDS.CMD_DATA) {
807
+ // Set a timeout to handle delayed responses
808
+ timer = setTimeout(() => {
809
+ internalCallback(replyBuffer); // Resolve with accumulated buffer
810
+ }, 1000);
811
+ }
812
+ else {
813
+ // Set a timeout to handle errors
814
+ timer = setTimeout(() => {
815
+ if (this.socket) {
816
+ this.socket.removeListener('data', handleOnData); // Clean up listener on timeout
817
+ }
818
+ reject(new Error('TIMEOUT_ON_RECEIVING_REQUEST_DATA')); // Reject on timeout
819
+ }, this.timeout);
820
+ // Extract packet length and handle accordingly
821
+ const packetLength = data_3.readUIntLE(4, 2);
822
+ if (packetLength > 8) {
823
+ internalCallback(data_3); // Resolve immediately if sufficient data
824
+ }
825
+ }
826
+ };
827
+ // Ensure the socket is valid before attaching the listener
828
+ if (this.socket) {
829
+ this.socket.on('data', handleOnData);
830
+ // Write the message to the socket
831
+ this.socket.write(msg, null, (err) => {
832
+ if (err) {
833
+ if (this.socket) {
834
+ this.socket.removeListener('data', handleOnData); // Clean up listener on error
835
+ }
836
+ return reject(err); // Reject the promise with the error
837
+ }
838
+ // Set a timeout to handle cases where no response is received
839
+ timer = setTimeout(() => {
840
+ if (this.socket) {
841
+ this.socket.removeListener('data', handleOnData); // Clean up listener on timeout
842
+ }
843
+ reject(new Error('TIMEOUT_IN_RECEIVING_RESPONSE_AFTER_REQUESTING_DATA')); // Reject on timeout
844
+ }, this.timeout);
845
+ });
846
+ }
847
+ else {
848
+ reject(new Error('SOCKET_NOT_INITIALIZED')); // Reject if socket is not initialized
849
+ }
850
+ });
851
+ }
852
+ catch (err_1) {
853
+ console.error("Promise Rejected:", err_1); // Log the rejection reason
854
+ throw err_1; // Re-throw the error to be handled by the caller
855
+ }
856
+ }
857
+ /**
858
+ *
859
+ * @param {*} command
860
+ * @param {*} data
861
+ *
862
+ *
863
+ * reject error when command fail and resolve data when success
864
+ */
865
+ async executeCmd(command, data) {
866
+ // Reset sessionId and replyId for connection commands
867
+ if (command === COMMANDS.CMD_CONNECT) {
868
+ this.sessionId = 0;
869
+ this.replyId = 0;
870
+ }
871
+ else {
872
+ this.replyId++;
873
+ }
874
+ if (this.verbose) {
875
+ console.log("linea 305: replyId: ", this.replyId, " command: ", command, Object.keys(COMMANDS).find(u => COMMANDS[u] == command));
876
+ }
877
+ const buf = createTCPHeader(command, this.sessionId, this.replyId, data);
878
+ try {
879
+ // Write the message to the socket and wait for a response
880
+ const reply = await this.writeMessage(buf, command === COMMANDS.CMD_CONNECT || command === COMMANDS.CMD_EXIT);
881
+ // Remove TCP header from the response
882
+ const rReply = removeTcpHeader(reply);
883
+ // Update sessionId for connection command responses
884
+ if (command === COMMANDS.CMD_CONNECT && rReply && rReply.length >= 6) { // Assuming sessionId is located at offset 4 and is 2 bytes long
885
+ this.sessionId = rReply.readUInt16LE(4);
886
+ }
887
+ return rReply;
888
+ }
889
+ catch (err) {
890
+ // Log or handle the error if necessary
891
+ console.error('Error executing command:', err);
892
+ throw err; // Re-throw the error for handling by the caller
893
+ }
894
+ }
895
+ async sendChunkRequest(start, size) {
896
+ this.replyId++;
897
+ const reqData = Buffer.alloc(8);
898
+ reqData.writeUInt32LE(start, 0);
899
+ reqData.writeUInt32LE(size, 4);
900
+ const buf = createTCPHeader(COMMANDS.CMD_DATA_RDY, this.sessionId, this.replyId, reqData);
901
+ try {
902
+ await new Promise((resolve, reject) => {
903
+ this.socket.write(buf, null, (err) => {
904
+ if (err) {
905
+ console.error(`[TCP][SEND_CHUNK_REQUEST] Error sending chunk request: ${err.message}`);
906
+ reject(err); // Reject the promise if there is an error
907
+ }
908
+ else {
909
+ resolve(true); // Resolve the promise if the write operation succeeds
910
+ }
911
+ });
912
+ });
913
+ }
914
+ catch (err) {
915
+ // Handle or log the error as needed
916
+ console.error(`[TCP][SEND_CHUNK_REQUEST] Exception: ${err.message}`);
917
+ throw err; // Re-throw the error for handling by the caller
918
+ }
919
+ }
920
+ /**
921
+ *
922
+ * @param {*} reqData - indicate the type of data that need to receive ( user or attLog)
923
+ * @param {*} cb - callback is triggered when receiving packets
924
+ *
925
+ * readWithBuffer will reject error if it'wrong when starting request data
926
+ * readWithBuffer will return { data: replyData , err: Error } when receiving requested data
927
+ */
928
+ readWithBuffer(reqData, cb = null) {
929
+ return new Promise(async (resolve, reject) => {
930
+ this.replyId++;
931
+ const buf = createTCPHeader(COMMANDS.CMD_DATA_WRRQ, this.sessionId, this.replyId, reqData);
932
+ let reply = null;
933
+ try {
934
+ reply = await this.requestData(buf);
935
+ }
936
+ catch (err) {
937
+ reject(err);
938
+ console.log(reply);
939
+ }
940
+ const header = decodeTCPHeader(reply.subarray(0, 16));
941
+ switch (header.commandId) {
942
+ case COMMANDS.CMD_DATA: {
943
+ resolve({ data: reply.subarray(16), mode: 8 });
944
+ break;
945
+ }
946
+ case COMMANDS.CMD_ACK_OK:
947
+ case COMMANDS.CMD_PREPARE_DATA: {
948
+ // this case show that data is prepared => send command to get these data
949
+ // reply variable includes information about the size of following data
950
+ const recvData = reply.subarray(16);
951
+ const size = recvData.readUIntLE(1, 4);
952
+ // We need to split the data to many chunks to receive , because it's to large
953
+ // After receiving all chunk data , we concat it to TotalBuffer variable , that 's the data we want
954
+ let remain = size % MAX_CHUNK;
955
+ let numberChunks = Math.round(size - remain) / MAX_CHUNK;
956
+ let totalPackets = numberChunks + (remain > 0 ? 1 : 0);
957
+ let replyData = Buffer.from([]);
958
+ let totalBuffer = Buffer.from([]);
959
+ let realTotalBuffer = Buffer.from([]);
960
+ const timeout = 10000;
961
+ let timer = setTimeout(() => {
962
+ internalCallback(replyData, new Error('TIMEOUT WHEN RECEIVING PACKET'));
963
+ }, timeout);
964
+ const internalCallback = (replyData, err = null) => {
965
+ // this.socket && this.socket.removeListener('data', handleOnData)
966
+ timer && clearTimeout(timer);
967
+ resolve({ data: replyData, err });
968
+ };
969
+ const handleOnData = (reply) => {
970
+ if (checkNotEventTCP(reply))
971
+ return;
972
+ clearTimeout(timer);
973
+ timer = setTimeout(() => {
974
+ internalCallback(replyData, new Error(`TIME OUT !! ${totalPackets} PACKETS REMAIN !`));
975
+ }, timeout);
976
+ totalBuffer = Buffer.concat([totalBuffer, reply]);
977
+ const packetLength = totalBuffer.readUIntLE(4, 2);
978
+ if (totalBuffer.length >= 8 + packetLength) {
979
+ realTotalBuffer = Buffer.concat([realTotalBuffer, totalBuffer.subarray(16, 8 + packetLength)]);
980
+ totalBuffer = totalBuffer.subarray(8 + packetLength);
981
+ if ((totalPackets > 1 && realTotalBuffer.length === MAX_CHUNK + 8)
982
+ || (totalPackets === 1 && realTotalBuffer.length === remain + 8)) {
983
+ replyData = Buffer.concat([replyData, realTotalBuffer.subarray(8)]);
984
+ totalBuffer = Buffer.from([]);
985
+ realTotalBuffer = Buffer.from([]);
986
+ totalPackets -= 1;
987
+ cb && cb(replyData.length, size);
988
+ if (totalPackets <= 0) {
989
+ internalCallback(replyData);
990
+ }
991
+ }
992
+ }
993
+ };
994
+ this.socket.once('close', () => {
995
+ internalCallback(replyData, new Error('Socket is disconnected unexpectedly'));
996
+ });
997
+ this.socket.on('data', handleOnData);
998
+ for (let i = 0; i <= numberChunks; i++) {
999
+ if (i === numberChunks) {
1000
+ await this.sendChunkRequest(numberChunks * MAX_CHUNK, remain);
1001
+ }
1002
+ else {
1003
+ await this.sendChunkRequest(i * MAX_CHUNK, MAX_CHUNK);
1004
+ }
1005
+ }
1006
+ break;
1007
+ }
1008
+ default: {
1009
+ reject(new Error('ERROR_IN_UNHANDLE_CMD ' + exportErrorMessage(header.commandId)));
1010
+ }
1011
+ }
1012
+ });
1013
+ }
1014
+ /**
1015
+ * reject error when starting request data
1016
+ * @return {Record<string, User[] | Error>} when receiving requested data
1017
+ */
1018
+ async getUsers() {
1019
+ try {
1020
+ // Free any existing buffer data to prepare for a new request
1021
+ if (this.socket) {
1022
+ await this.freeData();
1023
+ }
1024
+ // Request user data
1025
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_USERS);
1026
+ // Free buffer data after receiving the data
1027
+ if (this.socket) {
1028
+ await this.freeData();
1029
+ }
1030
+ // Constants for user data processing
1031
+ const USER_PACKET_SIZE = 72;
1032
+ // Ensure data.data is a valid buffer
1033
+ if (!data.data || !(data.data instanceof Buffer)) {
1034
+ throw new Error('Invalid data received');
1035
+ }
1036
+ let userData = data.data.subarray(4); // Skip the first 4 bytes (headers)
1037
+ const users = [];
1038
+ // Process each user packet
1039
+ while (userData.length >= USER_PACKET_SIZE) {
1040
+ // Decode user data and add to the users array
1041
+ const user = decodeUserData72(userData.subarray(0, USER_PACKET_SIZE));
1042
+ users.push(user);
1043
+ userData = userData.subarray(USER_PACKET_SIZE); // Move to the next packet
1044
+ }
1045
+ // Return the list of users
1046
+ return { data: users };
1047
+ }
1048
+ catch (err) {
1049
+ // Log the error for debugging
1050
+ console.error('Error getting users:', err);
1051
+ // Re-throw the error to be handled by the caller
1052
+ throw err;
1053
+ }
1054
+ }
1055
+ /**
1056
+ *
1057
+ * @param {*} ip
1058
+ * @param {*} callbackInProcess
1059
+ * reject error when starting request data
1060
+ * return { data: records, err: Error } when receiving requested data
1061
+ */
1062
+ async getAttendances(callbackInProcess = () => { }) {
1063
+ try {
1064
+ // Free any existing buffer data to prepare for a new request
1065
+ if (this.socket) {
1066
+ await this.freeData();
1067
+ }
1068
+ // Request attendance logs and handle chunked data
1069
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_ATTENDANCE_LOGS, callbackInProcess);
1070
+ // Free buffer data after receiving the attendance logs
1071
+ if (this.socket) {
1072
+ await this.freeData();
1073
+ }
1074
+ // Constants for record processing
1075
+ const RECORD_PACKET_SIZE = 40;
1076
+ // Ensure data.data is a valid buffer
1077
+ if (!data.data || !(data.data instanceof Buffer)) {
1078
+ throw new Error('Invalid data received');
1079
+ }
1080
+ // Process the record data
1081
+ let recordData = data.data.subarray(4); // Skip header
1082
+ const records = [];
1083
+ // Process each attendance record
1084
+ while (recordData.length >= RECORD_PACKET_SIZE) {
1085
+ const record = decodeRecordData40(recordData.subarray(0, RECORD_PACKET_SIZE));
1086
+ records.push({ ...record, ip: this.ip }); // Add IP address to each record
1087
+ recordData = recordData.subarray(RECORD_PACKET_SIZE); // Move to the next packet
1088
+ }
1089
+ // Return the list of attendance records
1090
+ return { data: records };
1091
+ }
1092
+ catch (err) {
1093
+ // Log and re-throw the error
1094
+ console.error('Error getting attendance records:', err);
1095
+ throw err; // Re-throw the error for handling by the caller
1096
+ }
1097
+ }
1098
+ async freeData() {
1099
+ try {
1100
+ const resp = await this.executeCmd(COMMANDS.CMD_FREE_DATA, '');
1101
+ return !!resp;
1102
+ }
1103
+ catch (err) {
1104
+ console.error('Error freeing data:', err);
1105
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
1106
+ }
1107
+ }
1108
+ async disableDevice() {
1109
+ try {
1110
+ const resp = await this.executeCmd(COMMANDS.CMD_DISABLEDEVICE, REQUEST_DATA.DISABLE_DEVICE);
1111
+ return !!resp;
1112
+ }
1113
+ catch (err) {
1114
+ console.error('Error disabling device:', err);
1115
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
1116
+ }
1117
+ }
1118
+ async enableDevice() {
1119
+ try {
1120
+ const resp = await this.executeCmd(COMMANDS.CMD_ENABLEDEVICE, '');
1121
+ return !!resp;
1122
+ }
1123
+ catch (err) {
1124
+ console.error('Error enabling device:', err);
1125
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
1126
+ }
1127
+ }
1128
+ async disconnect() {
1129
+ try {
1130
+ // Attempt to execute the disconnect command
1131
+ await this.executeCmd(COMMANDS.CMD_EXIT, '');
1132
+ }
1133
+ catch (err) {
1134
+ // Log any errors encountered during command execution
1135
+ console.error('Error during disconnection:', err);
1136
+ // Optionally, add more handling or recovery logic here
1137
+ }
1138
+ // Attempt to close the socket and return the result
1139
+ try {
1140
+ await this.closeSocket();
1141
+ }
1142
+ catch (err) {
1143
+ // Log any errors encountered while closing the socket
1144
+ console.error('Error during socket closure:', err);
1145
+ // Optionally, rethrow or handle the error if necessary
1146
+ throw err; // Re-throwing to propagate the error
1147
+ }
1148
+ }
1149
+ async getInfo() {
1150
+ try {
1151
+ // Execute the command to retrieve free sizes from the device
1152
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, '');
1153
+ // Parse the response data to extract and return relevant information
1154
+ return {
1155
+ userCounts: data.readUIntLE(24, 4), // Number of users
1156
+ logCounts: data.readUIntLE(40, 4), // Number of logs
1157
+ logCapacity: data.readUIntLE(72, 4) // Capacity of logs in bytes
1158
+ };
1159
+ }
1160
+ catch (err) {
1161
+ // Log the error for debugging purposes
1162
+ console.error('Error getting device info:', err);
1163
+ // Re-throw the error to allow upstream error handling
1164
+ throw err;
1165
+ }
1166
+ }
1167
+ async getSizes() {
1168
+ try {
1169
+ // Execute the command to retrieve free sizes from the device
1170
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, '');
1171
+ // Parse the response data to extract and return relevant information
1172
+ const buf = data.slice(8); // remove header
1173
+ this.user_count = buf.readUIntLE(16, 4);
1174
+ this.fp_count = buf.readUIntLE(24, 4);
1175
+ this.pwd_count = buf.readUIntLE(52, 4);
1176
+ this.oplog_count = buf.readUIntLE(40, 4);
1177
+ this.attlog_count = buf.readUIntLE(32, 4);
1178
+ this.fp_cap = buf.readUIntLE(56, 4);
1179
+ this.user_cap = buf.readUIntLE(60, 4);
1180
+ this.attlog_cap = buf.readUIntLE(64, 4);
1181
+ this.fp_av = buf.readUIntLE(68, 4);
1182
+ this.user_av = buf.readUIntLE(72, 4);
1183
+ this.attlog_av = buf.readUIntLE(76, 4);
1184
+ this.face_count = buf.readUIntLE(80, 4);
1185
+ this.face_cap = buf.readUIntLE(88, 4);
1186
+ return {
1187
+ userCounts: this.user_count, // Number of users
1188
+ logCounts: this.attlog_count, // Number of logs
1189
+ fingerCount: this.fp_count,
1190
+ adminCount: this.pwd_count,
1191
+ opLogCount: this.oplog_count,
1192
+ logCapacity: this.attlog_cap, // Capacity of logs in bytes
1193
+ fingerCapacity: this.fp_cap,
1194
+ userCapacity: this.user_cap,
1195
+ attLogCapacity: this.attlog_cap,
1196
+ fingerAvailable: this.fp_av,
1197
+ userAvailable: this.user_av,
1198
+ attLogAvailable: this.attlog_av,
1199
+ faceCount: this.face_count,
1200
+ faceCapacity: this.face_cap
1201
+ };
1202
+ }
1203
+ catch (err) {
1204
+ // Log the error for debugging purposes
1205
+ console.error('Error getting device info:', err);
1206
+ // Re-throw the error to allow upstream error handling
1207
+ throw err;
1208
+ }
1209
+ }
1210
+ async getVendor() {
1211
+ const keyword = '~OEMVendor';
1212
+ try {
1213
+ // Execute the command to get serial number
1214
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1215
+ // Extract and format the serial number from the response data
1216
+ const vendor = data.slice(8) // Skip the first 8 bytes (header)
1217
+ .toString('ascii') // Convert buffer to string
1218
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1219
+ .replace(/\u0000/g, ''); // Remove null characters
1220
+ return vendor;
1221
+ }
1222
+ catch (err) {
1223
+ // Log the error for debugging
1224
+ console.error('Error getting vendor:', err);
1225
+ // Re-throw the error for higher-level handling
1226
+ throw err;
1227
+ }
1228
+ }
1229
+ async getProductTime() {
1230
+ const keyword = '~ProductTime';
1231
+ try {
1232
+ // Execute the command to get serial number
1233
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1234
+ // Extract and format the serial number from the response data
1235
+ const ProductTime = data.slice(8) // Skip the first 8 bytes (header)
1236
+ .toString('ascii') // Convert buffer to string
1237
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1238
+ .replace(/\u0000/g, ''); // Remove null characters
1239
+ return new Date(ProductTime);
1240
+ }
1241
+ catch (err) {
1242
+ // Log the error for debugging
1243
+ console.error('Error getting Product Time:', err);
1244
+ // Re-throw the error for higher-level handling
1245
+ throw err;
1246
+ }
1247
+ }
1248
+ async getMacAddress() {
1249
+ const keyword = 'MAC';
1250
+ try {
1251
+ // Execute the command to get serial number
1252
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1253
+ // Extract and format the serial number from the response data
1254
+ const macAddr = data.slice(8) // Skip the first 8 bytes (header)
1255
+ .toString('ascii') // Convert buffer to string
1256
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1257
+ .replace(/\u0000/g, ''); // Remove null characters
1258
+ return macAddr;
1259
+ }
1260
+ catch (err) {
1261
+ // Log the error for debugging
1262
+ console.error('Error getting MAC address:', err);
1263
+ // Re-throw the error for higher-level handling
1264
+ throw err;
1265
+ }
1266
+ }
1267
+ async getSerialNumber() {
1268
+ const keyword = '~SerialNumber';
1269
+ try {
1270
+ // Execute the command to get serial number
1271
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1272
+ // Extract and format the serial number from the response data
1273
+ const serialNumber = data.slice(8) // Skip the first 8 bytes (header)
1274
+ .toString('utf-8') // Convert buffer to string
1275
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1276
+ .replace(/\u0000/g, ''); // Remove null characters
1277
+ return serialNumber;
1278
+ }
1279
+ catch (err) {
1280
+ // Log the error for debugging
1281
+ console.error('Error getting serial number:', err);
1282
+ // Re-throw the error for higher-level handling
1283
+ throw err;
1284
+ }
1285
+ }
1286
+ async getDeviceVersion() {
1287
+ const keyword = '~ZKFPVersion';
1288
+ try {
1289
+ // Execute the command to get device version
1290
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1291
+ // Extract and format the device version from the response data
1292
+ // Remove null characters
1293
+ return data.slice(8) // Skip the first 8 bytes (header)
1294
+ .toString('ascii') // Convert buffer to ASCII string
1295
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1296
+ .replace(/\u0000/g, '');
1297
+ }
1298
+ catch (err) {
1299
+ // Log the error for debugging
1300
+ console.error('Error getting device version:', err);
1301
+ // Re-throw the error for higher-level handling
1302
+ throw err;
1303
+ }
1304
+ }
1305
+ async getDeviceName() {
1306
+ const keyword = '~DeviceName';
1307
+ try {
1308
+ // Execute the command to get the device name
1309
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1310
+ // Extract and format the device name from the response data
1311
+ // Remove null characters
1312
+ return data.slice(8) // Skip the first 8 bytes (header)
1313
+ .toString('ascii') // Convert buffer to ASCII string
1314
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1315
+ .replace(/\u0000/g, '');
1316
+ }
1317
+ catch (err) {
1318
+ // Log the error for debugging
1319
+ console.error('Error getting device name:', err);
1320
+ // Re-throw the error for higher-level handling
1321
+ throw err;
1322
+ }
1323
+ }
1324
+ async getPlatform() {
1325
+ const keyword = '~Platform';
1326
+ try {
1327
+ // Execute the command to get the platform information
1328
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1329
+ // Extract and format the platform information from the response data
1330
+ // Remove null characters
1331
+ return data.slice(8) // Skip the first 8 bytes (header)
1332
+ .toString('ascii') // Convert buffer to ASCII string
1333
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1334
+ .replace(/\u0000/g, '');
1335
+ }
1336
+ catch (err) {
1337
+ // Log the error for debugging
1338
+ console.error('Error getting platform information:', err);
1339
+ // Re-throw the error for higher-level handling
1340
+ throw err;
1341
+ }
1342
+ }
1343
+ async getOS() {
1344
+ const keyword = '~OS';
1345
+ try {
1346
+ // Execute the command to get the OS information
1347
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1348
+ // Extract and format the OS information from the response data
1349
+ // Remove null characters
1350
+ return data.slice(8) // Skip the first 8 bytes (header)
1351
+ .toString('ascii') // Convert buffer to ASCII string
1352
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1353
+ .replace(/\u0000/g, '');
1354
+ }
1355
+ catch (err) {
1356
+ // Log the error for debugging
1357
+ console.error('Error getting OS information:', err);
1358
+ // Re-throw the error for higher-level handling
1359
+ throw err;
1360
+ }
1361
+ }
1362
+ async getWorkCode() {
1363
+ const keyword = 'WorkCode';
1364
+ try {
1365
+ // Execute the command to get the WorkCode information
1366
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1367
+ // Extract and format the WorkCode information from the response data
1368
+ // Remove null characters
1369
+ return data.slice(8) // Skip the first 8 bytes (header)
1370
+ .toString('ascii') // Convert buffer to ASCII string
1371
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1372
+ .replace(/\u0000/g, '');
1373
+ }
1374
+ catch (err) {
1375
+ // Log the error for debugging
1376
+ console.error('Error getting WorkCode:', err);
1377
+ // Re-throw the error to be handled by the caller
1378
+ throw err;
1379
+ }
1380
+ }
1381
+ async getPIN() {
1382
+ const keyword = '~PIN2Width';
1383
+ try {
1384
+ // Execute the command to get the PIN information
1385
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1386
+ // Extract and format the PIN information from the response data
1387
+ // Remove null characters
1388
+ return data.slice(8) // Skip the first 8 bytes (header)
1389
+ .toString('ascii') // Convert buffer to ASCII string
1390
+ .replace(`${keyword}=`, '') // Remove the keyword prefix
1391
+ .replace(/\u0000/g, '');
1392
+ }
1393
+ catch (err) {
1394
+ // Log the error for debugging
1395
+ console.error('Error getting PIN:', err);
1396
+ // Re-throw the error to be handled by the caller
1397
+ throw err;
1398
+ }
1399
+ }
1400
+ async getFaceOn() {
1401
+ const keyword = 'FaceFunOn';
1402
+ try {
1403
+ // Execute the command to get the face function status
1404
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1405
+ // Extract and process the status from the response data
1406
+ const status = data.slice(8) // Skip the first 8 bytes (header)
1407
+ .toString('ascii') // Convert buffer to ASCII string
1408
+ .replace(`${keyword}=`, ''); // Remove the keyword prefix
1409
+ // Determine and return the face function status
1410
+ return status.includes('0') ? 'No' : 'Yes';
1411
+ }
1412
+ catch (err) {
1413
+ // Log the error for debugging
1414
+ console.error('Error getting face function status:', err);
1415
+ // Re-throw the error to be handled by the caller
1416
+ throw err;
1417
+ }
1418
+ }
1419
+ async getSSR() {
1420
+ const keyword = '~SSR';
1421
+ try {
1422
+ // Execute the command to get the SSR value
1423
+ const data = await this.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1424
+ // Extract and process the SSR value from the response data
1425
+ // Remove the keyword prefix
1426
+ // Return the SSR value
1427
+ return data.slice(8) // Skip the first 8 bytes (header)
1428
+ .toString('ascii') // Convert buffer to ASCII string
1429
+ .replace(`${keyword}=`, '');
1430
+ }
1431
+ catch (err) {
1432
+ // Log the error for debugging
1433
+ console.error('Error getting SSR value:', err);
1434
+ // Re-throw the error to be handled by the caller
1435
+ throw err;
1436
+ }
1437
+ }
1438
+ async getFirmware() {
1439
+ try {
1440
+ // Execute the command to get firmware information
1441
+ const data = await this.executeCmd(1100, '');
1442
+ // Extract and return the firmware version from the response data
1443
+ return data.slice(8).toString('ascii'); // Skip the first 8 bytes (header) and convert to ASCII string
1444
+ }
1445
+ catch (err) {
1446
+ // Log the error for debugging
1447
+ console.error('Error getting firmware version:', err);
1448
+ // Re-throw the error to be handled by the caller
1449
+ throw err;
1450
+ }
1451
+ }
1452
+ async getTime() {
1453
+ try {
1454
+ // Execute the command to get the current time
1455
+ const response = await this.executeCmd(COMMANDS.CMD_GET_TIME, '');
1456
+ // Check if the response is valid
1457
+ if (!response || response.length < 12) {
1458
+ throw new Error('Invalid response received for time command');
1459
+ }
1460
+ // Extract and decode the time value from the response
1461
+ const timeValue = response.readUInt32LE(8); // Read 4 bytes starting at offset 8
1462
+ return timeParser.decode(timeValue); // Parse and return the decoded time
1463
+ }
1464
+ catch (err) {
1465
+ // Log the error for debugging
1466
+ console.error('Error getting time:', err);
1467
+ // Re-throw the error for the caller to handle
1468
+ throw err;
1469
+ }
1470
+ }
1471
+ async setTime(tm) {
1472
+ try {
1473
+ // Validate the input time
1474
+ if (!(tm instanceof Date) && typeof tm !== 'number') {
1475
+ throw new TypeError('Invalid time parameter. Must be a Date object or a timestamp.');
1476
+ }
1477
+ // Convert the input time to a Date object if it's not already
1478
+ const date = (tm instanceof Date) ? tm : new Date(tm);
1479
+ // Encode the time into the required format
1480
+ const encodedTime = timeParser.encode(date);
1481
+ // Create a buffer and write the encoded time
1482
+ const commandString = Buffer.alloc(32);
1483
+ commandString.writeUInt32LE(encodedTime, 0);
1484
+ // Send the command to set the time
1485
+ const time = await this.executeCmd(COMMANDS.CMD_SET_TIME, commandString);
1486
+ return !!time;
1487
+ }
1488
+ catch (err) {
1489
+ // Log the error for debugging
1490
+ console.error('Error setting time:', err);
1491
+ // Re-throw the error for the caller to handle
1492
+ throw err;
1493
+ }
1494
+ }
1495
+ async voiceTest() {
1496
+ try {
1497
+ // Define the command data for the voice test
1498
+ const commandData = Buffer.from('\x00\x00', 'binary');
1499
+ await this.executeCmd(COMMANDS.CMD_TESTVOICE, commandData);
1500
+ // Execute the command and return the result
1501
+ }
1502
+ catch (err) {
1503
+ // Log the error for debugging purposes
1504
+ console.error('Error executing voice test:', err);
1505
+ // Re-throw the error to be handled by the caller
1506
+ throw err;
1507
+ }
1508
+ }
1509
+ async setUser(uid, userid, name, password, role = 0, cardno = 0) {
1510
+ try {
1511
+ // Validate input parameters
1512
+ if (uid <= 0 || uid > 3000 ||
1513
+ userid.length > 9 ||
1514
+ name.length > 24 ||
1515
+ password.length > 8 ||
1516
+ typeof role !== 'number' ||
1517
+ cardno.toString().length > 10) {
1518
+ throw new Error('Invalid input parameters');
1519
+ }
1520
+ // Allocate and initialize the buffer
1521
+ const commandBuffer = Buffer.alloc(72);
1522
+ // Fill the buffer with user data
1523
+ commandBuffer.writeUInt16LE(uid, 0);
1524
+ commandBuffer.writeUInt16LE(role, 2);
1525
+ commandBuffer.write(password.padEnd(8, '\0'), 3, 8); // Ensure password is 8 bytes
1526
+ commandBuffer.write(name.padEnd(24, '\0'), 11, 24); // Ensure name is 24 bytes
1527
+ commandBuffer.writeUInt16LE(cardno, 35);
1528
+ commandBuffer.writeUInt32LE(0, 40); // Placeholder or reserved field
1529
+ commandBuffer.write(userid.padEnd(9, '\0'), 48, 9); // Ensure userid is 9 bytes
1530
+ // Send the command and return the result
1531
+ const created = await this.executeCmd(COMMANDS.CMD_USER_WRQ, commandBuffer);
1532
+ return !!created;
1533
+ }
1534
+ catch (err) {
1535
+ // Log error details for debugging
1536
+ console.error('Error setting user:', err);
1537
+ // Re-throw error for upstream handling
1538
+ throw err;
1539
+ }
1540
+ }
1541
+ async deleteUser(uid) {
1542
+ try {
1543
+ // Validate input parameter
1544
+ if (uid <= 0 || uid > 3000) {
1545
+ throw new Error('Invalid UID: must be between 1 and 3000');
1546
+ }
1547
+ // Allocate and initialize the buffer
1548
+ const commandBuffer = Buffer.alloc(72);
1549
+ // Write UID to the buffer
1550
+ commandBuffer.writeUInt16LE(uid, 0);
1551
+ // Send the delete command and return the result
1552
+ const deleted = await this.executeCmd(COMMANDS.CMD_DELETE_USER, commandBuffer);
1553
+ return !!deleted;
1554
+ }
1555
+ catch (err) {
1556
+ // Log error details for debugging
1557
+ console.error('Error deleting user:', err);
1558
+ // Re-throw error for upstream handling
1559
+ throw err;
1560
+ }
1561
+ }
1562
+ async getAttendanceSize() {
1563
+ try {
1564
+ // Execute command to get free sizes
1565
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, '');
1566
+ // Parse and return the attendance size
1567
+ return data.readUIntLE(40, 4); // Assuming data at offset 40 represents the attendance size
1568
+ }
1569
+ catch (err) {
1570
+ // Log error details for debugging
1571
+ console.error('Error getting attendance size:', err);
1572
+ // Re-throw the error to be handled by the caller
1573
+ throw err;
1574
+ }
1575
+ }
1576
+ // Clears the attendance logs on the device
1577
+ async clearAttendanceLog() {
1578
+ try {
1579
+ // Execute the command to clear attendance logs
1580
+ return await this.executeCmd(COMMANDS.CMD_CLEAR_ATTLOG, '');
1581
+ }
1582
+ catch (err) {
1583
+ // Log the error for debugging purposes
1584
+ console.error('Error clearing attendance log:', err);
1585
+ // Re-throw the error to be handled by the caller
1586
+ throw err;
1587
+ }
1588
+ }
1589
+ // Clears all data on the device
1590
+ async clearData() {
1591
+ try {
1592
+ // Execute the command to clear all data
1593
+ return await this.executeCmd(COMMANDS.CMD_CLEAR_DATA, '');
1594
+ }
1595
+ catch (err) {
1596
+ // Log the error for debugging purposes
1597
+ console.error('Error clearing data:', err);
1598
+ // Re-throw the error to be handled by the caller
1599
+ throw err;
1600
+ }
1601
+ }
1602
+ async getRealTimeLogs(cb = (realTimeLog) => { }) {
1603
+ this.replyId++; // Increment the reply ID for this request
1604
+ try {
1605
+ // Create a buffer with the command header to request real-time logs
1606
+ const buf = createTCPHeader(COMMANDS.CMD_REG_EVENT, this.sessionId, this.replyId, Buffer.from([0x01, 0x00, 0x00, 0x00]));
1607
+ // Send the request to the device
1608
+ this.socket.write(buf, null, (err) => {
1609
+ if (err) {
1610
+ // Log and reject the promise if there is an error writing to the socket
1611
+ console.error('Error sending real-time logs request:', err);
1612
+ throw err;
1613
+ }
1614
+ });
1615
+ // Ensure data listeners are added only once
1616
+ if (this.socket.listenerCount('data') === 0) {
1617
+ this.socket.on('data', (data) => {
1618
+ // Check if the data is an event and not just a regular response
1619
+ if (checkNotEventTCP(data)) {
1620
+ // Process the data if it is of the expected length
1621
+ if (data.length > 16) {
1622
+ // Decode and pass the log to the callback
1623
+ cb(decodeRecordRealTimeLog52(data));
1624
+ }
1625
+ }
1626
+ });
1627
+ }
1628
+ }
1629
+ catch (err) {
1630
+ // Handle errors and reject the promise
1631
+ console.error('Error getting real-time logs:', err);
1632
+ throw err;
1633
+ }
1634
+ }
1635
+ async getTemplates() {
1636
+ try {
1637
+ await this.freeData();
1638
+ await this.disableDevice();
1639
+ const Buffer = await this.readWithBuffer(REQUEST_DATA.GET_TEMPLATES);
1640
+ let templateData = Buffer.data.slice(4);
1641
+ let totalSize = Buffer.data.readUIntLE(0, 4);
1642
+ let templates = [];
1643
+ while (totalSize) {
1644
+ const buf = templateData.slice(0, 6);
1645
+ const size = buf.readUIntLE(0, 2);
1646
+ templates.push(new Finger(buf.readUIntLE(2, 2), buf.readUIntLE(4, 1), buf.readUIntLE(5, 1), templateData.slice(6, size)));
1647
+ templateData = templateData.slice(size);
1648
+ totalSize -= size;
1649
+ }
1650
+ return templates;
1651
+ }
1652
+ catch (err) {
1653
+ console.error('Error getting user templates: ', err);
1654
+ throw err;
1655
+ }
1656
+ finally {
1657
+ await this.enableDevice();
1658
+ await this.freeData();
1659
+ }
1660
+ }
1661
+ async refreshData() {
1662
+ try {
1663
+ const reply = await this.executeCmd(COMMANDS.CMD_REFRESHDATA, '');
1664
+ return !!reply;
1665
+ }
1666
+ catch (err) {
1667
+ console.error('Error getting user templates: ', err);
1668
+ throw err;
1669
+ }
1670
+ }
1671
+ async sendWithBuffer(buffer) {
1672
+ const MAX_CHUNK = 1024;
1673
+ const size = buffer.length;
1674
+ await this.freeData();
1675
+ const commandString = Buffer.alloc(4); // 'I' is 4 bytes
1676
+ commandString.writeUInt32LE(size, 0);
1677
+ try {
1678
+ const cmdResponse = await this.executeCmd(COMMANDS.CMD_PREPARE_DATA, commandString);
1679
+ // responds with 2000 = CMD_ACK_OK
1680
+ if (!cmdResponse) {
1681
+ throw new Error("Can't prepare data");
1682
+ }
1683
+ }
1684
+ catch (e) {
1685
+ console.error(e);
1686
+ }
1687
+ const remain = size % MAX_CHUNK;
1688
+ const packets = Math.floor((size - remain) / MAX_CHUNK);
1689
+ let start = 0;
1690
+ try {
1691
+ for (let i = 0; i < packets; i++) {
1692
+ const resp = await this.sendChunk(buffer.slice(start, start + MAX_CHUNK));
1693
+ if (resp) {
1694
+ start += MAX_CHUNK;
1695
+ if (i == packets - 1 && remain) {
1696
+ const lastPacket = await this.sendChunk(buffer.slice(start, start + remain));
1697
+ return lastPacket;
1698
+ }
1699
+ }
1700
+ }
1701
+ }
1702
+ catch (e) {
1703
+ console.error(e);
1704
+ }
1705
+ }
1706
+ async sendChunk(commandString) {
1707
+ try {
1708
+ return await new Promise((resolve, reject) => {
1709
+ resolve(this.executeCmd(COMMANDS.CMD_DATA, commandString));
1710
+ });
1711
+ }
1712
+ catch (e) {
1713
+ throw new ZkError(e, COMMANDS.CMD_DATA, this.ip);
1714
+ }
1715
+ }
1716
+ /**
1717
+ * save user and template
1718
+ *
1719
+ * @param {User | number | string} user - User class object | uid | user_id
1720
+ * @param {Finger[]} fingers - Array of finger class. `0 <= index <= 9`
1721
+ */
1722
+ async saveUserTemplate(user, fingers = []) {
1723
+ if (fingers.length > 9 || fingers.length == 0)
1724
+ throw new Error("maximum finger length is 10 and can't be empty");
1725
+ try {
1726
+ await this.disableDevice();
1727
+ const users = await this.getUsers();
1728
+ //check users exists
1729
+ if (!users.data.some(u => u.uid == user.uid || +u.user_id == +user.user_id))
1730
+ throw new Error("error validating user input");
1731
+ if (!(user instanceof User)) {
1732
+ let tusers = users.data.filter(x => x.uid === +user.uid);
1733
+ if (tusers.length === 1) {
1734
+ user = tusers[0];
1735
+ }
1736
+ else {
1737
+ tusers = users.data.filter(x => x.user_id === String(user));
1738
+ if (tusers.length === 1) {
1739
+ user = tusers[0];
1740
+ }
1741
+ else {
1742
+ throw new Error("Can't find user");
1743
+ }
1744
+ }
1745
+ }
1746
+ if (fingers instanceof Finger) {
1747
+ fingers = [fingers];
1748
+ }
1749
+ let fpack = Buffer.alloc(0);
1750
+ let table = Buffer.alloc(0);
1751
+ const fnum = 0x10;
1752
+ let tstart = 0;
1753
+ for (const finger of fingers) {
1754
+ const tfp = finger.repackOnly();
1755
+ const tableEntry = Buffer.alloc(11); // b=1, H=2, b=1, I=4 => 1+2+1+4=8? Wait, bHbI is 1+2+1+4=8 bytes
1756
+ tableEntry.writeInt8(2, 0);
1757
+ tableEntry.writeUInt16LE(user.uid, 1);
1758
+ tableEntry.writeInt8(fnum + finger.fid, 3);
1759
+ tableEntry.writeUInt32LE(tstart, 4);
1760
+ table = Buffer.concat([table, tableEntry]);
1761
+ tstart += tfp.length;
1762
+ fpack = Buffer.concat([fpack, tfp]);
1763
+ }
1764
+ let upack;
1765
+ if (this.userPacketSize === 28) {
1766
+ upack = user.repack29();
1767
+ }
1768
+ else {
1769
+ upack = user.repack73();
1770
+ }
1771
+ const head = Buffer.alloc(12); // III = 3*4 bytes
1772
+ head.writeUInt32LE(upack.length, 0);
1773
+ head.writeUInt32LE(table.length, 4);
1774
+ head.writeUInt32LE(fpack.length, 8);
1775
+ const packet = Buffer.concat([head, upack, table, fpack]);
1776
+ const bufferResponse = await this.sendWithBuffer(packet);
1777
+ const command = 110;
1778
+ const commandString = Buffer.alloc(8); // <IHH = I(4) + H(2) + H(2) = 8 bytes
1779
+ commandString.writeUInt32LE(12, 0);
1780
+ commandString.writeUInt16LE(0, 4);
1781
+ commandString.writeUInt16LE(8, 6);
1782
+ const cmdResponse = await this.executeCmd(command, commandString);
1783
+ if (this.verbose)
1784
+ console.log("finally bulk save user templates: \n", cmdResponse.readUInt16LE(0));
1785
+ }
1786
+ catch (error) {
1787
+ throw error;
1788
+ }
1789
+ finally {
1790
+ await this.refreshData();
1791
+ await this.enableDevice();
1792
+ }
1793
+ }
1794
+ async deleteFinger(uid, fid) {
1795
+ try {
1796
+ const buf = Buffer.alloc(4);
1797
+ buf.writeUInt16LE(uid, 0);
1798
+ buf.writeUint16LE(fid, 2);
1799
+ const reply = await this.executeCmd(COMMANDS.CMD_DELETE_USERTEMP, buf);
1800
+ return !!reply;
1801
+ }
1802
+ catch (error) {
1803
+ throw new Error("Can't save utemp");
1804
+ }
1805
+ finally {
1806
+ await this.refreshData();
1807
+ }
1808
+ }
1809
+ async enrollUser(uid, tempId, userId = '') {
1810
+ let done = false;
1811
+ try {
1812
+ //validate user exists
1813
+ const users = await this.getUsers();
1814
+ const filteredUsers = users.data.filter(x => x.uid === uid);
1815
+ if (filteredUsers.length >= 1) {
1816
+ userId = filteredUsers[0].user_id;
1817
+ }
1818
+ else {
1819
+ throw new Error("user not found");
1820
+ }
1821
+ const userBuf = Buffer.alloc(24);
1822
+ userBuf.write(userId.toString(), 0, 24, 'ascii');
1823
+ let commandString = Buffer.concat([
1824
+ userBuf,
1825
+ Buffer.from([tempId, 1])
1826
+ ]);
1827
+ const cancel = await this.cancelCapture();
1828
+ const cmdResponse = await this.executeCmd(COMMANDS.CMD_STARTENROLL, commandString);
1829
+ this.timeout = 60000; // 60 seconds timeout
1830
+ let attempts = 3;
1831
+ while (attempts > 0) {
1832
+ if (this.verbose)
1833
+ console.log(`A:${attempts} esperando primer regevent`);
1834
+ let dataRecv = await this.readSocket(17);
1835
+ await this.ackOk();
1836
+ if (dataRecv.length > 16) {
1837
+ const padded = Buffer.concat([dataRecv, Buffer.alloc(24 - dataRecv.length)]);
1838
+ const res = padded.readUInt16LE(16);
1839
+ if (this.verbose)
1840
+ console.log(`res ${res}`);
1841
+ if (res === 0 || res === 6 || res === 4) {
1842
+ if (this.verbose)
1843
+ console.log("posible timeout o reg Fallido");
1844
+ break;
1845
+ }
1846
+ }
1847
+ if (this.verbose)
1848
+ console.log(`A:${attempts} esperando 2do regevent`);
1849
+ dataRecv = await this.readSocket(17);
1850
+ await this.ackOk();
1851
+ if (this.verbose)
1852
+ console.log(dataRecv);
1853
+ if (dataRecv.length > 8) {
1854
+ const padded = Buffer.concat([dataRecv, Buffer.alloc(24 - dataRecv.length)]);
1855
+ const res = padded.readUInt16LE(16);
1856
+ if (this.verbose)
1857
+ console.log(`res ${res}`);
1858
+ if (res === 6 || res === 4) {
1859
+ if (this.verbose)
1860
+ console.log("posible timeout o reg Fallido");
1861
+ break;
1862
+ }
1863
+ else if (res === 0x64) {
1864
+ if (this.verbose)
1865
+ console.log("ok, continue?");
1866
+ attempts--;
1867
+ }
1868
+ }
1869
+ }
1870
+ if (attempts === 0) {
1871
+ const dataRecv = await this.readSocket(17);
1872
+ await this.ackOk();
1873
+ if (this.verbose)
1874
+ console.log(dataRecv.toString('hex'));
1875
+ const padded = Buffer.concat([dataRecv, Buffer.alloc(24 - dataRecv.length)]);
1876
+ let res = padded.readUInt16LE(16);
1877
+ if (this.verbose)
1878
+ console.log(`res ${res}`);
1879
+ if (res === 5) {
1880
+ if (this.verbose)
1881
+ console.log("finger duplicate");
1882
+ }
1883
+ if (res === 6 || res === 4) {
1884
+ if (this.verbose)
1885
+ console.log("posible timeout");
1886
+ }
1887
+ if (res === 0) {
1888
+ const size = padded.readUInt16LE(10);
1889
+ const pos = padded.readUInt16LE(12);
1890
+ if (this.verbose)
1891
+ console.log(`enroll ok ${size} ${pos}`);
1892
+ done = true;
1893
+ }
1894
+ }
1895
+ //this.__sock.setTimeout(this.__timeout);
1896
+ await this.regEvent(0); // TODO: test
1897
+ return done;
1898
+ }
1899
+ catch (error) {
1900
+ throw error;
1901
+ }
1902
+ finally {
1903
+ await this.cancelCapture();
1904
+ await this.verifyUser(undefined);
1905
+ }
1906
+ }
1907
+ async readSocket(length, cb = null) {
1908
+ let replyBufer = Buffer.from([]);
1909
+ let totalPackets = 0;
1910
+ return new Promise((resolve, reject) => {
1911
+ let timer = setTimeout(() => {
1912
+ internalCallback(replyBufer, new Error('TIMEOUT WHEN RECEIVING PACKET'));
1913
+ }, this.timeout);
1914
+ const internalCallback = (replyData, err = null) => {
1915
+ this.socket && this.socket.removeListener('data', onDataEnroll);
1916
+ timer && clearTimeout(timer);
1917
+ resolve({ data: replyData, err: err });
1918
+ };
1919
+ function onDataEnroll(data) {
1920
+ clearTimeout(timer);
1921
+ timer = setTimeout(() => {
1922
+ internalCallback(replyBufer, new Error(`TIME OUT !! ${totalPackets} PACKETS REMAIN !`));
1923
+ }, this.timeout);
1924
+ replyBufer = Buffer.concat([replyBufer, data], replyBufer.length + data.length);
1925
+ if (data.length == length) {
1926
+ internalCallback(data);
1927
+ }
1928
+ }
1929
+ this.socket.once('close', () => {
1930
+ internalCallback(replyBufer, new Error('Socket is disconnected unexpectedly'));
1931
+ });
1932
+ this.socket.on('data', onDataEnroll);
1933
+ }).catch((err) => {
1934
+ console.error("Promise Rejected:", err); // Log the rejection reason
1935
+ throw err; // Re-throw the error to be handled by the caller
1936
+ });
1937
+ }
1938
+ /**
1939
+ * Register events
1940
+ * @param {number} flags - Event flags
1941
+ * @returns {Promise<void>}
1942
+ * @throws {ZKErrorResponse} If registration fails
1943
+ */
1944
+ async regEvent(flags) {
1945
+ try {
1946
+ const commandString = Buffer.alloc(4); // 'I' format is 4 bytes
1947
+ commandString.writeUInt32LE(flags, 0); // Little-endian unsigned int
1948
+ const cmdResponse = await this.executeCmd(COMMANDS.CMD_REG_EVENT, commandString);
1949
+ if (this.verbose)
1950
+ console.log("regEvent: ", cmdResponse.readUInt16LE(0));
1951
+ }
1952
+ catch (e) {
1953
+ throw new ZkError(e, COMMANDS.CMD_REG_EVENT, this.ip);
1954
+ }
1955
+ }
1956
+ async ackOk() {
1957
+ try {
1958
+ const buf = createTCPHeader(COMMANDS.CMD_ACK_OK, this.sessionId, USHRT_MAX - 1, Buffer.from([]));
1959
+ this.socket.write(buf);
1960
+ }
1961
+ catch (e) {
1962
+ throw new ZkError(e, COMMANDS.CMD_ACK_OK, this.ip);
1963
+ }
1964
+ }
1965
+ async cancelCapture() {
1966
+ try {
1967
+ const reply = await this.executeCmd(COMMANDS.CMD_CANCELCAPTURE, '');
1968
+ return !!reply;
1969
+ }
1970
+ catch (e) {
1971
+ throw new ZkError(e, COMMANDS.CMD_CANCELCAPTURE, this.ip);
1972
+ }
1973
+ }
1974
+ async verifyUser(uid) {
1975
+ try {
1976
+ let command_string = '';
1977
+ if (uid) {
1978
+ command_string = Buffer.alloc(4);
1979
+ command_string.writeUInt32LE(uid, 0);
1980
+ }
1981
+ const reply = await this.executeCmd(COMMANDS.CMD_STARTVERIFY, command_string);
1982
+ if (this.verbose)
1983
+ console.log(reply.readUInt16LE(0));
1984
+ return !!reply;
1985
+ }
1986
+ catch (error) {
1987
+ console.error(error);
1988
+ }
1989
+ }
1990
+ async restartDevice() {
1991
+ try {
1992
+ await this.executeCmd(COMMANDS.CMD_RESTART, '');
1993
+ }
1994
+ catch (e) {
1995
+ throw new ZkError(e, COMMANDS.CMD_RESTART, this.ip);
1996
+ }
1997
+ }
1998
+ }
1999
+
2000
+ class ZUDP {
2001
+ ip;
2002
+ port;
2003
+ timeout;
2004
+ socket;
2005
+ sessionId;
2006
+ replyId;
2007
+ inport;
2008
+ comm_key;
2009
+ constructor(ip, port, timeout, inport, comm_key = 0) {
2010
+ this.ip = ip;
2011
+ this.port = port;
2012
+ this.timeout = timeout;
2013
+ this.socket = null;
2014
+ this.sessionId = null;
2015
+ this.replyId = 0;
2016
+ this.inport = inport;
2017
+ this.comm_key = comm_key;
2018
+ }
2019
+ createSocket(cbError, cbClose) {
2020
+ return new Promise((resolve, reject) => {
2021
+ this.socket = dgram.createSocket('udp4');
2022
+ this.socket.setMaxListeners(Infinity);
2023
+ this.socket.once('error', (err) => {
2024
+ this.socket = null;
2025
+ reject(err);
2026
+ if (cbError)
2027
+ cbError(err);
2028
+ });
2029
+ this.socket.once('close', () => {
2030
+ this.socket = null;
2031
+ if (cbClose)
2032
+ cbClose('udp');
2033
+ });
2034
+ this.socket.once('listening', () => {
2035
+ resolve(this.socket);
2036
+ });
2037
+ try {
2038
+ this.socket.bind(this.inport);
2039
+ }
2040
+ catch (err) {
2041
+ this.socket = null;
2042
+ reject(err);
2043
+ if (cbError)
2044
+ cbError(err);
2045
+ }
2046
+ });
2047
+ }
2048
+ async connect() {
2049
+ try {
2050
+ let reply = await this.executeCmd(COMMANDS.CMD_CONNECT, '');
2051
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
2052
+ return true;
2053
+ }
2054
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_UNAUTH) {
2055
+ const hashedCommkey = authKey(this.comm_key, this.sessionId);
2056
+ reply = await this.executeCmd(COMMANDS.CMD_AUTH, hashedCommkey);
2057
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
2058
+ return true;
2059
+ }
2060
+ else {
2061
+ throw new Error("Authentication error");
2062
+ }
2063
+ }
2064
+ else {
2065
+ throw new Error('NO_REPLY_ON_CMD_CONNECT');
2066
+ }
2067
+ }
2068
+ catch (err) {
2069
+ console.error('Error in connect method:', err);
2070
+ throw err;
2071
+ }
2072
+ }
2073
+ async closeSocket() {
2074
+ return new Promise((resolve, reject) => {
2075
+ if (!this.socket) {
2076
+ resolve(true);
2077
+ return;
2078
+ }
2079
+ const timeout = 2000;
2080
+ const timer = setTimeout(() => {
2081
+ console.warn('Socket close timeout');
2082
+ resolve(true);
2083
+ }, timeout);
2084
+ this.socket.removeAllListeners('message');
2085
+ // @ts-ignore
2086
+ this.socket.close((err) => {
2087
+ clearTimeout(timer);
2088
+ if (err) {
2089
+ console.error('Error closing socket:', err);
2090
+ reject(err);
2091
+ }
2092
+ else {
2093
+ resolve(true);
2094
+ }
2095
+ this.socket = null;
2096
+ });
2097
+ });
2098
+ }
2099
+ writeMessage(msg, connect) {
2100
+ return new Promise((resolve, reject) => {
2101
+ if (!this.socket) {
2102
+ reject(new Error('Socket not initialized'));
2103
+ return;
2104
+ }
2105
+ let sendTimeoutId;
2106
+ const onMessage = (data) => {
2107
+ clearTimeout(sendTimeoutId);
2108
+ this.socket.removeListener('message', onMessage);
2109
+ resolve(data);
2110
+ };
2111
+ this.socket.once('message', onMessage);
2112
+ this.socket.send(msg, 0, msg.length, this.port, this.ip, (err) => {
2113
+ if (err) {
2114
+ this.socket.removeListener('message', onMessage);
2115
+ reject(err);
2116
+ return;
2117
+ }
2118
+ if (this.timeout) {
2119
+ sendTimeoutId = setTimeout(() => {
2120
+ this.socket.removeListener('message', onMessage);
2121
+ reject(new Error('TIMEOUT_ON_WRITING_MESSAGE'));
2122
+ }, connect ? 2000 : this.timeout);
2123
+ }
2124
+ });
2125
+ });
2126
+ }
2127
+ requestData(msg) {
2128
+ return new Promise((resolve, reject) => {
2129
+ if (!this.socket) {
2130
+ reject(new Error('Socket not initialized'));
2131
+ return;
2132
+ }
2133
+ let sendTimeoutId;
2134
+ let responseTimeoutId;
2135
+ const handleOnData = (data) => {
2136
+ if (checkNotEventUDP(data))
2137
+ return;
2138
+ clearTimeout(sendTimeoutId);
2139
+ clearTimeout(responseTimeoutId);
2140
+ this.socket.removeListener('message', handleOnData);
2141
+ resolve(data);
2142
+ };
2143
+ const onReceiveTimeout = () => {
2144
+ this.socket.removeListener('message', handleOnData);
2145
+ reject(new Error('TIMEOUT_ON_RECEIVING_REQUEST_DATA'));
2146
+ };
2147
+ this.socket.on('message', handleOnData);
2148
+ this.socket.send(msg, 0, msg.length, this.port, this.ip, (err) => {
2149
+ if (err) {
2150
+ this.socket.removeListener('message', handleOnData);
2151
+ reject(err);
2152
+ return;
2153
+ }
2154
+ responseTimeoutId = setTimeout(onReceiveTimeout, this.timeout);
2155
+ });
2156
+ sendTimeoutId = setTimeout(() => {
2157
+ this.socket.removeListener('message', handleOnData);
2158
+ reject(new Error('TIMEOUT_IN_RECEIVING_RESPONSE_AFTER_REQUESTING_DATA'));
2159
+ }, this.timeout);
2160
+ });
2161
+ }
2162
+ async executeCmd(command, data) {
2163
+ try {
2164
+ if (command === COMMANDS.CMD_CONNECT) {
2165
+ this.sessionId = 0;
2166
+ this.replyId = 0;
2167
+ }
2168
+ else {
2169
+ this.replyId++;
2170
+ }
2171
+ const buf = createUDPHeader(command, this.sessionId, this.replyId, data);
2172
+ const reply = await this.writeMessage(buf, command === COMMANDS.CMD_CONNECT || command === COMMANDS.CMD_EXIT);
2173
+ if (reply && reply.length > 0) {
2174
+ if (command === COMMANDS.CMD_CONNECT) {
2175
+ this.sessionId = reply.readUInt16LE(4);
2176
+ }
2177
+ }
2178
+ return reply;
2179
+ }
2180
+ catch (err) {
2181
+ console.error(`Error executing command ${command}:`, err);
2182
+ throw err;
2183
+ }
2184
+ }
2185
+ async sendChunkRequest(start, size) {
2186
+ this.replyId++;
2187
+ const reqData = Buffer.alloc(8);
2188
+ reqData.writeUInt32LE(start, 0);
2189
+ reqData.writeUInt32LE(size, 4);
2190
+ const buf = createUDPHeader(COMMANDS.CMD_DATA_RDY, this.sessionId, this.replyId, reqData);
2191
+ try {
2192
+ await new Promise((resolve, reject) => {
2193
+ this.socket.send(buf, 0, buf.length, this.port, this.ip, (err) => {
2194
+ if (err) {
2195
+ log(`[UDP][SEND_CHUNK_REQUEST] Error sending chunk request: ${err.message}`);
2196
+ reject(err);
2197
+ }
2198
+ else {
2199
+ resolve();
2200
+ }
2201
+ });
2202
+ });
2203
+ }
2204
+ catch (error) {
2205
+ log(`[UDP][SEND_CHUNK_REQUEST] Exception: ${error.message}`);
2206
+ throw error;
2207
+ }
2208
+ }
2209
+ async readWithBuffer(reqData, cb = null) {
2210
+ this.replyId++;
2211
+ const buf = createUDPHeader(COMMANDS.CMD_DATA_WRRQ, this.sessionId, this.replyId, reqData);
2212
+ try {
2213
+ const reply = await this.requestData(buf);
2214
+ const header = decodeUDPHeader(reply.subarray(0, 8));
2215
+ switch (header.commandId) {
2216
+ case COMMANDS.CMD_DATA:
2217
+ return { data: reply.subarray(8), err: null };
2218
+ case COMMANDS.CMD_ACK_OK:
2219
+ case COMMANDS.CMD_PREPARE_DATA:
2220
+ return await this.handleChunkedData(reply, header.commandId, cb);
2221
+ default:
2222
+ throw new Error('ERROR_IN_UNHANDLE_CMD ' + exportErrorMessage(header.commandId));
2223
+ }
2224
+ }
2225
+ catch (err) {
2226
+ return { data: null, err: err };
2227
+ }
2228
+ }
2229
+ async handleChunkedData(reply, commandId, cb) {
2230
+ return new Promise((resolve) => {
2231
+ const recvData = reply.subarray(8);
2232
+ const size = recvData.readUIntLE(1, 4);
2233
+ let totalBuffer = Buffer.from([]);
2234
+ const timeout = 3000;
2235
+ let timer = setTimeout(() => {
2236
+ this.socket.removeListener('message', handleOnData);
2237
+ resolve({ data: null, err: new Error('TIMEOUT WHEN RECEIVING PACKET') });
2238
+ }, timeout);
2239
+ const internalCallback = (replyData, err = null) => {
2240
+ this.socket.removeListener('message', handleOnData);
2241
+ clearTimeout(timer);
2242
+ resolve({ data: err ? null : replyData, err });
2243
+ };
2244
+ const handleOnData = (reply) => {
2245
+ if (checkNotEventUDP(reply))
2246
+ return;
2247
+ clearTimeout(timer);
2248
+ timer = setTimeout(() => {
2249
+ internalCallback(totalBuffer, new Error(`TIMEOUT !! ${(size - totalBuffer.length) / size} % REMAIN !`));
2250
+ }, timeout);
2251
+ const header = decodeUDPHeader(reply);
2252
+ switch (header.commandId) {
2253
+ case COMMANDS.CMD_PREPARE_DATA:
2254
+ break;
2255
+ case COMMANDS.CMD_DATA:
2256
+ totalBuffer = Buffer.concat([totalBuffer, reply.subarray(8)]);
2257
+ cb && cb(totalBuffer.length, size);
2258
+ break;
2259
+ case COMMANDS.CMD_ACK_OK:
2260
+ if (totalBuffer.length === size) {
2261
+ internalCallback(totalBuffer);
2262
+ }
2263
+ break;
2264
+ default:
2265
+ internalCallback(Buffer.from([]), new Error('ERROR_IN_UNHANDLE_CMD ' + exportErrorMessage(header.commandId)));
2266
+ }
2267
+ };
2268
+ this.socket.on('message', handleOnData);
2269
+ const chunkCount = Math.ceil(size / MAX_CHUNK);
2270
+ for (let i = 0; i < chunkCount; i++) {
2271
+ const start = i * MAX_CHUNK;
2272
+ const chunkSize = (i === chunkCount - 1) ? size % MAX_CHUNK : MAX_CHUNK;
2273
+ this.sendChunkRequest(start, chunkSize).catch(err => {
2274
+ internalCallback(Buffer.from([]), err);
2275
+ });
2276
+ }
2277
+ });
2278
+ }
2279
+ async getUsers() {
2280
+ try {
2281
+ if (this.socket) {
2282
+ await this.freeData();
2283
+ }
2284
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_USERS);
2285
+ if (this.socket) {
2286
+ await this.freeData();
2287
+ }
2288
+ const USER_PACKET_SIZE = 28;
2289
+ let userData = data.data?.subarray(4) || Buffer.from([]);
2290
+ const users = [];
2291
+ while (userData.length >= USER_PACKET_SIZE) {
2292
+ const user = decodeUserData28(userData.subarray(0, USER_PACKET_SIZE));
2293
+ users.push(user);
2294
+ userData = userData.subarray(USER_PACKET_SIZE);
2295
+ }
2296
+ return { data: users };
2297
+ }
2298
+ catch (err) {
2299
+ throw new Error(err.message);
2300
+ }
2301
+ }
2302
+ async getAttendances(callbackInProcess) {
2303
+ try {
2304
+ if (this.socket) {
2305
+ await this.freeData();
2306
+ }
2307
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_ATTENDANCE_LOGS);
2308
+ if (this.socket) {
2309
+ await this.freeData();
2310
+ }
2311
+ const RECORD_PACKET_SIZE = 16;
2312
+ let recordData = data.data?.subarray(4) || Buffer.from([]);
2313
+ const records = [];
2314
+ while (recordData.length >= RECORD_PACKET_SIZE) {
2315
+ const record = decodeRecordData16(recordData.subarray(0, RECORD_PACKET_SIZE));
2316
+ records.push({ ...record, ip: this.ip });
2317
+ recordData = recordData.subarray(RECORD_PACKET_SIZE);
2318
+ }
2319
+ return { data: records, err: data.err };
2320
+ }
2321
+ catch (err) {
2322
+ return { data: [], err: err };
2323
+ }
2324
+ }
2325
+ async freeData() {
2326
+ try {
2327
+ const resp = await this.executeCmd(COMMANDS.CMD_FREE_DATA, Buffer.alloc(0));
2328
+ return !!resp;
2329
+ }
2330
+ catch (err) {
2331
+ console.error('Error freeing data:', err);
2332
+ throw err;
2333
+ }
2334
+ }
2335
+ async getInfo() {
2336
+ try {
2337
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, Buffer.alloc(0));
2338
+ return {
2339
+ userCounts: data.readUIntLE(24, 4),
2340
+ logCounts: data.readUIntLE(40, 4),
2341
+ logCapacity: data.readUIntLE(72, 4)
2342
+ };
2343
+ }
2344
+ catch (err) {
2345
+ console.error('Error retrieving info:', err);
2346
+ throw err;
2347
+ }
2348
+ }
2349
+ async getTime() {
2350
+ try {
2351
+ const response = await this.executeCmd(COMMANDS.CMD_GET_TIME, Buffer.alloc(0));
2352
+ const timeValue = response.readUInt32LE(8);
2353
+ return timeParser.decode(timeValue);
2354
+ }
2355
+ catch (err) {
2356
+ console.error('Error retrieving time:', err);
2357
+ throw err;
2358
+ }
2359
+ }
2360
+ async setTime(tm) {
2361
+ try {
2362
+ const commandBuffer = Buffer.alloc(32);
2363
+ commandBuffer.writeUInt32LE(timeParser.encode(new Date(tm)), 0);
2364
+ await this.executeCmd(COMMANDS.CMD_SET_TIME, commandBuffer);
2365
+ return true;
2366
+ }
2367
+ catch (err) {
2368
+ console.error('Error setting time:', err);
2369
+ throw err;
2370
+ }
2371
+ }
2372
+ async clearAttendanceLog() {
2373
+ try {
2374
+ return await this.executeCmd(COMMANDS.CMD_CLEAR_ATTLOG, Buffer.alloc(0));
2375
+ }
2376
+ catch (err) {
2377
+ console.error('Error clearing attendance log:', err);
2378
+ throw err;
2379
+ }
2380
+ }
2381
+ async clearData() {
2382
+ try {
2383
+ return await this.executeCmd(COMMANDS.CMD_CLEAR_DATA, Buffer.alloc(0));
2384
+ }
2385
+ catch (err) {
2386
+ console.error('Error clearing data:', err);
2387
+ throw err;
2388
+ }
2389
+ }
2390
+ async disableDevice() {
2391
+ try {
2392
+ const resp = await this.executeCmd(COMMANDS.CMD_DISABLEDEVICE, REQUEST_DATA.DISABLE_DEVICE);
2393
+ return !!resp;
2394
+ }
2395
+ catch (err) {
2396
+ console.error('Error disabling device:', err);
2397
+ throw err;
2398
+ }
2399
+ }
2400
+ async enableDevice() {
2401
+ try {
2402
+ const resp = await this.executeCmd(COMMANDS.CMD_ENABLEDEVICE, Buffer.alloc(0));
2403
+ return !!resp;
2404
+ }
2405
+ catch (err) {
2406
+ console.error('Error enabling device:', err);
2407
+ throw err;
2408
+ }
2409
+ }
2410
+ async disconnect() {
2411
+ try {
2412
+ await this.executeCmd(COMMANDS.CMD_EXIT, Buffer.alloc(0));
2413
+ }
2414
+ catch (err) {
2415
+ console.error('Error executing disconnect command:', err);
2416
+ }
2417
+ try {
2418
+ await this.closeSocket();
2419
+ }
2420
+ catch (err) {
2421
+ console.error('Error closing the socket:', err);
2422
+ }
2423
+ }
2424
+ async getRealTimeLogs(cb = () => { }) {
2425
+ this.replyId++;
2426
+ const buf = createUDPHeader(COMMANDS.CMD_REG_EVENT, this.sessionId, this.replyId, REQUEST_DATA.GET_REAL_TIME_EVENT);
2427
+ try {
2428
+ this.socket.send(buf, 0, buf.length, this.port, this.ip, (err) => {
2429
+ if (err) {
2430
+ console.error('Error sending UDP message:', err);
2431
+ return;
2432
+ }
2433
+ console.log('UDP message sent successfully');
2434
+ });
2435
+ }
2436
+ catch (err) {
2437
+ console.error('Error during send operation:', err);
2438
+ return;
2439
+ }
2440
+ const handleMessage = (data) => {
2441
+ if (!checkNotEventUDP(data))
2442
+ return;
2443
+ if (data.length === 18) {
2444
+ cb(decodeRecordRealTimeLog18(data));
2445
+ }
2446
+ };
2447
+ if (this.socket.listenerCount('message') === 0) {
2448
+ this.socket.on('message', handleMessage);
2449
+ }
2450
+ else {
2451
+ console.warn('Multiple message listeners detected. Ensure only one listener is attached.');
2452
+ }
2453
+ }
2454
+ }
2455
+
2456
+ class Zklib {
2457
+ set connectionType(value) {
2458
+ this._connectionType = value;
2459
+ }
2460
+ _connectionType = null;
2461
+ ztcp;
2462
+ zudp;
2463
+ interval = null;
2464
+ timer = null;
2465
+ isBusy = false;
2466
+ ip;
2467
+ comm_key;
2468
+ get connectionType() {
2469
+ return this._connectionType;
2470
+ }
2471
+ /**
2472
+ * Creates a new Zkteco device connection instance
2473
+ * @param ip IP address of device
2474
+ * @param port Port number of device
2475
+ * @param timeout Connection timeout in milliseconds
2476
+ * @param inport Required only for UDP connection (default: 10000)
2477
+ * @param comm_key Communication key of device (default: 0)
2478
+ * @param verbose Console log some data
2479
+ */
2480
+ constructor(ip, port = 4370, timeout = 5000, inport = 10000, comm_key = 0, verbose = false) {
2481
+ this.ip = ip;
2482
+ this.comm_key = comm_key;
2483
+ this.ztcp = new ZTCP(ip, port, timeout, comm_key, verbose);
2484
+ this.zudp = new ZUDP(ip, port, timeout, inport);
2485
+ }
2486
+ async functionWrapper(tcpCallback, udpCallback, command) {
2487
+ try {
2488
+ switch (this._connectionType) {
2489
+ case 'tcp':
2490
+ if (this.ztcp && this.ztcp.socket) {
2491
+ return await tcpCallback();
2492
+ }
2493
+ else {
2494
+ throw new ZkError(new Error(`TCP socket isn't connected!`), `[TCP] ${command}`, this.ip);
2495
+ }
2496
+ case 'udp':
2497
+ if (this.zudp && this.zudp.socket) {
2498
+ return await udpCallback();
2499
+ }
2500
+ else {
2501
+ throw new ZkError(new Error(`UDP socket isn't connected!`), `[UDP] ${command}`, this.ip);
2502
+ }
2503
+ default:
2504
+ throw new ZkError(new Error(`Unsupported connection type or socket isn't connected!`), '', this.ip);
2505
+ }
2506
+ }
2507
+ catch (err) {
2508
+ throw new ZkError(err, `[${this._connectionType?.toUpperCase()}] ${command}`, this.ip);
2509
+ }
2510
+ }
2511
+ async createSocket(cbErr, cbClose) {
2512
+ try {
2513
+ if (this.ztcp.socket) {
2514
+ try {
2515
+ await this.ztcp.connect();
2516
+ console.log('TCP reconnection successful');
2517
+ this._connectionType = 'tcp';
2518
+ return true;
2519
+ }
2520
+ catch (err) {
2521
+ throw new ZkError(err, 'TCP CONNECT', this.ip);
2522
+ }
2523
+ }
2524
+ else {
2525
+ try {
2526
+ await this.ztcp.createSocket(cbErr, cbClose);
2527
+ await this.ztcp.connect();
2528
+ console.log('TCP connection successful');
2529
+ this._connectionType = 'tcp';
2530
+ return true;
2531
+ }
2532
+ catch (err) {
2533
+ throw new ZkError(err, 'TCP CONNECT', this.ip);
2534
+ }
2535
+ }
2536
+ }
2537
+ catch (err) {
2538
+ try {
2539
+ if (this.ztcp.socket)
2540
+ await this.ztcp.disconnect();
2541
+ }
2542
+ catch (disconnectErr) {
2543
+ console.error('Error disconnecting TCP:', disconnectErr);
2544
+ }
2545
+ if (err.code !== ERROR_TYPES.ECONNREFUSED) {
2546
+ throw new ZkError(err, 'TCP CONNECT', this.ip);
2547
+ }
2548
+ try {
2549
+ if (!this.zudp.socket) {
2550
+ await this.zudp.createSocket(cbErr, cbClose);
2551
+ }
2552
+ await this.zudp.connect();
2553
+ console.log('UDP connection successful');
2554
+ this._connectionType = 'udp';
2555
+ return true;
2556
+ }
2557
+ catch (err) {
2558
+ if (err.message !== 'EADDRINUSE') {
2559
+ this._connectionType = null;
2560
+ try {
2561
+ await this.zudp.disconnect();
2562
+ }
2563
+ catch (disconnectErr) {
2564
+ console.error('Error disconnecting UDP:', disconnectErr);
2565
+ }
2566
+ throw new ZkError(err, 'UDP CONNECT', this.ip);
2567
+ }
2568
+ this._connectionType = 'udp';
2569
+ return true;
2570
+ }
2571
+ }
2572
+ }
2573
+ async getUsers() {
2574
+ return this.functionWrapper(() => this.ztcp.getUsers(), () => this.zudp.getUsers(), 'GET_USERS');
2575
+ }
2576
+ async getTime() {
2577
+ return this.functionWrapper(() => this.ztcp.getTime(), () => this.zudp.getTime(), 'GET_TIME');
2578
+ }
2579
+ async setTime(t) {
2580
+ return this.functionWrapper(() => this.ztcp.setTime(t), () => this.zudp.setTime(t), 'SET_TIME');
2581
+ }
2582
+ async voiceTest() {
2583
+ return this.functionWrapper(() => this.ztcp.voiceTest(), async () => { throw new Error('UDP voice test not supported'); }, 'VOICE_TEST');
2584
+ }
2585
+ async getProductTime() {
2586
+ return this.functionWrapper(() => this.ztcp.getProductTime(), async () => { throw new Error('UDP get product time not supported'); }, 'GET_PRODUCT_TIME');
2587
+ }
2588
+ async getVendor() {
2589
+ return this.functionWrapper(() => this.ztcp.getVendor(), async () => { throw new Error('UDP get vendor not supported'); }, 'GET_VENDOR');
2590
+ }
2591
+ async getMacAddress() {
2592
+ return this.functionWrapper(() => this.ztcp.getMacAddress(), async () => { throw new Error('UDP get MAC address not supported'); }, 'GET_MAC_ADDRESS');
2593
+ }
2594
+ async getSerialNumber() {
2595
+ return this.functionWrapper(() => this.ztcp.getSerialNumber(), async () => { throw new Error('UDP get serial number not supported'); }, 'GET_SERIAL_NUMBER');
2596
+ }
2597
+ async getDeviceVersion() {
2598
+ return this.functionWrapper(() => this.ztcp.getDeviceVersion(), async () => { throw new Error('UDP get device version not supported'); }, 'GET_DEVICE_VERSION');
2599
+ }
2600
+ async getDeviceName() {
2601
+ return this.functionWrapper(() => this.ztcp.getDeviceName(), async () => { throw new Error('UDP get device name not supported'); }, 'GET_DEVICE_NAME');
2602
+ }
2603
+ async getPlatform() {
2604
+ return this.functionWrapper(() => this.ztcp.getPlatform(), async () => { throw new Error('UDP get platform not supported'); }, 'GET_PLATFORM');
2605
+ }
2606
+ async getOS() {
2607
+ return this.functionWrapper(() => this.ztcp.getOS(), async () => { throw new Error('UDP get OS not supported'); }, 'GET_OS');
2608
+ }
2609
+ async getWorkCode() {
2610
+ return this.functionWrapper(() => this.ztcp.getWorkCode(), async () => { throw new Error('UDP get work code not supported'); }, 'GET_WORK_CODE');
2611
+ }
2612
+ async getPIN() {
2613
+ return this.functionWrapper(() => this.ztcp.getPIN(), async () => { throw new Error('UDP get PIN not supported'); }, 'GET_PIN');
2614
+ }
2615
+ async getFaceOn() {
2616
+ return this.functionWrapper(() => this.ztcp.getFaceOn(), async () => { throw new Error('UDP get face on not supported'); }, 'GET_FACE_ON');
2617
+ }
2618
+ async getSSR() {
2619
+ return this.functionWrapper(() => this.ztcp.getSSR(), async () => { throw new Error('UDP get SSR not supported'); }, 'GET_SSR');
2620
+ }
2621
+ async getFirmware() {
2622
+ return this.functionWrapper(() => this.ztcp.getFirmware(), async () => { throw new Error('UDP get firmware not supported'); }, 'GET_FIRMWARE');
2623
+ }
2624
+ async setUser(uid, userid, name, password, role = 0, cardno = 0) {
2625
+ return this.functionWrapper(() => this.ztcp.setUser(uid, userid, name, password, role, cardno), async () => { throw new Error('UDP set user not supported'); }, 'SET_USER');
2626
+ }
2627
+ async deleteUser(uid) {
2628
+ return this.functionWrapper(() => this.ztcp.deleteUser(uid), async () => { throw new Error('UDP delete user not supported'); }, 'DELETE_USER');
2629
+ }
2630
+ async getAttendanceSize() {
2631
+ return this.functionWrapper(() => this.ztcp.getAttendanceSize(), async () => { throw new Error('UDP get attendance size not supported'); }, 'GET_ATTENDANCE_SIZE');
2632
+ }
2633
+ async getAttendances(cb) {
2634
+ return this.functionWrapper(() => this.ztcp.getAttendances(cb), () => this.zudp.getAttendances(cb), 'GET_ATTENDANCES');
2635
+ }
2636
+ async getRealTimeLogs(cb) {
2637
+ return this.functionWrapper(() => this.ztcp.getRealTimeLogs(cb), () => this.zudp.getRealTimeLogs(cb), 'GET_REAL_TIME_LOGS');
2638
+ }
2639
+ async getTemplates() {
2640
+ return this.functionWrapper(() => this.ztcp.getTemplates(), async () => { throw new Error('UDP get templates not supported'); }, 'GET_TEMPLATES');
2641
+ }
2642
+ async saveUserTemplate(user, fingers = []) {
2643
+ return await this.functionWrapper(async () => await this.ztcp.saveUserTemplate(user, fingers), async () => { throw new Error('UDP save user template not supported'); }, 'SAVE_USER_TEMPLATE');
2644
+ }
2645
+ async deleteFinger(uid, fid) {
2646
+ if (fid > 9 || 0 > fid)
2647
+ throw new Error("fid params out of index");
2648
+ if (uid > 3000 || uid < 1)
2649
+ throw new Error("fid params out of index");
2650
+ return this.functionWrapper(() => this.ztcp.deleteFinger(uid, fid), async () => { throw new Error('UDP delete finger not supported'); }, 'DELETE_FINGER');
2651
+ }
2652
+ async enrollUser(uid, temp_id, user_id) {
2653
+ if (temp_id < 0 || temp_id > 9)
2654
+ throw new Error("temp_id out of range 0-9");
2655
+ if (uid < 1 || uid > 3000)
2656
+ throw new Error("uid out of range 1-3000");
2657
+ return this.functionWrapper(() => this.ztcp.enrollUser(uid, temp_id, user_id), async () => { throw new Error('UDP enroll user not supported'); }, 'ENROLL_USER');
2658
+ }
2659
+ async verifyUser(uid) {
2660
+ return this.functionWrapper(() => this.ztcp.verifyUser(uid), async () => { throw new Error('UDP verify user not supported'); }, 'VERIFY_USER');
2661
+ }
2662
+ async restartDevice() {
2663
+ return this.functionWrapper(() => this.ztcp.restartDevice(), async () => { throw new Error('UDP restart device not supported'); }, 'RESTART_DEVICE');
2664
+ }
2665
+ async getSizes() {
2666
+ return this.functionWrapper(() => this.ztcp.getSizes(), () => this.zudp.getInfo(), 'GET_SIZES');
2667
+ }
2668
+ async disconnect() {
2669
+ return this.functionWrapper(() => this.ztcp.disconnect(), () => this.zudp.disconnect(), 'DISCONNECT');
2670
+ }
2671
+ async freeData() {
2672
+ return this.functionWrapper(() => this.ztcp.freeData(), () => this.zudp.freeData(), 'FREE_DATA');
2673
+ }
2674
+ async disableDevice() {
2675
+ return this.functionWrapper(() => this.ztcp.disableDevice(), () => this.zudp.disableDevice(), 'DISABLE_DEVICE');
2676
+ }
2677
+ async enableDevice() {
2678
+ return this.functionWrapper(() => this.ztcp.enableDevice(), () => this.zudp.enableDevice(), 'ENABLE_DEVICE');
2679
+ }
2680
+ async getInfo() {
2681
+ return this.functionWrapper(() => this.ztcp.getInfo(), () => this.zudp.getInfo(), 'GET_INFO');
2682
+ }
2683
+ async clearAttendanceLog() {
2684
+ return this.functionWrapper(() => this.ztcp.clearAttendanceLog(), () => this.zudp.clearAttendanceLog(), 'CLEAR_ATTENDANCE_LOG');
2685
+ }
2686
+ async clearData() {
2687
+ return this.functionWrapper(() => this.ztcp.clearData(), () => this.zudp.clearData(), 'CLEAR_DATA');
2688
+ }
2689
+ async executeCmd(command, data = '') {
2690
+ return this.functionWrapper(() => this.ztcp.executeCmd(command, data), () => this.zudp.executeCmd(command, data), 'EXECUTE_CMD');
2691
+ }
2692
+ }
2693
+
2694
+ export { Zklib as default };