zklib-ts 1.0.7 → 1.0.8

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.
package/dist/index.es.js CHANGED
@@ -1,7 +1,3479 @@
1
- Object.defineProperty(exports, "__esModule", { value: true });
2
- const ztcp_1 = require("./ztcp");
3
- const zudp_1 = require("./zudp");
4
- const handler_1 = require("./exceptions/handler");
1
+ import { Socket } from 'net';
2
+ import { appendFile } from 'fs';
3
+ import * as dgram from 'node:dgram';
4
+
5
+ var COMMANDS;
6
+ (function (COMMANDS) {
7
+ COMMANDS[COMMANDS["CMD_ACK_DATA"] = 2002] = "CMD_ACK_DATA";
8
+ /** There was an error when processing the request.*/
9
+ COMMANDS[COMMANDS["CMD_ACK_ERROR"] = 2001] = "CMD_ACK_ERROR";
10
+ COMMANDS[COMMANDS["CMD_ACK_ERROR_CMD"] = 65533] = "CMD_ACK_ERROR_CMD";
11
+ COMMANDS[COMMANDS["CMD_ACK_ERROR_DATA"] = 65531] = "CMD_ACK_ERROR_DATA";
12
+ COMMANDS[COMMANDS["CMD_ACK_ERROR_INIT"] = 65532] = "CMD_ACK_ERROR_INIT";
13
+ /** [0xD0, 0x07] The request was processed sucessfully. */
14
+ COMMANDS[COMMANDS["CMD_ACK_OK"] = 2000] = "CMD_ACK_OK";
15
+ COMMANDS[COMMANDS["CMD_ACK_REPEAT"] = 2004] = "CMD_ACK_REPEAT";
16
+ COMMANDS[COMMANDS["CMD_ACK_RETRY"] = 2003] = "CMD_ACK_RETRY";
17
+ /** [0xD5, 0x07] Connection not authorized. */
18
+ COMMANDS[COMMANDS["CMD_ACK_UNAUTH"] = 2005] = "CMD_ACK_UNAUTH";
19
+ /** Received unknown command. */
20
+ COMMANDS[COMMANDS["CMD_ACK_UNKNOWN"] = 65535] = "CMD_ACK_UNKNOWN";
21
+ /** Request attendance log. */
22
+ COMMANDS[COMMANDS["CMD_ATTLOG_RRQ"] = 13] = "CMD_ATTLOG_RRQ";
23
+ /** [0x4E, 0x04] Request to begin session using commkey. */
24
+ COMMANDS[COMMANDS["CMD_AUTH"] = 1102] = "CMD_AUTH";
25
+ /** [0x3e, 0x00] Disable normal authentication of users. */
26
+ COMMANDS[COMMANDS["CMD_CANCELCAPTURE"] = 62] = "CMD_CANCELCAPTURE";
27
+ /** Capture fingerprint picture. */
28
+ COMMANDS[COMMANDS["CMD_CAPTUREFINGER"] = 1009] = "CMD_CAPTUREFINGER";
29
+ /** Capture the entire image. */
30
+ COMMANDS[COMMANDS["CMD_CAPTUREIMAGE"] = 1012] = "CMD_CAPTUREIMAGE";
31
+ /** Change transmission speed. */
32
+ COMMANDS[COMMANDS["CMD_CHANGE_SPEED"] = 1101] = "CMD_CHANGE_SPEED";
33
+ /** [0x77, 0x00] Get checksum of machine's buffer. */
34
+ COMMANDS[COMMANDS["CMD_CHECKSUM_BUFFER"] = 119] = "CMD_CHECKSUM_BUFFER";
35
+ /** Restore access control to default. */
36
+ COMMANDS[COMMANDS["CMD_CLEAR_ACC"] = 32] = "CMD_CLEAR_ACC";
37
+ /** Clears admins privileges. */
38
+ COMMANDS[COMMANDS["CMD_CLEAR_ADMIN"] = 20] = "CMD_CLEAR_ADMIN";
39
+ /** Delete attendance record. */
40
+ COMMANDS[COMMANDS["CMD_CLEAR_ATTLOG"] = 15] = "CMD_CLEAR_ATTLOG";
41
+ /** Delete data. */
42
+ COMMANDS[COMMANDS["CMD_CLEAR_DATA"] = 14] = "CMD_CLEAR_DATA";
43
+ /** Clear screen captions. */
44
+ COMMANDS[COMMANDS["CMD_CLEAR_LCD"] = 67] = "CMD_CLEAR_LCD";
45
+ /** Delete operations log. */
46
+ COMMANDS[COMMANDS["CMD_CLEAR_OPLOG"] = 33] = "CMD_CLEAR_OPLOG";
47
+ /** [0xE8, 0x03] Begin connection. */
48
+ COMMANDS[COMMANDS["CMD_CONNECT"] = 1000] = "CMD_CONNECT";
49
+ /** [0xDD, 0x05] Data packet. */
50
+ COMMANDS[COMMANDS["CMD_DATA"] = 1501] = "CMD_DATA";
51
+ /** Indicates that it is ready to receive data. */
52
+ COMMANDS[COMMANDS["CMD_DATA_RDY"] = 1504] = "CMD_DATA_RDY";
53
+ /** Read/Write a large data set. */
54
+ COMMANDS[COMMANDS["CMD_DATA_WRRQ"] = 1503] = "CMD_DATA_WRRQ";
55
+ /** Read saved data. */
56
+ COMMANDS[COMMANDS["CMD_DB_RRQ"] = 7] = "CMD_DB_RRQ";
57
+ /** Deletes fingerprint template. */
58
+ COMMANDS[COMMANDS["CMD_DEL_FPTMP"] = 134] = "CMD_DEL_FPTMP";
59
+ /** Delete short message. */
60
+ COMMANDS[COMMANDS["CMD_DELETE_SMS"] = 72] = "CMD_DELETE_SMS";
61
+ /** Delete user short message. */
62
+ COMMANDS[COMMANDS["CMD_DELETE_UDATA"] = 74] = "CMD_DELETE_UDATA";
63
+ /** Delete user. */
64
+ COMMANDS[COMMANDS["CMD_DELETE_USER"] = 18] = "CMD_DELETE_USER";
65
+ /** Delete user fingerprint template. */
66
+ COMMANDS[COMMANDS["CMD_DELETE_USERTEMP"] = 19] = "CMD_DELETE_USERTEMP";
67
+ /** Disables fingerprint, rfid reader and keyboard. */
68
+ COMMANDS[COMMANDS["CMD_DISABLEDEVICE"] = 1003] = "CMD_DISABLEDEVICE";
69
+ /** Get door state. */
70
+ COMMANDS[COMMANDS["CMD_DOORSTATE_RRQ"] = 75] = "CMD_DOORSTATE_RRQ";
71
+ /** Clear Mifare card. */
72
+ COMMANDS[COMMANDS["CMD_EMPTY_MIFARE"] = 78] = "CMD_EMPTY_MIFARE";
73
+ /** Enables the ":" in screen clock. */
74
+ COMMANDS[COMMANDS["CMD_ENABLE_CLOCK"] = 57] = "CMD_ENABLE_CLOCK";
75
+ /** Change machine state to "normal work". */
76
+ COMMANDS[COMMANDS["CMD_ENABLEDEVICE"] = 1002] = "CMD_ENABLEDEVICE";
77
+ /** [0xE9, 0x03] Disconnect. */
78
+ COMMANDS[COMMANDS["CMD_EXIT"] = 1001] = "CMD_EXIT";
79
+ /** [0xDE, 0x05] Release buffer used for data transmission. */
80
+ COMMANDS[COMMANDS["CMD_FREE_DATA"] = 1502] = "CMD_FREE_DATA";
81
+ /** Request machine status (remaining space). */
82
+ COMMANDS[COMMANDS["CMD_GET_FREE_SIZES"] = 50] = "CMD_GET_FREE_SIZES";
83
+ /** Request max size for users id. */
84
+ COMMANDS[COMMANDS["CMD_GET_PINWIDTH"] = 69] = "CMD_GET_PINWIDTH";
85
+ /** Request machine time. */
86
+ COMMANDS[COMMANDS["CMD_GET_TIME"] = 201] = "CMD_GET_TIME";
87
+ COMMANDS[COMMANDS["CMD_GET_USERTEMP"] = 88] = "CMD_GET_USERTEMP";
88
+ /** Request the firmware edition. */
89
+ COMMANDS[COMMANDS["CMD_GET_VERSION"] = 1100] = "CMD_GET_VERSION";
90
+ /** Get group timezone. */
91
+ COMMANDS[COMMANDS["CMD_GRPTZ_RRQ"] = 25] = "CMD_GRPTZ_RRQ";
92
+ /** Set group timezone. */
93
+ COMMANDS[COMMANDS["CMD_GRPTZ_WRQ"] = 26] = "CMD_GRPTZ_WRQ";
94
+ /** Read operations log. */
95
+ COMMANDS[COMMANDS["CMD_OPLOG_RRQ"] = 34] = "CMD_OPLOG_RRQ";
96
+ /** Read configuration value of the machine. */
97
+ COMMANDS[COMMANDS["CMD_OPTIONS_RRQ"] = 11] = "CMD_OPTIONS_RRQ";
98
+ /** Change configuration value of the machine. */
99
+ COMMANDS[COMMANDS["CMD_OPTIONS_WRQ"] = 12] = "CMD_OPTIONS_WRQ";
100
+ /** Shut-down machine. */
101
+ COMMANDS[COMMANDS["CMD_POWEROFF"] = 1005] = "CMD_POWEROFF";
102
+ /** [0xDC, 0x05] Prepare for data transmission. */
103
+ COMMANDS[COMMANDS["CMD_PREPARE_DATA"] = 1500] = "CMD_PREPARE_DATA";
104
+ /** [0xF5, 0x03] Refresh the machine stored data. */
105
+ COMMANDS[COMMANDS["CMD_REFRESHDATA"] = 1013] = "CMD_REFRESHDATA";
106
+ /** Refresh the configuration parameters. */
107
+ COMMANDS[COMMANDS["CMD_REFRESHOPTION"] = 1014] = "CMD_REFRESHOPTION";
108
+ /** Realtime events. */
109
+ COMMANDS[COMMANDS["CMD_REG_EVENT"] = 500] = "CMD_REG_EVENT";
110
+ /** Restart machine. */
111
+ COMMANDS[COMMANDS["CMD_RESTART"] = 1004] = "CMD_RESTART";
112
+ /** Change machine state to "awaken". */
113
+ COMMANDS[COMMANDS["CMD_RESUME"] = 1007] = "CMD_RESUME";
114
+ /** Set machine time. */
115
+ COMMANDS[COMMANDS["CMD_SET_TIME"] = 202] = "CMD_SET_TIME";
116
+ /** Change machine state to "idle". */
117
+ COMMANDS[COMMANDS["CMD_SLEEP"] = 1006] = "CMD_SLEEP";
118
+ /** Download short message. */
119
+ COMMANDS[COMMANDS["CMD_SMS_RRQ"] = 71] = "CMD_SMS_RRQ";
120
+ /** Upload short message. */
121
+ COMMANDS[COMMANDS["CMD_SMS_WRQ"] = 70] = "CMD_SMS_WRQ";
122
+ /** [0x3d, 0x00] Start enroll procedure. */
123
+ COMMANDS[COMMANDS["CMD_STARTENROLL"] = 61] = "CMD_STARTENROLL";
124
+ /** [0x3c, 0x00] Set the machine to authentication state. */
125
+ COMMANDS[COMMANDS["CMD_STARTVERIFY"] = 60] = "CMD_STARTVERIFY";
126
+ /** Query state. */
127
+ COMMANDS[COMMANDS["CMD_STATE_RRQ"] = 64] = "CMD_STATE_RRQ";
128
+ /** Test if fingerprint exists. */
129
+ COMMANDS[COMMANDS["CMD_TEST_TEMP"] = 1011] = "CMD_TEST_TEMP";
130
+ /** Test voice. */
131
+ COMMANDS[COMMANDS["CMD_TESTVOICE"] = 1017] = "CMD_TESTVOICE";
132
+ /** [0x77, 0x00] Transfer fp template from buffer. */
133
+ COMMANDS[COMMANDS["CMD_TMP_WRITE"] = 87] = "CMD_TMP_WRITE";
134
+ /** Get device timezones. */
135
+ COMMANDS[COMMANDS["CMD_TZ_RRQ"] = 27] = "CMD_TZ_RRQ";
136
+ /** Set device timezones. */
137
+ COMMANDS[COMMANDS["CMD_TZ_WRQ"] = 28] = "CMD_TZ_WRQ";
138
+ /** Set user short message. */
139
+ COMMANDS[COMMANDS["CMD_UDATA_WRQ"] = 73] = "CMD_UDATA_WRQ";
140
+ /** Get group combination to unlock. */
141
+ COMMANDS[COMMANDS["CMD_ULG_RRQ"] = 29] = "CMD_ULG_RRQ";
142
+ /** Set group combination to unlock. */
143
+ COMMANDS[COMMANDS["CMD_ULG_WRQ"] = 30] = "CMD_ULG_WRQ";
144
+ /** Unlock door for a specified amount of time. */
145
+ COMMANDS[COMMANDS["CMD_UNLOCK"] = 31] = "CMD_UNLOCK";
146
+ /** Upload user data. */
147
+ COMMANDS[COMMANDS["CMD_USER_WRQ"] = 8] = "CMD_USER_WRQ";
148
+ /** Read user group. */
149
+ COMMANDS[COMMANDS["CMD_USERGRP_RRQ"] = 21] = "CMD_USERGRP_RRQ";
150
+ /** Set user group. */
151
+ COMMANDS[COMMANDS["CMD_USERGRP_WRQ"] = 22] = "CMD_USERGRP_WRQ";
152
+ /** [0x09, 0x00] Read user fingerprint template. */
153
+ COMMANDS[COMMANDS["CMD_USERTEMP_RRQ"] = 9] = "CMD_USERTEMP_RRQ";
154
+ /** Upload user fingerprint template. */
155
+ COMMANDS[COMMANDS["CMD_USERTEMP_WRQ"] = 10] = "CMD_USERTEMP_WRQ";
156
+ /** Get user timezones. */
157
+ COMMANDS[COMMANDS["CMD_USERTZ_RRQ"] = 23] = "CMD_USERTZ_RRQ";
158
+ /** Set the user timezones. */
159
+ COMMANDS[COMMANDS["CMD_USERTZ_WRQ"] = 24] = "CMD_USERTZ_WRQ";
160
+ /** Read verification style of a given user. */
161
+ COMMANDS[COMMANDS["CMD_VERIFY_RRQ"] = 80] = "CMD_VERIFY_RRQ";
162
+ /** Change verification style of a given user. */
163
+ COMMANDS[COMMANDS["CMD_VERIFY_WRQ"] = 79] = "CMD_VERIFY_WRQ";
164
+ /** Prints chars to the device screen. */
165
+ COMMANDS[COMMANDS["CMD_WRITE_LCD"] = 66] = "CMD_WRITE_LCD";
166
+ /** Write data to Mifare card. */
167
+ COMMANDS[COMMANDS["CMD_WRITE_MIFARE"] = 76] = "CMD_WRITE_MIFARE";
168
+ })(COMMANDS || (COMMANDS = {}));
169
+ var RTEvent;
170
+ (function (RTEvent) {
171
+ /** Triggered alarm. */
172
+ RTEvent[RTEvent["EF_ALARM"] = 512] = "EF_ALARM";
173
+ /** Attendance entry. */
174
+ RTEvent[RTEvent["EF_ATTLOG"] = 1] = "EF_ATTLOG";
175
+ /** Pressed keyboard key. */
176
+ RTEvent[RTEvent["EF_BUTTON"] = 16] = "EF_BUTTON";
177
+ /** Upload user data. */
178
+ RTEvent[RTEvent["EF_ENROLLFINGER"] = 8] = "EF_ENROLLFINGER";
179
+ /** Enrolled user. */
180
+ RTEvent[RTEvent["EF_ENROLLUSER"] = 4] = "EF_ENROLLUSER";
181
+ /** Pressed finger. */
182
+ RTEvent[RTEvent["EF_FINGER"] = 2] = "EF_FINGER";
183
+ /** Fingerprint score in enroll procedure. */
184
+ RTEvent[RTEvent["EF_FPFTR"] = 256] = "EF_FPFTR";
185
+ /** Restore access control to default. */
186
+ RTEvent[RTEvent["EF_UNLOCK"] = 32] = "EF_UNLOCK";
187
+ /** Registered user placed finger. */
188
+ RTEvent[RTEvent["EF_VERIFY"] = 128] = "EF_VERIFY";
189
+ })(RTEvent || (RTEvent = {}));
190
+ var DISCOVERED_CMD;
191
+ (function (DISCOVERED_CMD) {
192
+ /** [0x7f, 0x13] */
193
+ DISCOVERED_CMD[DISCOVERED_CMD["UNKNOWN"] = 4991] = "UNKNOWN";
194
+ /** Returned when the Finger id not exists in the user uid, when attempting to download single finger template */
195
+ DISCOVERED_CMD[DISCOVERED_CMD["FID_NOT_FOUND"] = 4993] = "FID_NOT_FOUND";
196
+ /** [0x87, 0x13] i guess is an error reply code, is returned when attempint to read options ~isABCPinEnable and ~T9FunOn */
197
+ DISCOVERED_CMD[DISCOVERED_CMD["UNKNOWN_OR_NOT_SUPPORTED"] = 4999] = "UNKNOWN_OR_NOT_SUPPORTED";
198
+ })(DISCOVERED_CMD || (DISCOVERED_CMD = {}));
199
+ var Constants;
200
+ (function (Constants) {
201
+ Constants[Constants["USHRT_MAX"] = 65535] = "USHRT_MAX";
202
+ Constants[Constants["MAX_CHUNK"] = 65472] = "MAX_CHUNK";
203
+ Constants[Constants["MACHINE_PREPARE_DATA_1"] = 20560] = "MACHINE_PREPARE_DATA_1";
204
+ Constants[Constants["MACHINE_PREPARE_DATA_2"] = 32130] = "MACHINE_PREPARE_DATA_2";
205
+ })(Constants || (Constants = {}));
206
+ const REQUEST_DATA = {
207
+ START_TAG: Buffer.from([0x50, 0x50, 0x82, 0x7d]),
208
+ DISABLE_DEVICE: Buffer.from([0, 0, 0, 0]),
209
+ GET_REAL_TIME_EVENT: Buffer.from([0x01, 0x00, 0x00, 0x00]),
210
+ GET_ATTENDANCE_LOGS: Buffer.from([0x01, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
211
+ GET_USERS: Buffer.from([0x01, 0x09, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
212
+ GET_TEMPLATES: Buffer.from([0x01, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
213
+ };
214
+
215
+ /**
216
+ * Error types for device communication
217
+ */
218
+ const ERROR_TYPES = {
219
+ ECONNRESET: 'ECONNRESET',
220
+ ECONNREFUSED: 'ECONNREFUSED'};
221
+ /**
222
+ * Custom error class for device communication errors
223
+ */
224
+ class ZkError {
225
+ err;
226
+ ip;
227
+ command;
228
+ /**
229
+ * Creates a new ZkError instance
230
+ * @param err The error object
231
+ * @param command The command that caused the error
232
+ * @param ip The IP address of the device
233
+ */
234
+ constructor(err, command, ip) {
235
+ this.err = err;
236
+ this.ip = ip;
237
+ this.command = command;
238
+ }
239
+ /**
240
+ * Gets a user-friendly error message
241
+ * @returns A formatted error message
242
+ */
243
+ toast() {
244
+ if (this.err.code === ERROR_TYPES.ECONNRESET) {
245
+ return 'Another device is connecting to the device so the connection is interrupted';
246
+ }
247
+ else if (this.err.code === ERROR_TYPES.ECONNREFUSED) {
248
+ return 'IP of the device is refused';
249
+ }
250
+ return this.err.message;
251
+ }
252
+ /**
253
+ * Gets detailed error information
254
+ * @returns An object containing error details
255
+ */
256
+ getError() {
257
+ return {
258
+ err: {
259
+ message: this.err.message,
260
+ code: this.err.code
261
+ },
262
+ ip: this.ip,
263
+ command: this.command
264
+ };
265
+ }
266
+ }
267
+
268
+ const parseCurrentTime = () => {
269
+ const currentTime = new Date();
270
+ return {
271
+ year: currentTime.getFullYear(),
272
+ month: currentTime.getMonth() + 1,
273
+ day: currentTime.getDate(),
274
+ hour: currentTime.getHours(),
275
+ second: currentTime.getSeconds()
276
+ };
277
+ };
278
+ const log = (text) => {
279
+ const currentTime = parseCurrentTime();
280
+ const fileName = `${currentTime.day}`.padStart(2, '0') +
281
+ `${currentTime.month}`.padStart(2, '0') +
282
+ `${currentTime.year}.err.log`;
283
+ const logMessage = `\n [${currentTime.hour}:${currentTime.second}] ${text}`;
284
+ appendFile(fileName, logMessage, () => { });
285
+ };
286
+
287
+ /**
288
+ * Represents a User as is from ZkDevice and contain methods
289
+ * */
290
+ class User {
291
+ uid;
292
+ name;
293
+ privilege;
294
+ password;
295
+ group_id;
296
+ user_id;
297
+ card;
298
+ /**
299
+ * Creates a new User instance
300
+ * @param uid User ID
301
+ * @param name User name
302
+ * @param privilege Privilege level
303
+ * @param password User password (default: "")
304
+ * @param group_id Group ID (default: "")
305
+ * @param user_id Alternate user ID (default: "")
306
+ * @param card Card number (default: 0)
307
+ */
308
+ constructor(uid, name, privilege, password = '', group_id = '', user_id = '', card = 0) {
309
+ this.uid = uid;
310
+ this.name = name;
311
+ this.privilege = privilege;
312
+ this.password = password;
313
+ this.group_id = group_id;
314
+ this.user_id = user_id;
315
+ this.card = card;
316
+ }
317
+ ensureEncoding(string) {
318
+ try {
319
+ return decodeURIComponent(string);
320
+ }
321
+ catch (e) {
322
+ return unescape(string);
323
+ }
324
+ }
325
+ repack29() {
326
+ // Pack format: <BHB5s8sIxBhI (total 29 bytes)
327
+ const buf = Buffer.alloc(29);
328
+ let offset = 0;
329
+ buf.writeUInt8(2, offset);
330
+ offset += 1;
331
+ buf.writeUInt16LE(this.uid, offset);
332
+ offset += 2;
333
+ buf.writeUInt8(this.privilege, offset);
334
+ offset += 1;
335
+ const passwordBuf = Buffer.from(this.ensureEncoding(this.password));
336
+ passwordBuf.copy(buf, offset, 0, 5);
337
+ offset += 5;
338
+ const nameBuf = Buffer.from(this.ensureEncoding(this.name));
339
+ nameBuf.copy(buf, offset, 0, 8);
340
+ offset += 8;
341
+ buf.writeUInt32LE(this.card, offset);
342
+ offset += 4;
343
+ offset += 1; // padding byte
344
+ buf.writeUInt8(0, offset);
345
+ offset += 1;
346
+ buf.writeUInt32LE(parseInt(this.user_id) || 0, offset);
347
+ return buf;
348
+ }
349
+ repack73() {
350
+ // Pack format: <BHB8s24sIB7sx24s (total 73 bytes)
351
+ const buf = Buffer.alloc(73);
352
+ let offset = 0;
353
+ buf.writeUInt8(2, offset);
354
+ offset += 1;
355
+ buf.writeUInt16LE(this.uid, offset);
356
+ offset += 2;
357
+ buf.writeUInt8(this.privilege, offset);
358
+ offset += 1;
359
+ const passwordBuf = Buffer.from(this.ensureEncoding(this.password));
360
+ passwordBuf.copy(buf, offset, 0, 8);
361
+ offset += 8;
362
+ const nameBuf = Buffer.from(this.ensureEncoding(this.name));
363
+ nameBuf.copy(buf, offset, 0, 24);
364
+ offset += 24;
365
+ buf.writeUInt32LE(this.card, offset);
366
+ offset += 4;
367
+ buf.writeUInt8(1, offset);
368
+ offset += 1;
369
+ const groupBuf = Buffer.from(this.ensureEncoding(String(this.group_id)));
370
+ groupBuf.copy(buf, offset, 0, 7);
371
+ offset += 8;
372
+ const userIdBuf = Buffer.from(this.ensureEncoding(String(this.user_id)));
373
+ userIdBuf.copy(buf, offset, 0, 24);
374
+ return buf;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Represents an Attendance Records
380
+ */
381
+ class Attendance {
382
+ /** Internal serial number for the user */
383
+ sn;
384
+ /** User ID/Pin stored as a string */
385
+ user_id;
386
+ /** Verification type */
387
+ type;
388
+ /** Time of the attendance event */
389
+ record_time;
390
+ /** Verify state */
391
+ state;
392
+ ip;
393
+ constructor(sn, user_id, type, record_time, state) {
394
+ this.sn = sn;
395
+ this.user_id = user_id;
396
+ this.type = type || undefined;
397
+ this.record_time = record_time;
398
+ this.state = state || undefined;
399
+ }
400
+ }
401
+
402
+ const parseHexToTime = (hex) => {
403
+ const time = {
404
+ year: hex.readUIntLE(0, 1),
405
+ month: hex.readUIntLE(1, 1),
406
+ date: hex.readUIntLE(2, 1),
407
+ hour: hex.readUIntLE(3, 1),
408
+ minute: hex.readUIntLE(4, 1),
409
+ second: hex.readUIntLE(5, 1),
410
+ };
411
+ return new Date(2000 + time.year, time.month - 1, time.date, time.hour, time.minute, time.second);
412
+ };
413
+ const createChkSum = (buf) => {
414
+ let chksum = 0;
415
+ for (let i = 0; i < buf.length; i += 2) {
416
+ if (i === buf.length - 1) {
417
+ chksum += buf[i];
418
+ }
419
+ else {
420
+ chksum += buf.readUInt16LE(i);
421
+ }
422
+ chksum %= Constants.USHRT_MAX;
423
+ }
424
+ chksum = Constants.USHRT_MAX - chksum - 1;
425
+ return chksum;
426
+ };
427
+ const createUDPHeader = (command, sessionId, replyId, data) => {
428
+ const dataBuffer = Buffer.from(data);
429
+ const buf = Buffer.alloc(8 + dataBuffer.length);
430
+ buf.writeUInt16LE(command, 0);
431
+ buf.writeUInt16LE(0, 2);
432
+ buf.writeUInt16LE(sessionId, 4);
433
+ buf.writeUInt16LE(replyId, 6);
434
+ dataBuffer.copy(buf, 8);
435
+ const chksum2 = createChkSum(buf);
436
+ buf.writeUInt16LE(chksum2, 2);
437
+ replyId = (replyId + 1) % Constants.USHRT_MAX;
438
+ buf.writeUInt16LE(replyId, 6);
439
+ return buf;
440
+ };
441
+ const createTCPHeader = (command, sessionId, replyId, data) => {
442
+ const buf = createUDPHeader(command, sessionId, replyId, data);
443
+ const prefixBuf = Buffer.from([
444
+ 0x50, 0x50, 0x82, 0x7d, 0x13, 0x00, 0x00, 0x00,
445
+ ]);
446
+ prefixBuf.writeUInt16LE(buf.length, 4);
447
+ return Buffer.concat([prefixBuf, buf]);
448
+ };
449
+ const removeTcpHeader = (buf) => {
450
+ if (buf.length < 8) {
451
+ return buf;
452
+ }
453
+ if (buf.compare(Buffer.from([0x50, 0x50, 0x82, 0x7d]), 0, 4, 0, 4) !== 0) {
454
+ return buf;
455
+ }
456
+ return buf.slice(8);
457
+ };
458
+ const parseTimeToDate = (time) => {
459
+ const second = time % 60;
460
+ time = (time - second) / 60;
461
+ const minute = time % 60;
462
+ time = (time - minute) / 60;
463
+ const hour = time % 24;
464
+ time = (time - hour) / 24;
465
+ const day = (time % 31) + 1;
466
+ time = (time - (day - 1)) / 31;
467
+ const month = time % 12;
468
+ time = (time - month) / 12;
469
+ const year = time + 2000;
470
+ return new Date(Date.UTC(year, month, day, hour, minute, second));
471
+ };
472
+ const decodeUserData28 = (userData) => {
473
+ return {
474
+ uid: userData.readUIntLE(0, 2),
475
+ privilege: userData.readUIntLE(2, 1),
476
+ name: userData
477
+ .slice(8, 8 + 8)
478
+ .toString("ascii")
479
+ .split("\0")
480
+ .shift() || "",
481
+ user_id: userData.readUIntLE(24, 4).toString(),
482
+ };
483
+ };
484
+ const decodeUserData72 = (userData) => {
485
+ return new User(userData.readUIntLE(0, 2), userData.slice(11).toString("ascii").split("\0").shift() || "", userData.readUIntLE(2, 1), userData
486
+ .subarray(3, 3 + 8)
487
+ .toString("ascii")
488
+ .split("\0")
489
+ .shift() || "", userData.readUIntLE(39, 1), userData
490
+ .slice(48, 48 + 9)
491
+ .toString("ascii")
492
+ .split("\0")
493
+ .shift() || "", userData.readUIntLE(35, 4));
494
+ };
495
+ const decodeRecordData40 = (recordData) => {
496
+ return new Attendance(recordData.readUIntLE(0, 2), recordData
497
+ .slice(2, 2 + 9)
498
+ .toString("ascii")
499
+ .split("\0")
500
+ .shift() || "", recordData.readUIntLE(26, 1), parseTimeToDate(recordData.readUInt32LE(27)), recordData.readUIntLE(31, 1));
501
+ };
502
+ const decodeRecordData16 = (recordData) => {
503
+ return {
504
+ user_id: recordData.readUIntLE(0, 2).toString(),
505
+ record_time: parseTimeToDate(recordData.readUInt32LE(4)),
506
+ };
507
+ };
508
+ const decodeRecordRealTimeLog18 = (recordData) => {
509
+ const user_id = recordData.readUIntLE(8, 1).toString();
510
+ const record_time = parseHexToTime(recordData.subarray(12, 18));
511
+ return { user_id, record_time };
512
+ };
513
+ const decodeUDPHeader = (header) => {
514
+ return {
515
+ commandId: header.readUIntLE(0, 2),
516
+ checkSum: header.readUIntLE(2, 2),
517
+ sessionId: header.readUIntLE(4, 2),
518
+ replyId: header.readUIntLE(6, 2),
519
+ };
520
+ };
521
+ const decodeTCPHeader = (header) => {
522
+ const recvData = header.subarray(8);
523
+ const payloadSize = header.readUIntLE(4, 2);
524
+ return {
525
+ commandId: recvData.readUIntLE(0, 2),
526
+ checkSum: recvData.readUIntLE(2, 2),
527
+ sessionId: recvData.readUIntLE(4, 2),
528
+ replyId: recvData.readUIntLE(6, 2),
529
+ payloadSize,
530
+ };
531
+ };
532
+ const exportErrorMessage = (commandValue) => {
533
+ const keys = Object.keys(COMMANDS);
534
+ for (const key of keys) {
535
+ if (COMMANDS[key] === commandValue) {
536
+ return key.toString();
537
+ }
538
+ }
539
+ return "AN UNKNOWN ERROR";
540
+ };
541
+ const isRTEvent = (event) => Object.values(RTEvent).includes(event);
542
+ const checkNotEventTCP = (data) => {
543
+ try {
544
+ const cleanedData = removeTcpHeader(data);
545
+ const commandId = cleanedData.readUIntLE(0, 2);
546
+ const event = cleanedData.readUIntLE(4, 2);
547
+ return isRTEvent(event) && commandId === COMMANDS.CMD_REG_EVENT;
548
+ }
549
+ catch (err) {
550
+ log(`[228] : ${err.toString()} ,${data.toString("hex")} `);
551
+ return false;
552
+ }
553
+ };
554
+ const checkNotEventUDP = (data) => {
555
+ const { commandId } = decodeUDPHeader(data.subarray(0, 8));
556
+ return commandId === COMMANDS.CMD_REG_EVENT;
557
+ };
558
+ const decodeRTEvent = (data) => {
559
+ const header = decodeTCPHeader(data);
560
+ console.log(header);
561
+ const event = header.sessionId;
562
+ const recvData = data.subarray(16);
563
+ const build = {
564
+ alarm4bytes: function (data) {
565
+ return {
566
+ alarm_type: data.readUintLE(0, 4),
567
+ alarm_cause: data.readUintLE(4, 2),
568
+ user_uid: data.readUintLE(6, 2),
569
+ match_type: data.readUintLE(8, 4),
570
+ };
571
+ },
572
+ enrolledFinger: function (data) {
573
+ return {
574
+ result: data.readUIntLE(0, 2),
575
+ size: data.readUintLE(2, 2),
576
+ pin: data.subarray(4, 4 + 9).toString("ascii"),
577
+ fid: data.readUIntLE(1, 13),
578
+ };
579
+ },
580
+ fingerScore: function (data) {
581
+ return { score: data.readUintLE(0, 1) };
582
+ },
583
+ };
584
+ switch (event) {
585
+ case RTEvent.EF_FINGER:
586
+ return { event };
587
+ case RTEvent.EF_FPFTR:
588
+ return { event, payload: build.fingerScore(recvData) };
589
+ default:
590
+ console.log("utils linea 284");
591
+ break;
592
+ }
593
+ };
594
+ const makeKey = (key, sessionId) => {
595
+ let k = 0;
596
+ for (let i = 0; i < 32; i++) {
597
+ if ((key & (1 << i)) !== 0) {
598
+ k = (k << 1) | 1;
599
+ }
600
+ else {
601
+ k = k << 1;
602
+ }
603
+ }
604
+ k += sessionId;
605
+ let hex = k.toString(16).padStart(8, "0");
606
+ const response = new Uint8Array(4);
607
+ let index = 3;
608
+ while (hex.length > 0) {
609
+ response[index] = parseInt(hex.substring(0, 2), 16);
610
+ index--;
611
+ hex = hex.substring(2);
612
+ }
613
+ response[0] ^= "Z".charCodeAt(0);
614
+ response[1] ^= "K".charCodeAt(0);
615
+ response[2] ^= "S".charCodeAt(0);
616
+ response[3] ^= "O".charCodeAt(0);
617
+ let finalKey = response[0] +
618
+ (response[1] << 8) +
619
+ (response[2] << 16) +
620
+ (response[3] << 24);
621
+ const swp = finalKey >>> 16;
622
+ finalKey = (finalKey << 16) | swp;
623
+ return finalKey >>> 0;
624
+ };
625
+ const authKey = (comKey, sessionId) => {
626
+ const k = makeKey(comKey, sessionId) >>> 0;
627
+ const rand = Math.floor(Math.random() * 256);
628
+ let hex = k.toString(16).padStart(8, "0");
629
+ const response = new Uint8Array(4);
630
+ let index = 3;
631
+ while (index >= 0) {
632
+ response[index] = parseInt(hex.substring(0, 2), 16);
633
+ index--;
634
+ hex = hex.substring(2);
635
+ }
636
+ response[0] ^= rand;
637
+ response[1] ^= rand;
638
+ response[2] = rand;
639
+ response[3] ^= rand;
640
+ return Array.from(response);
641
+ };
642
+ /** Some Tcp packets receibed by the socket client can be merged in one single data event by the OS, and we need to split to handle correctly */
643
+ const splitTcpPackets = (data) => {
644
+ const packets = [];
645
+ let unProcessed = data;
646
+ while (unProcessed.length > 0) {
647
+ const headers = decodeTCPHeader(unProcessed);
648
+ packets.push(unProcessed.subarray(0, headers.payloadSize + 8));
649
+ unProcessed = unProcessed.subarray(headers.payloadSize + 8);
650
+ }
651
+ return packets;
652
+ };
653
+
654
+ /**
655
+ * Represents a fingerprint template with associated metadata
656
+ */
657
+ class Finger {
658
+ uid;
659
+ fid;
660
+ /** Flag indicating 0 = invalid | 1 = valid | 3 = duress. if is not initilizaed, default is 1 = valid */
661
+ valid;
662
+ template;
663
+ size;
664
+ mark;
665
+ /**
666
+ * Creates a new Finger instance
667
+ * @param uid User internal reference
668
+ * @param fid Finger ID (value >= 0 && value <= 9)
669
+ * @param valid Flag indicating 0 = invalid | 1 = valid | 3 = duress
670
+ * @param template Fingerprint template data buffer
671
+ */
672
+ constructor(uid, fid, template, valid) {
673
+ this.uid = Number(uid);
674
+ this.fid = Number(fid);
675
+ this.valid = valid ? Number(valid) : 1;
676
+ this.template = template;
677
+ this.size = template.length;
678
+ // Create mark showing first and last 8 bytes as hex
679
+ const start = Uint8Array.prototype.slice.call(template, 0, 8).toString('hex');
680
+ const end = Uint8Array.prototype.slice.call(template, -8).toString('hex');
681
+ this.mark = `${start}...${end}`;
682
+ }
683
+ /**
684
+ * Packs the fingerprint data with metadata into a Buffer
685
+ * @returns Buffer containing packed fingerprint data
686
+ */
687
+ repack() {
688
+ // pack("HHbb%is" % (self.size), self.size+6, self.uid, self.fid, self.valid, self.template)
689
+ const buf = Buffer.alloc(6 + this.size); // HHbb = 6 bytes + template size
690
+ let offset = 0;
691
+ buf.writeUInt16LE(this.size + 6, offset);
692
+ offset += 2;
693
+ buf.writeUInt16LE(this.uid, offset);
694
+ offset += 2;
695
+ buf.writeUInt8(this.fid, offset);
696
+ offset += 1;
697
+ buf.writeUInt8(this.valid, offset);
698
+ offset += 1;
699
+ this.template.copy(buf, offset);
700
+ return buf;
701
+ }
702
+ /**
703
+ * Packs only the fingerprint template data into a Buffer
704
+ * @returns Buffer containing just the template data
705
+ */
706
+ repackOnly() {
707
+ // pack("H%is" % (self.size), self.size, self.template)
708
+ const buf = Buffer.alloc(2 + this.size); // H = 2 bytes + template size
709
+ buf.writeUInt16LE(this.size, 0);
710
+ this.template.copy(buf, 2);
711
+ return buf;
712
+ }
713
+ /**
714
+ * Compares this fingerprint with another for equality
715
+ * @param other Another Finger instance to compare with
716
+ * @returns true if all properties and template data match
717
+ */
718
+ equals(other) {
719
+ if (!(other instanceof Finger))
720
+ return false;
721
+ return this.uid === other.uid &&
722
+ this.fid === other.fid &&
723
+ this.valid === other.valid &&
724
+ this.template.equals(other.template);
725
+ }
726
+ }
727
+
728
+ class UserService {
729
+ _zkTcp;
730
+ _users;
731
+ constructor(zkTcp) {
732
+ this._zkTcp = zkTcp;
733
+ }
734
+ async getUserByUserId(user_id) {
735
+ if (!this._users) {
736
+ await this.getUsers();
737
+ }
738
+ if (this._users.has(String(user_id))) {
739
+ return this._users.get(String(user_id));
740
+ }
741
+ else
742
+ throw new Error("user_id not exists");
743
+ }
744
+ async getUsers() {
745
+ try {
746
+ // Free any existing buffer data to prepare for a new request
747
+ if (this._users) {
748
+ return { data: Array.from(this._users.values()) };
749
+ }
750
+ else {
751
+ this._users = new Map([]);
752
+ }
753
+ if (this._zkTcp.socket) {
754
+ await this._zkTcp.freeData();
755
+ }
756
+ await this._zkTcp.disableDevice();
757
+ const users = await new Promise((resolve, reject) => {
758
+ // Request user data
759
+ this._zkTcp
760
+ .readWithBuffer(REQUEST_DATA.GET_USERS)
761
+ .then(async (data) => {
762
+ // Ensure data.data is a valid buffer
763
+ if (!data.data || !(data.data instanceof Buffer)) {
764
+ reject(new Error("Invalid data received"));
765
+ return;
766
+ }
767
+ let userData = data.data.subarray(4); // Skip the first 4 bytes (headers)
768
+ const users = [];
769
+ // Constants for user data processing
770
+ const USER_PACKET_SIZE = 72;
771
+ // Process each user packet
772
+ while (userData.length >= USER_PACKET_SIZE) {
773
+ // Decode user data and add to the users array
774
+ const user = decodeUserData72(userData.subarray(0, USER_PACKET_SIZE));
775
+ users.push(user);
776
+ this._users.set(user.user_id, user);
777
+ userData = userData.subarray(USER_PACKET_SIZE); // Move to the next packet
778
+ }
779
+ resolve(users);
780
+ })
781
+ .catch(reject);
782
+ });
783
+ // Free buffer data after receiving the data
784
+ if (this._zkTcp.socket && users) {
785
+ await this._zkTcp.enableDevice();
786
+ await this._zkTcp.freeData();
787
+ }
788
+ // Return the list of users
789
+ return { data: users };
790
+ }
791
+ catch (err) {
792
+ // Log the error for debugging
793
+ console.error("Error getting users:", err);
794
+ // Re-throw the error to be handled by the caller
795
+ throw err;
796
+ }
797
+ }
798
+ async setUser(user_id, name, password, role = 0, cardno = 0) {
799
+ try {
800
+ // Validate input parameters
801
+ if (user_id.length > 9 ||
802
+ name.length > 24 ||
803
+ password.length > 8 ||
804
+ typeof role !== "number" ||
805
+ cardno.toString().length > 10) {
806
+ throw new Error("Invalid input parameters");
807
+ }
808
+ // Allocate and initialize the buffer
809
+ const commandBuffer = Buffer.alloc(72);
810
+ // Fill the buffer with user data
811
+ commandBuffer.writeUInt16LE(0, 0); // uid will be set in the device
812
+ commandBuffer.writeUInt16LE(role, 2);
813
+ commandBuffer.write(password.padEnd(8, "\0"), 3, 8); // Ensure password is 8 bytes
814
+ commandBuffer.write(name.padEnd(24, "\0"), 11, 24); // Ensure name is 24 bytes
815
+ commandBuffer.writeUInt16LE(cardno, 35);
816
+ commandBuffer.writeUInt32LE(0, 40); // Placeholder or reserved field
817
+ commandBuffer.write(user_id.padEnd(9, "\0"), 48, 9); // Ensure userid is 9 bytes
818
+ // Send the command and return the result
819
+ const created = await this._zkTcp.executeCmd(COMMANDS.CMD_USER_WRQ, commandBuffer);
820
+ return !!created;
821
+ }
822
+ catch (err) {
823
+ // Log error details for debugging
824
+ console.error("Error setting user:", err);
825
+ // Re-throw error for upstream handling
826
+ throw err;
827
+ }
828
+ }
829
+ async DeleteUser(user_id) {
830
+ try {
831
+ const user = await this.getUserByUserId(user_id);
832
+ // Allocate and initialize the buffer
833
+ const commandBuffer = Buffer.alloc(72);
834
+ // Write UID to the buffer
835
+ commandBuffer.writeUInt16LE(user.uid, 0);
836
+ // Send the delete command and return the result
837
+ const deleted = await this._zkTcp.executeCmd(COMMANDS.CMD_DELETE_USER, commandBuffer);
838
+ return !!deleted;
839
+ }
840
+ catch (err) {
841
+ // Log error details for debugging
842
+ console.error("Error deleting user:", err);
843
+ // Re-throw error for upstream handling
844
+ throw err;
845
+ }
846
+ }
847
+ async getTemplates(cb) {
848
+ const templates = [];
849
+ try {
850
+ await this._zkTcp.disableDevice();
851
+ if (this._zkTcp.socket) {
852
+ await this._zkTcp.freeData();
853
+ }
854
+ if (!this._zkTcp.fp_count) {
855
+ await this._zkTcp.getSizes();
856
+ }
857
+ if (this._zkTcp.fp_count == 0)
858
+ return { data: [] };
859
+ const resp = (await this._zkTcp.readWithBuffer(REQUEST_DATA.GET_TEMPLATES));
860
+ let templateData = resp.data.subarray(4);
861
+ let totalSize = resp.data.readUIntLE(0, 4);
862
+ while (totalSize) {
863
+ const buf = templateData.subarray(0, 6);
864
+ const size = buf.readUIntLE(0, 2);
865
+ const uid = buf.readUIntLE(2, 2);
866
+ const fid = buf.readUIntLE(4, 1);
867
+ const valid = buf.readUIntLE(5, 1);
868
+ // Force-copy bytes so we don't retain the entire big backing buffer
869
+ const tplBytes = Buffer.from(templateData.subarray(6, size));
870
+ templates.push(new Finger(uid, fid, tplBytes, valid));
871
+ templateData = templateData.subarray(size);
872
+ totalSize -= size;
873
+ }
874
+ if (cb)
875
+ cb(templates);
876
+ return { data: templates };
877
+ }
878
+ catch (err) {
879
+ this._zkTcp.verbose && console.log("Error getting templates", err);
880
+ throw err;
881
+ }
882
+ finally {
883
+ await this._zkTcp.freeData();
884
+ await this._zkTcp.enableDevice();
885
+ }
886
+ }
887
+ async DownloadFp(user_id, fid) {
888
+ try {
889
+ const user = (await this.getUserByUserId(String(user_id)));
890
+ if (0 > fid || fid > 9)
891
+ throw new Error("fid must be between 0 and 9");
892
+ // Allocate and initialize the buffer
893
+ const data = Buffer.alloc(3);
894
+ // Fill the buffer with user data
895
+ data.writeUInt16LE(user.uid, 0);
896
+ data.writeUIntLE(fid, 2, 1);
897
+ this._zkTcp.replyId++;
898
+ const packet = createTCPHeader(COMMANDS.CMD_USERTEMP_RRQ, this._zkTcp.sessionId, this._zkTcp.replyId, data);
899
+ let fingerSize = 0;
900
+ let fingerTemplate = Buffer.from([]);
901
+ const template = await new Promise((resolve, reject) => {
902
+ let timeout;
903
+ const cleanup = () => {
904
+ if (this._zkTcp.socket) {
905
+ this._zkTcp.socket.removeListener("data", receiveData);
906
+ }
907
+ if (timeout)
908
+ clearTimeout(timeout);
909
+ };
910
+ let timer = () => setTimeout(() => {
911
+ cleanup();
912
+ reject(new Error("Time Out, Could not retrieve data"));
913
+ }, this._zkTcp.timeout);
914
+ const receiveData = (data) => {
915
+ timeout = timer();
916
+ if (data.length === 0)
917
+ return;
918
+ try {
919
+ if (data.length === 0)
920
+ return;
921
+ const headers = decodeTCPHeader(data);
922
+ switch (headers.commandId) {
923
+ case DISCOVERED_CMD.FID_NOT_FOUND:
924
+ throw new Error("Could not retrieve data. maybe finger id not exists?");
925
+ case COMMANDS.CMD_PREPARE_DATA:
926
+ fingerSize = data.readUIntLE(16, 2);
927
+ break;
928
+ case COMMANDS.CMD_DATA:
929
+ // A single 'data' event might contain multiple TCP packets combined by the OS
930
+ // in this method, is possible to get CMD_DATA and CMD_ACK_OK in the same event,
931
+ // so It's important to split data received for remove CMD_ACK_OK headers
932
+ fingerTemplate = Buffer.concat([
933
+ fingerTemplate,
934
+ data.subarray(16, fingerSize + 10),
935
+ ]);
936
+ // @ts-ignore
937
+ resolve(fingerTemplate);
938
+ break;
939
+ case COMMANDS.CMD_ACK_OK:
940
+ cleanup();
941
+ // @ts-ignore
942
+ resolve(fingerTemplate);
943
+ return;
944
+ default:
945
+ // If it's not a recognized command but has data, it might be raw template data
946
+ if (headers.commandId > 2000 && headers.commandId < 3000) {
947
+ // Likely another ACK or system msg
948
+ }
949
+ else {
950
+ fingerTemplate = Buffer.concat([fingerTemplate, data]);
951
+ }
952
+ break;
953
+ }
954
+ clearTimeout(timeout);
955
+ }
956
+ catch (e) {
957
+ cleanup();
958
+ reject(e);
959
+ }
960
+ };
961
+ if (this._zkTcp.socket) {
962
+ this._zkTcp.socket.on("data", receiveData);
963
+ this._zkTcp.socket.write(packet, undefined, (err) => {
964
+ if (err) {
965
+ cleanup();
966
+ reject(err);
967
+ }
968
+ });
969
+ }
970
+ else {
971
+ reject(new Error("Socket not initialized"));
972
+ }
973
+ });
974
+ return new Finger(user.uid, fid, template);
975
+ }
976
+ catch (err) {
977
+ throw err;
978
+ }
979
+ finally {
980
+ await this._zkTcp.freeData();
981
+ }
982
+ }
983
+ /**
984
+ *
985
+ * @param user_id {string} user
986
+ * @param fingers {Finger[]} array of finger templates instances
987
+ * */
988
+ async saveTemplates(user_id, fingers = []) {
989
+ if (fingers.length > 9 || fingers.length == 0)
990
+ throw new Error("maximum finger length is 10 and can't be empty");
991
+ try {
992
+ await this._zkTcp.disableDevice();
993
+ // check users exists
994
+ const user = await this.getUserByUserId(user_id);
995
+ let fpack = Buffer.alloc(0);
996
+ let table = Buffer.alloc(0);
997
+ const fnum = 0x10;
998
+ let tstart = 0;
999
+ for (const finger of fingers) {
1000
+ const tfp = finger.repackOnly();
1001
+ 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
1002
+ tableEntry.writeInt8(2, 0);
1003
+ tableEntry.writeUInt16LE(user.uid, 1);
1004
+ tableEntry.writeInt8(fnum + finger.fid, 3);
1005
+ tableEntry.writeUInt32LE(tstart, 4);
1006
+ table = Buffer.concat([table, tableEntry]);
1007
+ tstart += tfp.length;
1008
+ fpack = Buffer.concat([fpack, tfp]);
1009
+ }
1010
+ let upack;
1011
+ if (this._zkTcp.userPacketSize === 28) {
1012
+ upack = user.repack29();
1013
+ }
1014
+ else {
1015
+ upack = user.repack73();
1016
+ }
1017
+ const head = Buffer.alloc(12); // III = 3*4 bytes
1018
+ head.writeUInt32LE(upack.length, 0);
1019
+ head.writeUInt32LE(table.length, 4);
1020
+ head.writeUInt32LE(fpack.length, 8);
1021
+ const packet = Buffer.concat([head, upack, table, fpack]);
1022
+ await this._zkTcp.sendWithBuffer(packet);
1023
+ const command = 110;
1024
+ const commandString = Buffer.alloc(8); // <IHH = I(4) + H(2) + H(2) = 8 bytes
1025
+ commandString.writeUInt32LE(12, 0);
1026
+ commandString.writeUInt16LE(0, 4);
1027
+ commandString.writeUInt16LE(8, 6);
1028
+ await this._zkTcp.executeCmd(command, commandString);
1029
+ if (this._zkTcp.verbose)
1030
+ console.log("finally bulk save user templates: \n", "templates saved successfully");
1031
+ }
1032
+ catch (error) {
1033
+ throw error;
1034
+ }
1035
+ finally {
1036
+ await this._zkTcp.refreshData();
1037
+ await this._zkTcp.enableDevice();
1038
+ }
1039
+ }
1040
+ async deleteFinger(user_id, fid) {
1041
+ try {
1042
+ const user = (await this.getUserByUserId(user_id));
1043
+ const buf = Buffer.alloc(4);
1044
+ buf.writeUInt16LE(user_id ? user.uid : 0, 0);
1045
+ buf.writeUint16LE(fid ? fid : 0, 2);
1046
+ const reply = await this._zkTcp.executeCmd(COMMANDS.CMD_DELETE_USERTEMP, buf);
1047
+ return !!reply;
1048
+ }
1049
+ catch (error) {
1050
+ throw new Error("Can't save utemp");
1051
+ }
1052
+ finally {
1053
+ await this._zkTcp.refreshData();
1054
+ }
1055
+ }
1056
+ async enrollInfo(user_id, tempId) {
1057
+ try {
1058
+ let timer;
1059
+ const setTimeoutTimer = (cb) => {
1060
+ if (timer)
1061
+ clearTimeout(timer);
1062
+ return setTimeout(() => {
1063
+ cb(new Error("[ENROLL_INFO] time out"));
1064
+ }, 1000 * 20);
1065
+ };
1066
+ const cleanUp = () => {
1067
+ if (timer)
1068
+ clearTimeout(timer);
1069
+ };
1070
+ return await new Promise((resolve, reject) => {
1071
+ const handleRtEvent = (rtEvent) => {
1072
+ switch (rtEvent.event) {
1073
+ case RTEvent.EF_FPFTR:
1074
+ timer = setTimeoutTimer(reject);
1075
+ break;
1076
+ case RTEvent.EF_FINGER:
1077
+ console.log(rtEvent);
1078
+ break;
1079
+ case RTEvent.EF_ENROLLFINGER:
1080
+ cleanUp();
1081
+ resolve(rtEvent);
1082
+ break;
1083
+ default:
1084
+ console.log(rtEvent);
1085
+ break;
1086
+ }
1087
+ };
1088
+ // Start enroll process
1089
+ this.getUserByUserId(user_id)
1090
+ .then(async (user) => {
1091
+ /** First check if Finger index already exists, and if so, it must be deleted */
1092
+ try {
1093
+ const exists = await this.DownloadFp(user_id, tempId);
1094
+ console.log("exists: ", exists);
1095
+ if (exists) {
1096
+ this._zkTcp.verbose &&
1097
+ console.debug("Deleting Finger index before start enroll");
1098
+ await this.deleteFinger(user_id, tempId);
1099
+ }
1100
+ }
1101
+ catch (e) {
1102
+ this._zkTcp.verbose &&
1103
+ console.debug("Finger index is empty, skipping delete");
1104
+ }
1105
+ const userBuf = Buffer.alloc(24);
1106
+ userBuf.write(user_id, 0, 24, "ascii");
1107
+ const commandString = Buffer.concat([
1108
+ userBuf,
1109
+ Buffer.from([tempId, 1]),
1110
+ ]);
1111
+ await this._zkTcp.executeCmd(COMMANDS.CMD_STARTENROLL, commandString); // #5
1112
+ this._zkTcp.timeout = 60000; // 60 seconds timeout
1113
+ await this._zkTcp.executeCmd(COMMANDS.CMD_STARTVERIFY, ""); // #17
1114
+ timer = setTimeoutTimer(reject);
1115
+ void (await this._zkTcp.getRealTimeLogs(handleRtEvent)); // #9
1116
+ })
1117
+ .catch(reject);
1118
+ });
1119
+ }
1120
+ catch (error) {
1121
+ throw error;
1122
+ }
1123
+ finally {
1124
+ //await this._zkTcp.cancelCapture();
1125
+ //await this.verify(user_id);
1126
+ }
1127
+ }
1128
+ async verify(user_id) {
1129
+ try {
1130
+ const user = await this.getUserByUserId(user_id);
1131
+ const command_string = Buffer.alloc(4);
1132
+ command_string.writeUInt32LE(user.uid, 0);
1133
+ const reply = await this._zkTcp.executeCmd(COMMANDS.CMD_STARTVERIFY, command_string);
1134
+ if (this._zkTcp.verbose)
1135
+ console.log(reply.readUInt16LE(0));
1136
+ return !!reply;
1137
+ }
1138
+ catch (error) {
1139
+ console.error(error);
1140
+ throw error;
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Upload a single fingerprint for a given user id
1145
+ * @param user_id {string} user id for customer
1146
+ * @param fingerTemplate {string} finger template in base64 string
1147
+ * @param fid {number} finger id is a number between 0 and 9
1148
+ * @param fp_valid {number} finger flag. e.g., valid=1, duress=3
1149
+ */
1150
+ async uploadFingerTemplate(user_id, fingerTemplate, fid, fp_valid) {
1151
+ try {
1152
+ const user = this._users.get(user_id);
1153
+ await this._zkTcp.disableDevice();
1154
+ const prep_struct = Buffer.alloc(4);
1155
+ const fingerBuffer = Buffer.from(fingerTemplate, "base64");
1156
+ const fp_size = fingerBuffer.length;
1157
+ prep_struct.writeUInt16LE(fp_size, 0);
1158
+ const initPacket = await this._zkTcp.executeCmd(COMMANDS.CMD_PREPARE_DATA, prep_struct);
1159
+ if (initPacket.readUInt16LE(0) !== COMMANDS.CMD_ACK_OK) {
1160
+ throw new Error(`received unexpected command: ${initPacket.readUInt16LE(0)}`);
1161
+ }
1162
+ const fpPacket = await this._zkTcp.executeCmd(COMMANDS.CMD_DATA, fingerBuffer);
1163
+ if (fpPacket.readUInt16LE(0) !== COMMANDS.CMD_ACK_OK) {
1164
+ throw new Error(`received unexpected command: ${fpPacket.readUInt16LE(0)}`);
1165
+ }
1166
+ const cheksumPacket = await this._zkTcp.executeCmd(COMMANDS.CMD_CHECKSUM_BUFFER, "");
1167
+ if (cheksumPacket.readUInt16LE(0) !== COMMANDS.CMD_ACK_OK) {
1168
+ throw new Error(`received unexpected command: ${cheksumPacket.readUInt16LE(0)}`);
1169
+ }
1170
+ const tmp_wreq = Buffer.alloc(6);
1171
+ tmp_wreq.writeUInt16LE(user.uid, 0);
1172
+ tmp_wreq.writeUIntLE(fid, 2, 1);
1173
+ tmp_wreq.writeUIntLE(fp_valid, 3, 1);
1174
+ tmp_wreq.writeUInt16LE(fp_size, 4);
1175
+ const tmp_wreqPacket = await this._zkTcp.executeCmd(COMMANDS.CMD_TMP_WRITE, tmp_wreq);
1176
+ if (tmp_wreqPacket.readUInt16LE(0) !== COMMANDS.CMD_ACK_OK) {
1177
+ throw new Error(`received unexpected command: ${tmp_wreqPacket.readUInt16LE(0)}`);
1178
+ }
1179
+ const freeData = await this._zkTcp.executeCmd(COMMANDS.CMD_FREE_DATA, "");
1180
+ if (freeData.readUInt16LE(0) !== COMMANDS.CMD_ACK_OK) {
1181
+ throw new Error(`received unexpected command: ${freeData.readUInt16LE(0)}`);
1182
+ }
1183
+ return true;
1184
+ }
1185
+ catch (err) {
1186
+ throw err;
1187
+ }
1188
+ finally {
1189
+ await this._zkTcp.refreshData();
1190
+ await this._zkTcp.enableDevice();
1191
+ }
1192
+ }
1193
+ }
1194
+
1195
+ class TransactionService {
1196
+ _zkTcp;
1197
+ constructor(zkTcp) {
1198
+ this._zkTcp = zkTcp;
1199
+ }
1200
+ async getAttendances(callbackInProcess = () => { }) {
1201
+ try {
1202
+ // Free any existing buffer data to prepare for a new request
1203
+ if (this._zkTcp.socket) {
1204
+ await this._zkTcp.freeData();
1205
+ }
1206
+ // Request attendance logs and handle chunked data
1207
+ const data = await this._zkTcp.readWithBuffer(REQUEST_DATA.GET_ATTENDANCE_LOGS, callbackInProcess);
1208
+ // Free buffer data after receiving the attendance logs
1209
+ if (this._zkTcp.socket) {
1210
+ await this._zkTcp.freeData();
1211
+ }
1212
+ // Constants for record processing
1213
+ const RECORD_PACKET_SIZE = 40;
1214
+ // Ensure data.data is a valid buffer
1215
+ if (!data.data || !(data.data instanceof Buffer)) {
1216
+ throw new Error('Invalid data received');
1217
+ }
1218
+ // Process the record data
1219
+ let recordData = data.data.subarray(4); // Skip header
1220
+ const records = [];
1221
+ // Process each attendance record
1222
+ while (recordData.length >= RECORD_PACKET_SIZE) {
1223
+ const record = decodeRecordData40(recordData.subarray(0, RECORD_PACKET_SIZE));
1224
+ records.push({ ...record, ip: this._zkTcp.ip }); // Add IP address to each record
1225
+ recordData = recordData.subarray(RECORD_PACKET_SIZE); // Move to the next packet
1226
+ }
1227
+ // Return the list of attendance records
1228
+ return { data: records };
1229
+ }
1230
+ catch (err) {
1231
+ // Log and re-throw the error
1232
+ console.error('Error getting attendance records:', err);
1233
+ throw err; // Re-throw the error for handling by the caller
1234
+ }
1235
+ }
1236
+ // Clears the attendance logs on the device
1237
+ async clearAttendanceLog() {
1238
+ try {
1239
+ // Execute the command to clear attendance logs
1240
+ await this._zkTcp.disableDevice();
1241
+ const buf = await this._zkTcp.executeCmd(COMMANDS.CMD_CLEAR_ATTLOG, '');
1242
+ await this._zkTcp.refreshData();
1243
+ await this._zkTcp.enableDevice();
1244
+ return !!buf;
1245
+ }
1246
+ catch (err) {
1247
+ // Log the error for debugging purposes
1248
+ console.error('Error clearing attendance log:', err);
1249
+ // Re-throw the error to be handled by the caller
1250
+ throw err;
1251
+ }
1252
+ }
1253
+ }
1254
+
1255
+ /**
1256
+ *
1257
+ * @param {number} time
1258
+ */
1259
+ const decode = time => {
1260
+ const second = time % 60;
1261
+ time = (time - second) / 60;
1262
+ const minute = time % 60;
1263
+ time = (time - minute) / 60;
1264
+ const hour = time % 24;
1265
+ time = (time - hour) / 24;
1266
+ const day = time % 31 + 1;
1267
+ time = (time - (day - 1)) / 31;
1268
+ const month = time % 12;
1269
+ time = (time - month) / 12;
1270
+ const year = time + 2000;
1271
+ return new Date(year, month, day, hour, minute, second);
1272
+ };
1273
+ /**
1274
+ *
1275
+ * @param {Date} date
1276
+ */
1277
+ const encode = date => {
1278
+ return (((date.getFullYear() % 100) * 12 * 31 + date.getMonth() * 31 + date.getDate() - 1) * (24 * 60 * 60) +
1279
+ (date.getHours() * 60 + date.getMinutes()) * 60 +
1280
+ date.getSeconds());
1281
+ };
1282
+ var timeParser = { encode, decode };
1283
+
1284
+ /**
1285
+ * SDK Parameters Enum
1286
+ *
1287
+ * Generated from SDK parameter table with the following structure:
1288
+ * - Keys: Parameter names in uppercase without ~ prefix
1289
+ * - Values: Original parameter names
1290
+ * - JSDoc: Includes description, permissions, and notes
1291
+ */
1292
+ var SdkParameter;
1293
+ (function (SdkParameter) {
1294
+ /**
1295
+ * Device ID.
1296
+ * Permissions: RW
1297
+ * Notes: Value ranges from 1 to 254.
1298
+ */
1299
+ SdkParameter["DEVICE_ID"] = "DeviceID";
1300
+ /**
1301
+ * Language.
1302
+ * Permissions: RW
1303
+ * Notes: For english it is 97.
1304
+ */
1305
+ SdkParameter["NEW_LNG"] = "NewLng";
1306
+ /**
1307
+ * The machine will enter standby state or power off, after this time elapses.
1308
+ * Permissions: RW
1309
+ * Notes: Given in minutes.
1310
+ */
1311
+ SdkParameter["IDLE_MINUTE"] = "IdleMinute";
1312
+ /**
1313
+ * Lock control time.
1314
+ * Permissions: RW
1315
+ * Notes: Given in seconds.
1316
+ */
1317
+ SdkParameter["LOCK_ON"] = "LockOn";
1318
+ /**
1319
+ * Attendance record quantity alarm.
1320
+ * Permissions: RW
1321
+ * Notes:
1322
+ */
1323
+ SdkParameter["ALARM_ATT_LOG"] = "AlarmAttLog";
1324
+ /**
1325
+ * Operation record quantity alarm.
1326
+ * Permissions: RW
1327
+ * Notes:
1328
+ */
1329
+ SdkParameter["ALARM_OP_LOG"] = "AlarmOpLog";
1330
+ /**
1331
+ * Minimun time to record the same attendance state.
1332
+ * Permissions: RW
1333
+ * Notes: Units are unknown.
1334
+ */
1335
+ SdkParameter["ALARM_RE_REC"] = "AlarmReRec";
1336
+ /**
1337
+ * Baud rate for RS232/485.
1338
+ * Permissions: RW
1339
+ * Notes: Valid values are 1200, 2400, 4800, 9600, 19200, 38400 57600, 115200.
1340
+ */
1341
+ SdkParameter["RS232_BAUD_RATE"] = "RS232BaudRate";
1342
+ /**
1343
+ * Enable flag for network functions.
1344
+ * Permissions: RW
1345
+ * Notes:
1346
+ */
1347
+ SdkParameter["NETWORK_ON"] = "NetworkOn";
1348
+ /**
1349
+ * Enable flag for RS232.
1350
+ * Permissions: RW
1351
+ * Notes:
1352
+ */
1353
+ SdkParameter["RS232_ON"] = "RS232On";
1354
+ /**
1355
+ * Enable flag for RS485.
1356
+ * Permissions: RW
1357
+ * Notes:
1358
+ */
1359
+ SdkParameter["RS485_ON"] = "RS485On";
1360
+ /**
1361
+ * Enable announcements(voice).
1362
+ * Permissions: RW
1363
+ * Notes:
1364
+ */
1365
+ SdkParameter["VOICE_ON"] = "VoiceOn";
1366
+ /**
1367
+ * Perform high-speed comparison.
1368
+ * Permissions: RW
1369
+ * Notes: Value codification is unknown.
1370
+ */
1371
+ SdkParameter["MSPEED"] = "MSpeed";
1372
+ /**
1373
+ * Idle mode.
1374
+ * Permissions: RW
1375
+ * Notes: 87 indicates shutdown and 88 indicates hibernation.
1376
+ */
1377
+ SdkParameter["IDLE_POWER"] = "IdlePower";
1378
+ /**
1379
+ * Automatic shutdown time.
1380
+ * Permissions: RW
1381
+ * Notes: Value 255 indicates the machine to not shutdown automatically.
1382
+ */
1383
+ SdkParameter["AUTO_POWER_OFF"] = "AutoPowerOff";
1384
+ /**
1385
+ * Automatic startup time.
1386
+ * Permissions: RW
1387
+ * Notes: Value 255 indicates the machine to not startup automatically.
1388
+ */
1389
+ SdkParameter["AUTO_POWER_ON"] = "AutoPowerOn";
1390
+ /**
1391
+ * Automatic hibernation time.
1392
+ * Permissions: RW
1393
+ * Notes: Value 255 indicates the machine to not suspend automatically.
1394
+ */
1395
+ SdkParameter["AUTO_POWER_SUSPEND"] = "AutoPowerSuspend";
1396
+ /**
1397
+ * Alarm 1 time.
1398
+ * Permissions: RW
1399
+ * Notes: Value 65535 disables the alarm(t).
1400
+ */
1401
+ SdkParameter["AUTO_ALARM1"] = "AutoAlarm1";
1402
+ /**
1403
+ * 1:N comparison threshold.
1404
+ * Permissions: RW
1405
+ * Notes: Integer.
1406
+ */
1407
+ SdkParameter["MTHRESHOLD"] = "MThreshold";
1408
+ /**
1409
+ * Registration threshold.
1410
+ * Permissions: RW
1411
+ * Notes: Integer.
1412
+ */
1413
+ SdkParameter["ETHRESHOLD"] = "EThreshold";
1414
+ /**
1415
+ * 1:1 comparison threshold.
1416
+ * Permissions: RW
1417
+ * Notes: Integer.
1418
+ */
1419
+ SdkParameter["VTHRESHOLD"] = "VThreshold";
1420
+ /**
1421
+ * Display matching score during verification.
1422
+ * Permissions: RW
1423
+ * Notes: Bool.
1424
+ */
1425
+ SdkParameter["SHOW_SCORE"] = "ShowScore";
1426
+ /**
1427
+ * Number of people that may unlock the door at the same time.
1428
+ * Permissions: RW
1429
+ * Notes: Integer.
1430
+ */
1431
+ SdkParameter["UNLOCK_PERSON"] = "UnlockPerson";
1432
+ /**
1433
+ * Verify only the card number.
1434
+ * Permissions: RW
1435
+ * Notes: Bool.
1436
+ */
1437
+ SdkParameter["ONLY_PIN_CARD"] = "OnlyPINCard";
1438
+ /**
1439
+ * Network speed.
1440
+ * Permissions: RW
1441
+ * Notes: Value correspondence: 1=100M-H, 4=10M-F, 5=100M-F, 8=Auto, others=10M-H.
1442
+ */
1443
+ SdkParameter["HI_SPEED_NET"] = "HiSpeedNet";
1444
+ /**
1445
+ * Accept only registered cards.
1446
+ * Permissions: RW
1447
+ * Notes: Bool.
1448
+ */
1449
+ SdkParameter["MUST_ENROLL"] = "MustEnroll";
1450
+ /**
1451
+ * Timeout to return to the initial state.
1452
+ * Permissions: RW
1453
+ * Notes: Given in seconds.
1454
+ */
1455
+ SdkParameter["TO_STATE"] = "TOState";
1456
+ /**
1457
+ * Timeout to return to the initial state if there are no inputs after entering PIN.
1458
+ * Permissions: RW
1459
+ * Notes: Given in seconds.
1460
+ */
1461
+ SdkParameter["TO_STATE_PIN"] = "TOState";
1462
+ /**
1463
+ * Timeout to return to the initial state if there are no inputs after entering menu.
1464
+ * Permissions: RW
1465
+ * Notes: Given in seconds.
1466
+ */
1467
+ SdkParameter["TO_MENU"] = "TOMenu";
1468
+ /**
1469
+ * Time format.
1470
+ * Permissions: NA
1471
+ * Notes: Value codification is unknown.
1472
+ */
1473
+ SdkParameter["DT_FMT"] = "DtFmt";
1474
+ /**
1475
+ * Flag for mandatory 1:1 comparison.
1476
+ * Permissions: RW
1477
+ * Notes: Bool.
1478
+ */
1479
+ SdkParameter["MUST_1TO1"] = "Must1To1";
1480
+ /**
1481
+ * Alarm 2 time.
1482
+ * Permissions: RW
1483
+ * Notes: Value 65535 disables the alarm(t).
1484
+ */
1485
+ SdkParameter["AUTO_ALARM2"] = "AutoAlarm2";
1486
+ /**
1487
+ * Alarm 3 time.
1488
+ * Permissions: RW
1489
+ * Notes: Value 65535 disables the alarm(t).
1490
+ */
1491
+ SdkParameter["AUTO_ALARM3"] = "AutoAlarm3";
1492
+ /**
1493
+ * Alarm 4 time.
1494
+ * Permissions: RW
1495
+ * Notes: Value 65535 disables the alarm(t).
1496
+ */
1497
+ SdkParameter["AUTO_ALARM4"] = "AutoAlarm4";
1498
+ /**
1499
+ * Alarm 5 time.
1500
+ * Permissions: RW
1501
+ * Notes: Value 65535 disables the alarm(t).
1502
+ */
1503
+ SdkParameter["AUTO_ALARM5"] = "AutoAlarm5";
1504
+ /**
1505
+ * Alarm 6 time.
1506
+ * Permissions: RW
1507
+ * Notes: Value 65535 disables the alarm(t).
1508
+ */
1509
+ SdkParameter["AUTO_ALARM6"] = "AutoAlarm6";
1510
+ /**
1511
+ * Automatic status changing times.
1512
+ * Permissions: ?
1513
+ * Notes: -1 value indicates that the status will not change automatically.
1514
+ */
1515
+ SdkParameter["AS1"] = "AS1";
1516
+ /**
1517
+ * Automatic status changing times.
1518
+ * Permissions: ?
1519
+ * Notes: -1 value indicates that the status will not change automatically.
1520
+ */
1521
+ SdkParameter["AS2"] = "AS2";
1522
+ /**
1523
+ * Automatic status changing times.
1524
+ * Permissions: ?
1525
+ * Notes: -1 value indicates that the status will not change automatically.
1526
+ */
1527
+ SdkParameter["AS3"] = "AS3";
1528
+ /**
1529
+ * Automatic status changing times.
1530
+ * Permissions: ?
1531
+ * Notes: -1 value indicates that the status will not change automatically.
1532
+ */
1533
+ SdkParameter["AS4"] = "AS4";
1534
+ /**
1535
+ * Automatic status changing times.
1536
+ * Permissions: ?
1537
+ * Notes: -1 value indicates that the status will not change automatically.
1538
+ */
1539
+ SdkParameter["AS5"] = "AS5";
1540
+ /**
1541
+ * Automatic status changing times.
1542
+ * Permissions: ?
1543
+ * Notes: -1 value indicates that the status will not change automatically.
1544
+ */
1545
+ SdkParameter["AS6"] = "AS6";
1546
+ /**
1547
+ * Automatic status changing times.
1548
+ * Permissions: ?
1549
+ * Notes: -1 value indicates that the status will not change automatically.
1550
+ */
1551
+ SdkParameter["AS7"] = "AS7";
1552
+ /**
1553
+ * Automatic status changing times.
1554
+ * Permissions: ?
1555
+ * Notes: -1 value indicates that the status will not change automatically.
1556
+ */
1557
+ SdkParameter["AS8"] = "AS8";
1558
+ /**
1559
+ * Automatic status changing times.
1560
+ * Permissions: ?
1561
+ * Notes: -1 value indicates that the status will not change automatically.
1562
+ */
1563
+ SdkParameter["AS9"] = "AS9";
1564
+ /**
1565
+ * Automatic status changing times.
1566
+ * Permissions: ?
1567
+ * Notes: -1 value indicates that the status will not change automatically.
1568
+ */
1569
+ SdkParameter["AS10"] = "AS10";
1570
+ /**
1571
+ * Automatic status changing times.
1572
+ * Permissions: ?
1573
+ * Notes: -1 value indicates that the status will not change automatically.
1574
+ */
1575
+ SdkParameter["AS11"] = "AS11";
1576
+ /**
1577
+ * Automatic status changing times.
1578
+ * Permissions: ?
1579
+ * Notes: -1 value indicates that the status will not change automatically.
1580
+ */
1581
+ SdkParameter["AS12"] = "AS12";
1582
+ /**
1583
+ * Automatic status changing times.
1584
+ * Permissions: ?
1585
+ * Notes: -1 value indicates that the status will not change automatically.
1586
+ */
1587
+ SdkParameter["AS13"] = "AS13";
1588
+ /**
1589
+ * Automatic status changing times.
1590
+ * Permissions: ?
1591
+ * Notes: -1 value indicates that the status will not change automatically.
1592
+ */
1593
+ SdkParameter["AS14"] = "AS14";
1594
+ /**
1595
+ * Automatic status changing times.
1596
+ * Permissions: ?
1597
+ * Notes: -1 value indicates that the status will not change automatically.
1598
+ */
1599
+ SdkParameter["AS15"] = "AS15";
1600
+ /**
1601
+ * Automatic status changing times.
1602
+ * Permissions: ?
1603
+ * Notes: -1 value indicates that the status will not change automatically.
1604
+ */
1605
+ SdkParameter["AS16"] = "AS16";
1606
+ /**
1607
+ * Wiegand failure ID.
1608
+ * Permissions: ?
1609
+ * Notes:
1610
+ */
1611
+ SdkParameter["WG_FAILED_ID"] = "WGFailedID";
1612
+ /**
1613
+ * Wiegand duress ID.
1614
+ * Permissions: ?
1615
+ * Notes:
1616
+ */
1617
+ SdkParameter["WG_DURESS_ID"] = "WGDuressID";
1618
+ /**
1619
+ * Wiegand zone bit.
1620
+ * Permissions: ?
1621
+ * Notes:
1622
+ */
1623
+ SdkParameter["WG_SITE_CODE"] = "WGSiteCode";
1624
+ /**
1625
+ * Pulse width of Wiegand outputs.
1626
+ * Permissions: ?
1627
+ * Notes:
1628
+ */
1629
+ SdkParameter["WG_PULSE_WIDTH"] = "WGPulseWidth";
1630
+ /**
1631
+ * Pulse interval for Wiegand outputs.
1632
+ * Permissions: ?
1633
+ * Notes:
1634
+ */
1635
+ SdkParameter["WG_PULSE_INTERVAL"] = "WGPulseInterval";
1636
+ /**
1637
+ * ID of the start sector on the Mifare card where fingerprints are stored.
1638
+ * Permissions: ?
1639
+ * Notes:
1640
+ */
1641
+ SdkParameter["RF_START"] = "RFSStart";
1642
+ /**
1643
+ * Total number of sectors on the Mifare card where fingerprints are stored.
1644
+ * Permissions: ?
1645
+ * Notes:
1646
+ */
1647
+ SdkParameter["RF_LEN"] = "RFSLen";
1648
+ /**
1649
+ * Number of fingerprints stored on the Mifare card.
1650
+ * Permissions: ?
1651
+ * Notes:
1652
+ */
1653
+ SdkParameter["RF_FPC"] = "RFFPC";
1654
+ /**
1655
+ * Forbidden.
1656
+ * Permissions: NA
1657
+ * Notes:
1658
+ */
1659
+ SdkParameter["FORBIDDEN"] = "Forbidden";
1660
+ /**
1661
+ * Wheter to display the attendance status.
1662
+ * Permissions: RW
1663
+ * Notes:
1664
+ */
1665
+ SdkParameter["SHOW_STATE"] = "~ShowState";
1666
+ /**
1667
+ * TCP Port.
1668
+ * Permissions: ?
1669
+ * Notes:
1670
+ */
1671
+ SdkParameter["TCP_PORT"] = "TCPPort";
1672
+ /**
1673
+ * UDP Port.
1674
+ * Permissions: ?
1675
+ * Notes:
1676
+ */
1677
+ SdkParameter["UDP_PORT"] = "UDPPort";
1678
+ /**
1679
+ * Fingerprint algorithm version.
1680
+ * Permissions: R
1681
+ * Notes:
1682
+ */
1683
+ SdkParameter["ZK_FP_VERSION"] = "~ZKFPVersion";
1684
+ /**
1685
+ * Face algorithm version.
1686
+ * Permissions: R
1687
+ * Notes:
1688
+ */
1689
+ SdkParameter["ZK_FACE_VERSION"] = "~ZKFaceVersion";
1690
+ /**
1691
+ * Finger vein version.
1692
+ * Permissions: R
1693
+ * Notes:
1694
+ */
1695
+ SdkParameter["ZK_FV_VERSION"] = "~ZKFVVersion";
1696
+ /**
1697
+ * Face function.
1698
+ * Permissions: R
1699
+ * Notes:
1700
+ */
1701
+ SdkParameter["FACE_FUN_ON"] = "~FaceFunOn";
1702
+ /**
1703
+ * User id max length.
1704
+ * Permissions: R
1705
+ * Notes:
1706
+ */
1707
+ SdkParameter["PIN2_WIDTH"] = "~PIN2Width";
1708
+ /**
1709
+ * Does the user id support chars.
1710
+ * Permissions: R
1711
+ * Notes:
1712
+ */
1713
+ SdkParameter["IS_SUPPORT_ABC_PIN"] = "IsSupportABCPin";
1714
+ /**
1715
+ * ?
1716
+ * Permissions: ?
1717
+ * Notes:
1718
+ */
1719
+ SdkParameter["IME_FUN_ON"] = "IMEFunOn";
1720
+ /**
1721
+ * ?
1722
+ * Permissions: ?
1723
+ * Notes:
1724
+ */
1725
+ SdkParameter["IS_SUPPORT_ALARM_EXT"] = "IsSupportAlarmExt";
1726
+ /**
1727
+ * ?
1728
+ * Permissions: ?
1729
+ * Notes:
1730
+ */
1731
+ SdkParameter["DCTZ"] = "~DCTZ";
1732
+ /**
1733
+ * ?
1734
+ * Permissions: ?
1735
+ * Notes:
1736
+ */
1737
+ SdkParameter["DOTZ"] = "~DOTZ";
1738
+ /**
1739
+ * -
1740
+ * Permissions: ?
1741
+ * Notes:
1742
+ */
1743
+ SdkParameter["EXTEND_OP_LOG"] = "ExtendOPLog";
1744
+ /**
1745
+ * Bool
1746
+ * Permissions: RW
1747
+ * Notes:
1748
+ */
1749
+ SdkParameter["WORK_CODE"] = "WorkCode";
1750
+ /**
1751
+ * Integer
1752
+ * Permissions: RW
1753
+ * Notes:
1754
+ */
1755
+ SdkParameter["LANGUAGE"] = "Language";
1756
+ /**
1757
+ * -
1758
+ * Permissions: ?
1759
+ * Notes:
1760
+ */
1761
+ SdkParameter["BIOMETRIC_TYPE"] = "BiometricType";
1762
+ /**
1763
+ * Bool
1764
+ * Permissions: RW
1765
+ * Notes:
1766
+ */
1767
+ SdkParameter["FINGER_FUN_ON"] = "FingerFunOn";
1768
+ /**
1769
+ * Bool
1770
+ * Permissions: ?
1771
+ * Notes:
1772
+ */
1773
+ SdkParameter["IS_ONLY_RF_MACHINE"] = "~IsOnlyRFMachine";
1774
+ /**
1775
+ * Vendor name
1776
+ * Permissions: ?
1777
+ * Notes:
1778
+ */
1779
+ SdkParameter["OEM_VENDOR"] = "~OEMVendor";
1780
+ /**
1781
+ * Device name
1782
+ * Permissions: ?
1783
+ * Notes:
1784
+ */
1785
+ SdkParameter["DEVICE_NAME"] = "~DeviceName";
1786
+ /**
1787
+ * MAC address
1788
+ * Permissions: ?
1789
+ * Notes:
1790
+ */
1791
+ SdkParameter["MAC"] = "MAC";
1792
+ /**
1793
+ * Serial number
1794
+ * Permissions: ?
1795
+ * Notes:
1796
+ */
1797
+ SdkParameter["SERIAL_NUMBER"] = "~SerialNumber";
1798
+ /**
1799
+ * Date string
1800
+ * Permissions: ?
1801
+ * Notes:
1802
+ */
1803
+ SdkParameter["PRODUCT_TIME"] = "~ProductTime";
1804
+ /**
1805
+ * Bool
1806
+ * Permissions: ?
1807
+ * Notes:
1808
+ */
1809
+ SdkParameter["IS_ABC_PIN_ENABLE"] = "~IsABCPinEnable";
1810
+ /**
1811
+ * Bool
1812
+ * Permissions: ?
1813
+ * Notes:
1814
+ */
1815
+ SdkParameter["T9_FUN_ON"] = "~T9FunOn";
1816
+ /**
1817
+ * Date Time
1818
+ * Permissions: RW
1819
+ */
1820
+ SdkParameter["DATETIME"] = "DateTime";
1821
+ /**
1822
+ *
1823
+ */
1824
+ SdkParameter["OS"] = "~OS";
1825
+ })(SdkParameter || (SdkParameter = {}));
1826
+
1827
+ class OptionsService {
1828
+ _zkTcp;
1829
+ constructor(zkTcp) {
1830
+ this._zkTcp = zkTcp;
1831
+ }
1832
+ /** Ask if the device doesn't support alphanumeric symbols for user id values. */
1833
+ async isAbcPinEnable() {
1834
+ const keyword = "~IsABCPinEnable";
1835
+ try {
1836
+ // Execute the command to get the PIN information
1837
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1838
+ // Extract and format the PIN information from the response data
1839
+ return data
1840
+ .slice(8) // Skip the first 8 bytes (header)
1841
+ .toString("ascii") // Convert buffer to ASCII string
1842
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1843
+ .replace(/\u0000/g, ""); // Remove null characters 0x00
1844
+ }
1845
+ catch (err) {
1846
+ // Log the error for debugging
1847
+ console.error("Error getting PIN:", err);
1848
+ // Re-throw the error to be handled by the caller
1849
+ throw err;
1850
+ }
1851
+ }
1852
+ /** Ask if the device doesn't support alphanumeric symbols for user id values. */
1853
+ async isT9FunOn() {
1854
+ const keyword = "~T9FunOn";
1855
+ try {
1856
+ // Execute the command to get the PIN information
1857
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1858
+ // Extract and format the PIN information from the response data
1859
+ return data
1860
+ .slice(8) // Skip the first 8 bytes (header)
1861
+ .toString("ascii") // Convert buffer to ASCII string
1862
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1863
+ .replace(/\u0000/g, ""); // Remove null characters 0x00
1864
+ }
1865
+ catch (err) {
1866
+ // Log the error for debugging
1867
+ console.error("Error getting PIN:", err);
1868
+ // Re-throw the error to be handled by the caller
1869
+ throw err;
1870
+ }
1871
+ }
1872
+ async getDeviceId() {
1873
+ const keyword = SdkParameter.DEVICE_ID;
1874
+ try {
1875
+ let result;
1876
+ let retry = true;
1877
+ while (retry) {
1878
+ // Execute the command to get the device name
1879
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1880
+ // Extract and format the device name from the response data
1881
+ result = data
1882
+ .slice(8) // Skip the first 8 bytes (header)
1883
+ .toString("ascii") // Convert buffer to ASCII string
1884
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1885
+ .replace(/\u0000/g, ""); // Remove null characters
1886
+ retry = result.includes("=");
1887
+ }
1888
+ return result;
1889
+ }
1890
+ catch (err) {
1891
+ // Log the error for debugging
1892
+ console.error("Error getting vendor:", err);
1893
+ // Re-throw the error for higher-level handling
1894
+ throw err;
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Change Device ID
1899
+ * @param id a number between 1 and 254
1900
+ */
1901
+ async setDeviceId(id) {
1902
+ if (id < 1 || id > 254)
1903
+ throw new Error("Device ID must be a number between 1 and 254");
1904
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_WRQ, `DeviceID=${id}\x00`);
1905
+ return data.readUInt16LE(0) === COMMANDS.CMD_ACK_OK;
1906
+ }
1907
+ async getVendor() {
1908
+ const keyword = "~OEMVendor";
1909
+ try {
1910
+ let result;
1911
+ let retry = true;
1912
+ while (retry) {
1913
+ // Execute the command to get the device name
1914
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1915
+ // Extract and format the device name from the response data
1916
+ result = data
1917
+ .slice(8) // Skip the first 8 bytes (header)
1918
+ .toString("ascii") // Convert buffer to ASCII string
1919
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1920
+ .replace(/\u0000/g, ""); // Remove null characters
1921
+ retry = result.includes("=");
1922
+ }
1923
+ return result;
1924
+ }
1925
+ catch (err) {
1926
+ // Log the error for debugging
1927
+ console.error("Error getting vendor:", err);
1928
+ // Re-throw the error for higher-level handling
1929
+ throw err;
1930
+ }
1931
+ }
1932
+ async getProductTime() {
1933
+ const keyword = "~ProductTime";
1934
+ try {
1935
+ // Execute the command to get serial number
1936
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1937
+ // Extract and format the serial number from the response data
1938
+ const ProductTime = data
1939
+ .slice(8) // Skip the first 8 bytes (header)
1940
+ .toString("ascii") // Convert buffer to string
1941
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1942
+ .replace(/\u0000/g, ""); // Remove null characters
1943
+ return new Date(ProductTime);
1944
+ }
1945
+ catch (err) {
1946
+ // Log the error for debugging
1947
+ console.error("Error getting Product Time:", err);
1948
+ // Re-throw the error for higher-level handling
1949
+ throw err;
1950
+ }
1951
+ }
1952
+ async getMacAddress() {
1953
+ const keyword = "MAC";
1954
+ try {
1955
+ // Execute the command to get serial number
1956
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1957
+ // Extract and format the serial number from the response data
1958
+ const macAddr = data
1959
+ .slice(8) // Skip the first 8 bytes (header)
1960
+ .toString("ascii") // Convert buffer to string
1961
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1962
+ .replace(/\u0000/g, ""); // Remove null characters
1963
+ return macAddr;
1964
+ }
1965
+ catch (err) {
1966
+ // Log the error for debugging
1967
+ console.error("Error getting MAC address:", err);
1968
+ // Re-throw the error for higher-level handling
1969
+ throw err;
1970
+ }
1971
+ }
1972
+ async getNetworkParams() {
1973
+ try {
1974
+ const params = {
1975
+ IPAddress: "",
1976
+ NetMask: "",
1977
+ GATEIPAddress: "",
1978
+ TCPPort: "",
1979
+ };
1980
+ const keywords = Object.keys(params);
1981
+ for await (const keyword of keywords) {
1982
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
1983
+ params[keyword] = data
1984
+ .slice(8)
1985
+ .toString("utf-8")
1986
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
1987
+ .replace(/\u0000/g, "")
1988
+ .replace("=", "."); // Replace equal simbol to dot, due to sometimes there are parsing errors
1989
+ }
1990
+ return params;
1991
+ }
1992
+ catch (err) {
1993
+ console.error("Error getting Network Params: ", err);
1994
+ throw err;
1995
+ }
1996
+ }
1997
+ async getSerialNumber() {
1998
+ const keyword = "~SerialNumber";
1999
+ let serialNumber = "";
2000
+ let count = 10;
2001
+ try {
2002
+ // Execute the command to get serial number
2003
+ /**
2004
+ * @dev implemented a counter and a while loop because sometimes serial number parses wrong for some reason
2005
+ * */
2006
+ while (serialNumber.length !== 13 && count > 0) {
2007
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2008
+ // Extract and format the serial number from the response data
2009
+ const SN = data
2010
+ .slice(8) // Skip the first 8 bytes (header)
2011
+ .toString("utf-8") // Convert buffer to string
2012
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2013
+ .replace("=", "") // Remove sometines last number is a character equal to = or unknow character
2014
+ .replace(/\u0000/g, ""); // Remove null characters
2015
+ count--;
2016
+ serialNumber = SN;
2017
+ }
2018
+ return serialNumber;
2019
+ }
2020
+ catch (err) {
2021
+ // Log the error for debugging
2022
+ console.error("Error getting serial number:", err);
2023
+ // Re-throw the error for higher-level handling
2024
+ throw err;
2025
+ }
2026
+ }
2027
+ /**
2028
+ * get Zkteko Template version
2029
+ * @returns number
2030
+ */
2031
+ async getDeviceVersion() {
2032
+ const keyword = "~ZKFPVersion";
2033
+ try {
2034
+ // Execute the command to get device version
2035
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2036
+ // Extract and format the device version from the response data
2037
+ // Remove null characters
2038
+ return data
2039
+ .slice(8) // Skip the first 8 bytes (header)
2040
+ .toString("ascii") // Convert buffer to ASCII string
2041
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2042
+ .replace(/\u0000/g, "");
2043
+ }
2044
+ catch (err) {
2045
+ // Log the error for debugging
2046
+ console.error("Error getting device version:", err);
2047
+ // Re-throw the error for higher-level handling
2048
+ throw err;
2049
+ }
2050
+ }
2051
+ /**
2052
+ * get Device/Model Name
2053
+ * @returns
2054
+ */
2055
+ async getDeviceName() {
2056
+ const keyword = "~DeviceName";
2057
+ try {
2058
+ let result;
2059
+ let retry = true;
2060
+ while (retry) {
2061
+ // Execute the command to get the device name
2062
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2063
+ // Extract and format the device name from the response data
2064
+ result = data
2065
+ .slice(8) // Skip the first 8 bytes (header)
2066
+ .toString("ascii") // Convert buffer to ASCII string
2067
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2068
+ .replace(/\u0000/g, ""); // Remove null characters
2069
+ retry = result.includes("=");
2070
+ }
2071
+ return result;
2072
+ }
2073
+ catch (err) {
2074
+ // Log the error for debugging
2075
+ console.error("Error getting device name:", err);
2076
+ // Re-throw the error for higher-level handling
2077
+ throw err;
2078
+ }
2079
+ }
2080
+ async getPlatform() {
2081
+ const keyword = "~Platform";
2082
+ try {
2083
+ let result;
2084
+ let retry = true;
2085
+ while (retry) {
2086
+ // Execute the command to get the device name
2087
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2088
+ // Extract and format the device name from the response data
2089
+ result = data
2090
+ .slice(8) // Skip the first 8 bytes (header)
2091
+ .toString("ascii") // Convert buffer to ASCII string
2092
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2093
+ .replace(/\u0000/g, ""); // Remove null characters
2094
+ retry = result.includes("=");
2095
+ }
2096
+ return result;
2097
+ }
2098
+ catch (err) {
2099
+ // Log the error for debugging
2100
+ console.error("Error getting platform information:", err);
2101
+ // Re-throw the error for higher-level handling
2102
+ throw err;
2103
+ }
2104
+ }
2105
+ async getOS() {
2106
+ const keyword = "~OS";
2107
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2108
+ return data
2109
+ .slice(8) // Skip the first 8 bytes (header)
2110
+ .toString("ascii") // Convert buffer to ASCII string
2111
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2112
+ .replace(/\u0000/g, "");
2113
+ }
2114
+ async getWorkCode() {
2115
+ const keyword = "WorkCode";
2116
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2117
+ // Extract and format the WorkCode information from the response data
2118
+ // Remove null characters
2119
+ return data
2120
+ .slice(8) // Skip the first 8 bytes (header)
2121
+ .toString("ascii") // Convert buffer to ASCII string
2122
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2123
+ .replace(/\u0000/g, "");
2124
+ }
2125
+ /**
2126
+ * get User ID max length
2127
+ * @returns
2128
+ */
2129
+ async getPIN() {
2130
+ const keyword = "~PIN2Width";
2131
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2132
+ return data
2133
+ .slice(8) // Skip the first 8 bytes (header)
2134
+ .toString("ascii") // Convert buffer to ASCII string
2135
+ .replace(`${keyword}=`, "") // Remove the keyword prefix
2136
+ .replace(/\u0000/g, "");
2137
+ }
2138
+ async getFaceOn() {
2139
+ const keyword = "FaceFunOn";
2140
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2141
+ const status = data
2142
+ .slice(8) // Skip the first 8 bytes (header)
2143
+ .toString("ascii") // Convert buffer to ASCII string
2144
+ .replace(`${keyword}=`, ""); // Remove the keyword prefix
2145
+ // Determine and return the face function status
2146
+ return status.includes("0") ? "No" : "Yes";
2147
+ }
2148
+ async getSSR() {
2149
+ const keyword = "~SSR";
2150
+ const data = await this._zkTcp.executeCmd(COMMANDS.CMD_OPTIONS_RRQ, keyword);
2151
+ return data
2152
+ .slice(8) // Skip the first 8 bytes (header)
2153
+ .toString("ascii") // Convert buffer to ASCII string
2154
+ .replace(`${keyword}=`, "");
2155
+ }
2156
+ async getFirmware() {
2157
+ try {
2158
+ // Execute the command to get firmware information
2159
+ const data = await this._zkTcp.executeCmd(1100, "");
2160
+ // Extract and return the firmware version from the response data
2161
+ return data.slice(8).toString("ascii"); // Skip the first 8 bytes (header) and convert to ASCII string
2162
+ }
2163
+ catch (err) {
2164
+ // Log the error for debugging
2165
+ console.error("Error getting firmware version:", err);
2166
+ // Re-throw the error to be handled by the caller
2167
+ throw err;
2168
+ }
2169
+ }
2170
+ async getTime() {
2171
+ try {
2172
+ // Execute the command to get the current time
2173
+ const response = await this._zkTcp.executeCmd(COMMANDS.CMD_GET_TIME, "");
2174
+ // Check if the response is valid
2175
+ if (!response || response.length < 12) {
2176
+ throw new Error("Invalid response received for time command");
2177
+ }
2178
+ // Extract and decode the time value from the response
2179
+ const timeValue = response.readUInt32LE(8); // Read 4 bytes starting at offset 8
2180
+ const time = timeParser.decode(timeValue); // Parse and return the decoded time
2181
+ return time;
2182
+ }
2183
+ catch (err) {
2184
+ // Log the error for debugging
2185
+ console.error("Error getting time:", err);
2186
+ // Re-throw the error for the caller to handle
2187
+ throw err;
2188
+ }
2189
+ }
2190
+ async setTime(tm) {
2191
+ try {
2192
+ // Validate the input time
2193
+ if (!(tm instanceof Date) && typeof tm !== "number") {
2194
+ throw new TypeError("Invalid time parameter. Must be a Date object or a timestamp.");
2195
+ }
2196
+ // Convert the input time to a Date object if it's not already
2197
+ const date = tm instanceof Date ? tm : new Date(tm);
2198
+ // Encode the time into the required format
2199
+ const encodedTime = timeParser.encode(date);
2200
+ // Create a buffer and write the encoded time
2201
+ const commandString = Buffer.alloc(32);
2202
+ commandString.writeUInt32LE(encodedTime, 0);
2203
+ // Send the command to set the time
2204
+ const time = await this._zkTcp.executeCmd(COMMANDS.CMD_SET_TIME, commandString);
2205
+ return !!time;
2206
+ }
2207
+ catch (err) {
2208
+ // Log the error for debugging
2209
+ console.error("Error setting time:", err);
2210
+ // Re-throw the error for the caller to handle
2211
+ throw err;
2212
+ }
2213
+ }
2214
+ async voiceTest() {
2215
+ try {
2216
+ // Define the command data for the voice test
2217
+ const commandData = Buffer.from("\x00\x00", "binary");
2218
+ await this._zkTcp.executeCmd(COMMANDS.CMD_TESTVOICE, commandData);
2219
+ // Execute the command and return the result
2220
+ }
2221
+ catch (err) {
2222
+ // Log the error for debugging purposes
2223
+ console.error("Error executing voice test:", err);
2224
+ // Re-throw the error to be handled by the caller
2225
+ throw err;
2226
+ }
2227
+ }
2228
+ }
2229
+
2230
+ class ZTCP {
2231
+ /**
2232
+ * @param_ip ip address of device
2233
+ * @param_port port number of device
2234
+ * @param_timeout connection timout
2235
+ * @param_comm_key communication key of device (if the case)
2236
+ * @return Zkteco TCP socket connection instance
2237
+ */
2238
+ ip;
2239
+ port;
2240
+ timeout;
2241
+ sessionId = 0;
2242
+ replyId = 0;
2243
+ socket;
2244
+ comm_key;
2245
+ user_count = 0;
2246
+ fp_count = 0;
2247
+ pwd_count = 0;
2248
+ oplog_count = 0;
2249
+ attlog_count = 0;
2250
+ fp_cap = 0;
2251
+ user_cap = 0;
2252
+ attlog_cap = 0;
2253
+ fp_av = 0;
2254
+ user_av = 0;
2255
+ attlog_av = 0;
2256
+ face_count = 0;
2257
+ face_cap = 0;
2258
+ userPacketSize = 72;
2259
+ verbose = false;
2260
+ packetNumber = 0;
2261
+ replyData = Buffer.from([]);
2262
+ _optionsService;
2263
+ _transactionService;
2264
+ _userService;
2265
+ constructor(ip, port, timeout, comm_key, verbose) {
2266
+ this.ip = ip;
2267
+ this.port = port;
2268
+ this.timeout = timeout ? timeout : 10000;
2269
+ this.replyId = 0;
2270
+ this.comm_key = comm_key;
2271
+ this.verbose = verbose;
2272
+ this._optionsService = new OptionsService(this);
2273
+ this._userService = new UserService(this);
2274
+ this._transactionService = new TransactionService(this);
2275
+ }
2276
+ createSocket(cbError, cbClose) {
2277
+ return new Promise((resolve, reject) => {
2278
+ this.socket = new Socket();
2279
+ // Handle socket error
2280
+ this.socket.once("error", (err) => {
2281
+ this.socket = undefined; // Ensure socket reference is cleared
2282
+ reject(err);
2283
+ if (typeof cbError === "function")
2284
+ cbError(err);
2285
+ });
2286
+ // Handle successful connection
2287
+ this.socket.once("connect", () => {
2288
+ resolve(this.socket);
2289
+ });
2290
+ // Handle socket closure
2291
+ this.socket.once("close", () => {
2292
+ this.socket = undefined; // Ensure socket reference is cleared
2293
+ if (typeof cbClose === "function")
2294
+ cbClose("tcp");
2295
+ });
2296
+ // Set socket timeout if provided
2297
+ if (this.timeout) {
2298
+ this.socket.setTimeout(this.timeout);
2299
+ }
2300
+ // Initiate connection
2301
+ this.socket.connect(this.port, this.ip);
2302
+ });
2303
+ }
2304
+ async connect() {
2305
+ try {
2306
+ let reply = await this.executeCmd(COMMANDS.CMD_CONNECT, "");
2307
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
2308
+ return true;
2309
+ }
2310
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_UNAUTH) {
2311
+ const hashedCommkey = authKey(this.comm_key, this.sessionId);
2312
+ reply = await this.executeCmd(COMMANDS.CMD_AUTH, hashedCommkey);
2313
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
2314
+ return true;
2315
+ }
2316
+ else {
2317
+ throw new Error("error de authenticacion");
2318
+ }
2319
+ }
2320
+ else {
2321
+ // No reply received; throw an error
2322
+ throw new Error("NO_REPLY_ON_CMD_CONNECT");
2323
+ }
2324
+ }
2325
+ catch (err) {
2326
+ // Log the error for debugging, if necessary
2327
+ console.error("Failed to connect:", err);
2328
+ // Re-throw the error for handling by the caller
2329
+ throw err;
2330
+ }
2331
+ }
2332
+ async closeSocket() {
2333
+ return new Promise((resolve, reject) => {
2334
+ // If no socket is present, resolve immediately
2335
+ if (!this.socket) {
2336
+ return resolve(true);
2337
+ }
2338
+ // Clean up listeners to avoid potential memory leaks or duplicate handling
2339
+ this.socket.removeAllListeners("data");
2340
+ // Set a timeout to handle cases where socket.end might not resolve
2341
+ const timer = setTimeout(() => {
2342
+ this.socket?.destroy(); // Forcibly close the socket if not closed properly
2343
+ resolve(true); // Resolve even if the socket was not closed properly
2344
+ }, 2000);
2345
+ // Close the socket and clear the timeout upon successful completion
2346
+ this.socket.end(() => {
2347
+ clearTimeout(timer);
2348
+ resolve(true); // Resolve once the socket has ended
2349
+ });
2350
+ // Handle socket errors during closing
2351
+ this.socket.once("error", (err) => {
2352
+ clearTimeout(timer);
2353
+ reject(err); // Reject the promise with the error
2354
+ });
2355
+ });
2356
+ }
2357
+ writeMessage(msg, connect, cb) {
2358
+ return new Promise((resolve, reject) => {
2359
+ // Check if the socket is initialized
2360
+ if (!this.socket) {
2361
+ return reject(new Error("Socket is not initialized"));
2362
+ }
2363
+ // Define a variable for the timeout reference
2364
+ const timer = setTimeout(() => {
2365
+ // Check if the socket is still valid before trying to remove the listener
2366
+ cleanUp();
2367
+ reject(new Error("TIMEOUT_ON_WRITING_MESSAGE")); // Reject the promise on timeout
2368
+ }, connect ? 3000 : this.timeout);
2369
+ // Handle incoming data
2370
+ const onData = (data) => {
2371
+ // Check if the socket is still valid before trying to remove the listener
2372
+ cleanUp(); // Clear the timeout once data is received
2373
+ resolve(cb(data)); // Resolve the promise with the received data
2374
+ };
2375
+ const cleanUp = () => {
2376
+ if (timer)
2377
+ clearTimeout(timer);
2378
+ if (this.socket) {
2379
+ this.socket.removeListener("data", onData); // Remove the data event listener
2380
+ }
2381
+ };
2382
+ // Attach the data event listener
2383
+ this.socket.on("data", onData);
2384
+ // Attempt to write the message to the socket
2385
+ this.socket.write(msg, undefined, (err) => {
2386
+ if (err) {
2387
+ cleanUp();
2388
+ reject(err); // Reject the promise with the write error
2389
+ }
2390
+ });
2391
+ });
2392
+ }
2393
+ async requestData(msg) {
2394
+ try {
2395
+ return await new Promise((resolve, reject) => {
2396
+ let timer = null;
2397
+ let replyBuffer = Buffer.from([]);
2398
+ // Internal callback to handle data reception
2399
+ const internalCallback = (data_1) => {
2400
+ if (this.socket) {
2401
+ this.socket.removeListener("data", handleOnData); // Clean up listener
2402
+ }
2403
+ if (timer)
2404
+ clearTimeout(timer); // Clear the timeout
2405
+ resolve(data_1); // Resolve the promise with the data
2406
+ };
2407
+ const onTimeOut = () => setTimeout(() => {
2408
+ if (this.socket) {
2409
+ this.socket.removeListener("data", handleOnData); // Clean up listener on timeout
2410
+ }
2411
+ reject(new Error("TIMEOUT_IN_RECEIVING_RESPONSE_AFTER_REQUESTING_DATA")); // Reject on timeout
2412
+ }, this.timeout);
2413
+ // Handle incoming data
2414
+ const handleOnData = (data_3) => {
2415
+ replyBuffer = Buffer.concat([replyBuffer, data_3]); // Accumulate data
2416
+ // Check if the data is a valid TCP event
2417
+ if (checkNotEventTCP(data_3))
2418
+ return;
2419
+ // Decode the TCP header
2420
+ const header = decodeTCPHeader(replyBuffer.subarray(0, 16));
2421
+ if (this.verbose) {
2422
+ console.log("response command: ", header.commandId, COMMANDS[header.commandId], "replyid: ", header.replyId);
2423
+ }
2424
+ // Handle based on command ID
2425
+ if (header.commandId === COMMANDS.CMD_DATA) {
2426
+ // Set a timeout to handle delayed responses
2427
+ timer = setTimeout(() => {
2428
+ internalCallback(replyBuffer); // Resolve with accumulated buffer
2429
+ }, 1000);
2430
+ }
2431
+ else {
2432
+ // Set a timeout to handle errors
2433
+ timer = onTimeOut();
2434
+ // Extract packet length and handle accordingly
2435
+ const packetLength = data_3.readUIntLE(4, 2);
2436
+ if (packetLength > 8) {
2437
+ internalCallback(data_3); // Resolve immediately if sufficient data
2438
+ }
2439
+ }
2440
+ };
2441
+ // Ensure the socket is valid before attaching the listener
2442
+ if (this.socket) {
2443
+ this.socket.on("data", handleOnData);
2444
+ // Write the message to the socket
2445
+ this.socket.write(msg, undefined, (err) => {
2446
+ if (err) {
2447
+ if (this.socket) {
2448
+ this.socket.removeListener("data", handleOnData); // Clean up listener on error
2449
+ }
2450
+ return reject(err); // Reject the promise with the error
2451
+ }
2452
+ // Set a timeout to handle cases where no response is received
2453
+ timer = onTimeOut();
2454
+ });
2455
+ }
2456
+ else {
2457
+ reject(new Error("SOCKET_NOT_INITIALIZED")); // Reject if socket is not initialized
2458
+ }
2459
+ });
2460
+ }
2461
+ catch (err_1) {
2462
+ console.error("Promise Rejected:", err_1); // Log the rejection reason
2463
+ throw err_1; // Re-throw the error to be handled by the caller
2464
+ }
2465
+ }
2466
+ /**
2467
+ *
2468
+ * @param {*} command
2469
+ * @param {*} data
2470
+ *
2471
+ *
2472
+ * reject error when command fail and resolve data when success
2473
+ */
2474
+ async executeCmd(command, data) {
2475
+ // Reset sessionId and replyId for connection commands
2476
+ if (command === COMMANDS.CMD_CONNECT) {
2477
+ this.sessionId = 0;
2478
+ this.replyId = 0;
2479
+ }
2480
+ else {
2481
+ this.replyId++;
2482
+ }
2483
+ const currentReply = this.replyId;
2484
+ const buf = createTCPHeader(command, this.sessionId, this.replyId, data);
2485
+ const callback = (responseData) => {
2486
+ const packets = splitTcpPackets(responseData);
2487
+ for (const packet of packets) {
2488
+ const headers = decodeTCPHeader(packet);
2489
+ if (this.verbose) {
2490
+ const JOIN_CMD = { ...COMMANDS, ...DISCOVERED_CMD };
2491
+ console.debug("request command:", COMMANDS[command], "\nresponse command: ", JOIN_CMD[headers.commandId], "replyid: ", headers.replyId);
2492
+ }
2493
+ if (+headers.replyId === currentReply + 1) {
2494
+ return packet;
2495
+ }
2496
+ continue;
2497
+ }
2498
+ };
2499
+ return new Promise((Resolve, Reject) => {
2500
+ // Write the message to the socket and wait for a response
2501
+ this.writeMessage(buf, command === COMMANDS.CMD_CONNECT || command === COMMANDS.CMD_EXIT, callback)
2502
+ .then((reply) => {
2503
+ // Remove TCP header from the response
2504
+ let rReply;
2505
+ try {
2506
+ rReply = removeTcpHeader(reply);
2507
+ }
2508
+ catch (e) {
2509
+ console.log("reply", reply);
2510
+ }
2511
+ // Update sessionId for connection command responses
2512
+ if (command === COMMANDS.CMD_CONNECT &&
2513
+ rReply &&
2514
+ rReply.length >= 6) {
2515
+ // Assuming sessionId is located at offset 4 and is 2 bytes long
2516
+ this.sessionId = rReply.readUInt16LE(4);
2517
+ }
2518
+ Resolve(rReply);
2519
+ })
2520
+ .catch((err) => {
2521
+ // Log or handle the error if necessary
2522
+ console.error("Error executing command:", err);
2523
+ Reject(err); // Re-throw the error for handling by the caller
2524
+ });
2525
+ });
2526
+ }
2527
+ async sendChunkRequest(start, size) {
2528
+ this.replyId++;
2529
+ const reqData = Buffer.alloc(8);
2530
+ reqData.writeUInt32LE(start, 0);
2531
+ reqData.writeUInt32LE(size, 4);
2532
+ const buf = createTCPHeader(COMMANDS.CMD_DATA_RDY, this.sessionId, this.replyId, reqData);
2533
+ try {
2534
+ const promise = new Promise((resolve, reject) => {
2535
+ this.socket?.write(buf, undefined, (err) => {
2536
+ if (err) {
2537
+ console.error(`[TCP][SEND_CHUNK_REQUEST] Error sending chunk request: ${err.message}`);
2538
+ reject(err); // Reject the promise if there is an error
2539
+ }
2540
+ else {
2541
+ resolve(true); // Resolve the promise if the write operation succeeds
2542
+ }
2543
+ });
2544
+ });
2545
+ await promise;
2546
+ }
2547
+ catch (err) {
2548
+ // Handle or log the error as needed
2549
+ console.error(`[TCP][SEND_CHUNK_REQUEST] Exception: ${err.message}`);
2550
+ throw err; // Re-throw the error for handling by the caller
2551
+ }
2552
+ }
2553
+ /**
2554
+ *
2555
+ * @param {Buffer} reqData - indicate the type of data that need to receive ( user or attLog)
2556
+ * @param {Function} cb - callback is triggered when receiving packets
2557
+ *
2558
+ * readWithBuffer will reject error if it'wrong when starting request data
2559
+ * readWithBuffer will return { data: replyData , err: Error } when receiving requested data
2560
+ */
2561
+ readWithBuffer(reqData, cb) {
2562
+ return new Promise(async (resolve, reject) => {
2563
+ this.replyId++;
2564
+ const buf = createTCPHeader(COMMANDS.CMD_DATA_WRRQ, this.sessionId, this.replyId, reqData);
2565
+ let reply;
2566
+ try {
2567
+ reply = await this.requestData(buf);
2568
+ }
2569
+ catch (err) {
2570
+ reject(err);
2571
+ }
2572
+ const header = decodeTCPHeader(reply?.subarray(0, 16));
2573
+ switch (header.commandId) {
2574
+ case COMMANDS.CMD_DATA: {
2575
+ resolve({ data: reply.subarray(16), mode: 8 });
2576
+ break;
2577
+ }
2578
+ case COMMANDS.CMD_ACK_OK:
2579
+ case COMMANDS.CMD_PREPARE_DATA: {
2580
+ // this case show that data is prepared => send command to get these data
2581
+ // reply variable includes information about the size of following data
2582
+ const recvData = reply.subarray(16);
2583
+ const size = recvData.readUIntLE(1, 4);
2584
+ // We need to split the data to many chunks to receive , because it's to large
2585
+ // After receiving all chunk data , we concat it to TotalBuffer variable , that 's the data we want
2586
+ const remain = size % Constants.MAX_CHUNK;
2587
+ const numberChunks = Math.round(size - remain) / Constants.MAX_CHUNK;
2588
+ this.packetNumber = numberChunks + (remain > 0 ? 1 : 0);
2589
+ //let replyData = Buffer.from([])
2590
+ let totalBuffer = Buffer.from([]);
2591
+ let realTotalBuffer = Buffer.from([]);
2592
+ let timer = setTimeout(() => {
2593
+ internalCallback(this.replyData, new Error("TIMEOUT WHEN RECEIVING PACKET"));
2594
+ }, this.timeout);
2595
+ const internalCallback = (replyData, err = null) => {
2596
+ this.socket && this.socket.removeAllListeners("data");
2597
+ timer && clearTimeout(timer);
2598
+ resolve({ data: replyData, err });
2599
+ };
2600
+ this.socket?.once("close", () => {
2601
+ internalCallback(this.replyData, new Error("Socket is disconnected unexpectedly"));
2602
+ });
2603
+ for (let i = 0; i <= numberChunks; i++) {
2604
+ const data = await new Promise((resolve2, reject2) => {
2605
+ try {
2606
+ this.sendChunkRequest(i * Constants.MAX_CHUNK, i === numberChunks ? remain : Constants.MAX_CHUNK);
2607
+ this.socket?.on("data", (reply) => {
2608
+ clearTimeout(timer);
2609
+ timer = setTimeout(() => {
2610
+ internalCallback(this.replyData, new Error(`TIME OUT !! ${this.packetNumber} PACKETS REMAIN !`));
2611
+ }, this.timeout);
2612
+ if (this.verbose && reply.length >= 8) {
2613
+ const headers = decodeTCPHeader(reply);
2614
+ if (COMMANDS[headers.commandId]) {
2615
+ switch (headers.commandId) {
2616
+ case COMMANDS.CMD_ACK_OK:
2617
+ case COMMANDS.CMD_DATA:
2618
+ this.verbose &&
2619
+ console.log("CMD received: ", COMMANDS[headers.commandId]);
2620
+ break;
2621
+ case COMMANDS.CMD_PREPARE_DATA:
2622
+ this.verbose &&
2623
+ console.log("CMD received: ", COMMANDS[headers.commandId]);
2624
+ this.verbose &&
2625
+ console.log(`recieve chunk: prepare data size is ${headers.payloadSize}`);
2626
+ break;
2627
+ default:
2628
+ break;
2629
+ }
2630
+ }
2631
+ }
2632
+ totalBuffer = Buffer.concat([totalBuffer, reply]);
2633
+ const packetLength = totalBuffer.readUIntLE(4, 2);
2634
+ if (totalBuffer.length >= 8 + packetLength) {
2635
+ realTotalBuffer = Buffer.concat([
2636
+ realTotalBuffer,
2637
+ totalBuffer.subarray(16, 8 + packetLength),
2638
+ ]);
2639
+ totalBuffer = totalBuffer.subarray(8 + packetLength);
2640
+ if ((this.packetNumber > 1 &&
2641
+ realTotalBuffer.length === Constants.MAX_CHUNK + 8) ||
2642
+ (this.packetNumber === 1 &&
2643
+ realTotalBuffer.length === remain + 8)) {
2644
+ this.packetNumber--;
2645
+ cb && cb(realTotalBuffer.length, size);
2646
+ resolve2(realTotalBuffer.subarray(8));
2647
+ totalBuffer = Buffer.from([]);
2648
+ realTotalBuffer = Buffer.from([]);
2649
+ }
2650
+ }
2651
+ });
2652
+ }
2653
+ catch (e) {
2654
+ reject2(e);
2655
+ }
2656
+ });
2657
+ this.replyData = Buffer.concat([
2658
+ this.replyData,
2659
+ data,
2660
+ ]);
2661
+ this.socket?.removeAllListeners("data");
2662
+ if (this.packetNumber <= 0) {
2663
+ resolve({ data: this.replyData });
2664
+ }
2665
+ }
2666
+ break;
2667
+ }
2668
+ default: {
2669
+ reject(new Error("ERROR_IN_UNHANDLE_CMD " + exportErrorMessage(header.commandId)));
2670
+ }
2671
+ }
2672
+ });
2673
+ }
2674
+ /**
2675
+ *
2676
+ * @param {*} callbackInProcess
2677
+ * reject error when starting request data
2678
+ * return { data: records, err: Error } when receiving requested data
2679
+ */
2680
+ async freeData() {
2681
+ try {
2682
+ const resp = await this.executeCmd(COMMANDS.CMD_FREE_DATA, "");
2683
+ return !!resp;
2684
+ }
2685
+ catch (err) {
2686
+ console.error("Error freeing data:", err);
2687
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
2688
+ }
2689
+ }
2690
+ async disableDevice() {
2691
+ try {
2692
+ const resp = await this.executeCmd(COMMANDS.CMD_DISABLEDEVICE, REQUEST_DATA.DISABLE_DEVICE);
2693
+ return !!resp;
2694
+ }
2695
+ catch (err) {
2696
+ console.error("Error disabling device:", err);
2697
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
2698
+ }
2699
+ }
2700
+ async enableDevice() {
2701
+ try {
2702
+ const resp = await this.executeCmd(COMMANDS.CMD_ENABLEDEVICE, "");
2703
+ return !!resp;
2704
+ }
2705
+ catch (err) {
2706
+ console.error("Error enabling device:", err);
2707
+ throw err; // Optionally, re-throw the error if you need to handle it upstream
2708
+ }
2709
+ }
2710
+ async disconnect() {
2711
+ try {
2712
+ // Attempt to execute the disconnect command
2713
+ await this.executeCmd(COMMANDS.CMD_EXIT, "");
2714
+ }
2715
+ catch (err) {
2716
+ // Log any errors encountered during command execution
2717
+ console.error("Error during disconnection:", err);
2718
+ // Optionally, add more handling or recovery logic here
2719
+ }
2720
+ // Attempt to close the socket and return the result
2721
+ try {
2722
+ await this.closeSocket();
2723
+ }
2724
+ catch (err) {
2725
+ // Log any errors encountered while closing the socket
2726
+ console.error("Error during socket closure:", err);
2727
+ // Optionally, rethrow or handle the error if necessary
2728
+ throw err; // Re-throwing to propagate the error
2729
+ }
2730
+ }
2731
+ async getInfo() {
2732
+ try {
2733
+ // Execute the command to retrieve free sizes from the device
2734
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, "");
2735
+ // Parse the response data to extract and return relevant information
2736
+ return {
2737
+ userCounts: data.readUIntLE(24, 4), // Number of users
2738
+ logCounts: data.readUIntLE(40, 4), // Number of logs
2739
+ logCapacity: data.readUIntLE(72, 4), // Capacity of logs in bytes
2740
+ };
2741
+ }
2742
+ catch (err) {
2743
+ // Log the error for debugging purposes
2744
+ console.error("Error getting device info:", err);
2745
+ // Re-throw the error to allow upstream error handling
2746
+ throw err;
2747
+ }
2748
+ }
2749
+ async getSizes() {
2750
+ try {
2751
+ // Execute the command to retrieve free sizes from the device
2752
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, "");
2753
+ // Parse the response data to extract and return relevant information
2754
+ const buf = data.slice(8); // remove header
2755
+ this.user_count = buf.readUIntLE(16, 4);
2756
+ this.fp_count = buf.readUIntLE(24, 4);
2757
+ this.pwd_count = buf.readUIntLE(52, 4);
2758
+ this.oplog_count = buf.readUIntLE(40, 4);
2759
+ this.attlog_count = buf.readUIntLE(32, 4);
2760
+ this.fp_cap = buf.readUIntLE(56, 4);
2761
+ this.user_cap = buf.readUIntLE(60, 4);
2762
+ this.attlog_cap = buf.readUIntLE(64, 4);
2763
+ this.fp_av = buf.readUIntLE(68, 4);
2764
+ this.user_av = buf.readUIntLE(72, 4);
2765
+ this.attlog_av = buf.readUIntLE(76, 4);
2766
+ this.face_count = buf.readUIntLE(80, 4);
2767
+ this.face_cap = buf.readUIntLE(88, 4);
2768
+ return {
2769
+ userCounts: this.user_count, // Number of users
2770
+ logCounts: this.attlog_count, // Number of logs
2771
+ fingerCount: this.fp_count,
2772
+ adminCount: this.pwd_count,
2773
+ opLogCount: this.oplog_count,
2774
+ logCapacity: this.attlog_cap, // Capacity of logs in bytes
2775
+ fingerCapacity: this.fp_cap,
2776
+ userCapacity: this.user_cap,
2777
+ attLogCapacity: this.attlog_cap,
2778
+ fingerAvailable: this.fp_av,
2779
+ userAvailable: this.user_av,
2780
+ attLogAvailable: this.attlog_av,
2781
+ faceCount: this.face_count,
2782
+ faceCapacity: this.face_cap,
2783
+ };
2784
+ }
2785
+ catch (err) {
2786
+ // Log the error for debugging purposes
2787
+ console.error("Error getting device info:", err);
2788
+ // Re-throw the error to allow upstream error handling
2789
+ throw err;
2790
+ }
2791
+ }
2792
+ #listeners = new Map();
2793
+ async getAttendanceSize() {
2794
+ try {
2795
+ // Execute command to get free sizes
2796
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, "");
2797
+ // Parse and return the attendance size
2798
+ return data.readUIntLE(40, 4); // Assuming data at offset 40 represents the attendance size
2799
+ }
2800
+ catch (err) {
2801
+ // Log error details for debugging
2802
+ console.error("Error getting attendance size:", err);
2803
+ // Re-throw the error to be handled by the caller
2804
+ throw err;
2805
+ }
2806
+ }
2807
+ // Clears the attendance logs on the device
2808
+ async clearAttendanceLog() {
2809
+ return await this._transactionService.clearAttendanceLog();
2810
+ }
2811
+ /**
2812
+ * Clears all data on the device
2813
+ * @value 1 Attendance records
2814
+ * @value 2 Fingerprint templates
2815
+ * @value 3 None
2816
+ * @value 4 Operation records
2817
+ * @value 5 User information
2818
+ * @default 0 Delete all
2819
+ */
2820
+ async clearData(value) {
2821
+ try {
2822
+ // Execute the command to clear all data
2823
+ await this.disableDevice();
2824
+ if (!value)
2825
+ value = 3;
2826
+ const buf = await this.executeCmd(COMMANDS.CMD_CLEAR_DATA, value.toString());
2827
+ await this.refreshData();
2828
+ await this.enableDevice();
2829
+ return !!buf;
2830
+ }
2831
+ catch (err) {
2832
+ // Log the error for debugging purposes
2833
+ console.error("Error clearing data:", err);
2834
+ // Re-throw the error to be handled by the caller
2835
+ throw err;
2836
+ }
2837
+ }
2838
+ async getRealTimeLogs(cb = (realTimeLog) => { }) {
2839
+ this.replyId++; // Increment the reply ID for this request
2840
+ try {
2841
+ // Create a buffer with the command header to request real-time logs
2842
+ const buf = createTCPHeader(COMMANDS.CMD_REG_EVENT, this.sessionId, this.replyId, Buffer.from([0x01, 0x00, 0x00, 0x00]));
2843
+ // Send the request to the device
2844
+ this.socket?.write(buf, undefined, (err) => {
2845
+ if (err) {
2846
+ // Log and reject the promise if there is an error writing to the socket
2847
+ console.error("Error sending real-time logs request:", err);
2848
+ throw err;
2849
+ }
2850
+ });
2851
+ // Ensure data listeners are added only once
2852
+ if (this.socket?.listenerCount("data") === 0) {
2853
+ console.log("entraaa");
2854
+ this.socket.on("data", (data) => {
2855
+ // Check if the data is an event and not just a regular response
2856
+ if (checkNotEventTCP(data)) {
2857
+ // Process the data if it is of the expected length
2858
+ if (data.length > 16) {
2859
+ // Decode and pass the log to the callback
2860
+ cb(decodeRTEvent(data));
2861
+ }
2862
+ }
2863
+ });
2864
+ }
2865
+ }
2866
+ catch (err) {
2867
+ // Handle errors and reject the promise
2868
+ console.error("Error getting real-time logs:", err);
2869
+ throw err;
2870
+ }
2871
+ }
2872
+ /**
2873
+ * Get all Finger objects
2874
+ * @returns {Record<string, Finger[]>}
2875
+ */
2876
+ async getTemplates(callbackInProcess = () => { }) {
2877
+ return await this._userService.getTemplates(callbackInProcess);
2878
+ }
2879
+ /**
2880
+ * Return size
2881
+ * @param packet
2882
+ */
2883
+ testTcpTop(packet) {
2884
+ // Check if packet is too small
2885
+ if (packet.length <= 8)
2886
+ return 0;
2887
+ // Extract header values using little-endian format
2888
+ const headerValue1 = packet.readUInt16LE(0);
2889
+ const headerValue2 = packet.readUInt16LE(2);
2890
+ const size = packet.readUInt32LE(4);
2891
+ // Check if magic numbers match
2892
+ if (headerValue1 === Constants.MACHINE_PREPARE_DATA_1 &&
2893
+ headerValue2 === Constants.MACHINE_PREPARE_DATA_2) {
2894
+ return size;
2895
+ }
2896
+ return 0;
2897
+ }
2898
+ async refreshData() {
2899
+ try {
2900
+ const reply = await this.executeCmd(COMMANDS.CMD_REFRESHDATA, "");
2901
+ return !!reply;
2902
+ }
2903
+ catch (err) {
2904
+ console.error("Error getting user templates: ", err);
2905
+ throw err;
2906
+ }
2907
+ }
2908
+ async sendWithBuffer(buffer) {
2909
+ const MAX_CHUNK = 1024;
2910
+ const size = buffer.length;
2911
+ await this.freeData();
2912
+ const commandString = Buffer.alloc(4); // 'I' is 4 bytes
2913
+ commandString.writeUInt32LE(size, 0);
2914
+ try {
2915
+ const cmdResponse = await this.executeCmd(COMMANDS.CMD_PREPARE_DATA, commandString);
2916
+ // responds with 2000 = CMD_ACK_OK
2917
+ if (!cmdResponse) {
2918
+ throw new Error("Can't prepare data");
2919
+ }
2920
+ }
2921
+ catch (e) {
2922
+ console.error(e);
2923
+ }
2924
+ const remain = size % MAX_CHUNK;
2925
+ const packets = Math.floor((size - remain) / MAX_CHUNK);
2926
+ let start = 0;
2927
+ try {
2928
+ for (let i = 0; i < packets; i++) {
2929
+ const resp = await this.sendChunk(buffer.slice(start, start + MAX_CHUNK));
2930
+ if (resp) {
2931
+ start += MAX_CHUNK;
2932
+ if (i == packets - 1 && remain) {
2933
+ const lastPacket = await this.sendChunk(buffer.slice(start, start + remain));
2934
+ return lastPacket;
2935
+ }
2936
+ }
2937
+ }
2938
+ }
2939
+ catch (e) {
2940
+ console.error(e);
2941
+ }
2942
+ }
2943
+ async sendChunk(commandString) {
2944
+ try {
2945
+ return await new Promise((resolve, reject) => {
2946
+ resolve(this.executeCmd(COMMANDS.CMD_DATA, commandString));
2947
+ });
2948
+ }
2949
+ catch (e) {
2950
+ throw new ZkError(e, COMMANDS.CMD_DATA, this.ip);
2951
+ }
2952
+ }
2953
+ async readSocket(length, cb = null) {
2954
+ let replyBufer = Buffer.from([]);
2955
+ const totalPackets = 0;
2956
+ return new Promise((resolve, reject) => {
2957
+ let timer = setTimeout(() => {
2958
+ internalCallback(replyBufer, new Error("TIMEOUT WHEN RECEIVING PACKET"));
2959
+ }, this.timeout);
2960
+ const internalCallback = (replyData, err = null) => {
2961
+ this.socket && this.socket.removeListener("data", onDataEnroll);
2962
+ timer && clearTimeout(timer);
2963
+ resolve({ data: replyData, err: err });
2964
+ };
2965
+ function onDataEnroll(data) {
2966
+ clearTimeout(timer);
2967
+ timer = setTimeout(() => {
2968
+ internalCallback(replyBufer, new Error(`TIME OUT !! ${totalPackets} PACKETS REMAIN !`));
2969
+ }, this.timeout);
2970
+ replyBufer = Buffer.concat([replyBufer, data], replyBufer.length + data.length);
2971
+ if (data.length == length) {
2972
+ internalCallback(data);
2973
+ }
2974
+ }
2975
+ this.socket.once("close", () => {
2976
+ internalCallback(replyBufer, new Error("Socket is disconnected unexpectedly"));
2977
+ });
2978
+ this.socket.on("data", onDataEnroll);
2979
+ }).catch((err) => {
2980
+ console.error("Promise Rejected:", err); // Log the rejection reason
2981
+ throw err; // Re-throw the error to be handled by the caller
2982
+ });
2983
+ }
2984
+ /**
2985
+ * Register events
2986
+ * @param {number} flags - Event flags
2987
+ * @returns {Promise<void>}
2988
+ * @throws {ZKErrorResponse} If registration fails
2989
+ */
2990
+ async regEvent(flags) {
2991
+ try {
2992
+ const commandString = Buffer.alloc(4); // 'I' format is 4 bytes
2993
+ commandString.writeUInt32LE(flags, 0); // Little-endian unsigned int
2994
+ const cmdResponse = await this.executeCmd(COMMANDS.CMD_REG_EVENT, commandString);
2995
+ if (this.verbose)
2996
+ console.log("regEvent: ", cmdResponse.readUInt16LE(0));
2997
+ }
2998
+ catch (e) {
2999
+ throw new ZkError(e, COMMANDS.CMD_REG_EVENT, this.ip);
3000
+ }
3001
+ }
3002
+ async cancelCapture() {
3003
+ try {
3004
+ const reply = await this.executeCmd(COMMANDS.CMD_CANCELCAPTURE, "");
3005
+ return !!reply;
3006
+ }
3007
+ catch (e) {
3008
+ throw new ZkError(e, COMMANDS.CMD_CANCELCAPTURE, this.ip);
3009
+ }
3010
+ }
3011
+ async restartDevice() {
3012
+ try {
3013
+ await this.executeCmd(COMMANDS.CMD_RESTART, "");
3014
+ }
3015
+ catch (e) {
3016
+ throw new ZkError(e, COMMANDS.CMD_RESTART, this.ip);
3017
+ }
3018
+ }
3019
+ }
3020
+
3021
+ class ZUDP {
3022
+ ip;
3023
+ port;
3024
+ timeout;
3025
+ socket;
3026
+ sessionId;
3027
+ replyId;
3028
+ inport;
3029
+ comm_key;
3030
+ constructor(ip, port, timeout, inport, comm_key = 0) {
3031
+ this.ip = ip;
3032
+ this.port = port;
3033
+ this.timeout = timeout;
3034
+ this.socket = null;
3035
+ this.sessionId = null;
3036
+ this.replyId = 0;
3037
+ this.inport = inport;
3038
+ this.comm_key = comm_key;
3039
+ }
3040
+ createSocket(cbError, cbClose) {
3041
+ return new Promise((resolve, reject) => {
3042
+ this.socket = dgram.createSocket('udp4');
3043
+ this.socket.setMaxListeners(Infinity);
3044
+ this.socket.once('error', (err) => {
3045
+ this.socket = null;
3046
+ reject(err);
3047
+ if (cbError)
3048
+ cbError(err);
3049
+ });
3050
+ this.socket.once('close', () => {
3051
+ this.socket = null;
3052
+ if (cbClose)
3053
+ cbClose('udp');
3054
+ });
3055
+ this.socket.once('listening', () => {
3056
+ resolve(this.socket);
3057
+ });
3058
+ try {
3059
+ this.socket.bind(this.inport);
3060
+ }
3061
+ catch (err) {
3062
+ this.socket = null;
3063
+ reject(err);
3064
+ if (cbError)
3065
+ cbError(err);
3066
+ }
3067
+ });
3068
+ }
3069
+ async connect() {
3070
+ try {
3071
+ let reply = await this.executeCmd(COMMANDS.CMD_CONNECT, '');
3072
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
3073
+ return true;
3074
+ }
3075
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_UNAUTH) {
3076
+ const hashedCommkey = authKey(this.comm_key, this.sessionId);
3077
+ reply = await this.executeCmd(COMMANDS.CMD_AUTH, hashedCommkey);
3078
+ if (reply.readUInt16LE(0) === COMMANDS.CMD_ACK_OK) {
3079
+ return true;
3080
+ }
3081
+ else {
3082
+ throw new Error('Authentication error');
3083
+ }
3084
+ }
3085
+ else {
3086
+ throw new Error('NO_REPLY_ON_CMD_CONNECT');
3087
+ }
3088
+ }
3089
+ catch (err) {
3090
+ console.error('Error in connect method:', err);
3091
+ throw err;
3092
+ }
3093
+ }
3094
+ async closeSocket() {
3095
+ return new Promise((resolve, reject) => {
3096
+ if (!this.socket) {
3097
+ resolve(true);
3098
+ return;
3099
+ }
3100
+ const timeout = 2000;
3101
+ const timer = setTimeout(() => {
3102
+ console.warn('Socket close timeout');
3103
+ resolve(true);
3104
+ }, timeout);
3105
+ this.socket.removeAllListeners('message');
3106
+ // @ts-ignore
3107
+ this.socket.close((err) => {
3108
+ clearTimeout(timer);
3109
+ if (err) {
3110
+ console.error('Error closing socket:', err);
3111
+ reject(err);
3112
+ }
3113
+ else {
3114
+ resolve(true);
3115
+ }
3116
+ this.socket = null;
3117
+ });
3118
+ });
3119
+ }
3120
+ writeMessage(msg, connect) {
3121
+ return new Promise((resolve, reject) => {
3122
+ if (!this.socket) {
3123
+ reject(new Error('Socket not initialized'));
3124
+ return;
3125
+ }
3126
+ let sendTimeoutId;
3127
+ const onMessage = (data) => {
3128
+ clearTimeout(sendTimeoutId);
3129
+ this.socket.removeListener('message', onMessage);
3130
+ resolve(data);
3131
+ };
3132
+ this.socket.once('message', onMessage);
3133
+ this.socket.send(msg, 0, msg.length, this.port, this.ip, (err) => {
3134
+ if (err) {
3135
+ this.socket.removeListener('message', onMessage);
3136
+ reject(err);
3137
+ return;
3138
+ }
3139
+ if (this.timeout) {
3140
+ sendTimeoutId = setTimeout(() => {
3141
+ this.socket.removeListener('message', onMessage);
3142
+ reject(new Error('TIMEOUT_ON_WRITING_MESSAGE'));
3143
+ }, connect ? 2000 : this.timeout);
3144
+ }
3145
+ });
3146
+ });
3147
+ }
3148
+ requestData(msg) {
3149
+ return new Promise((resolve, reject) => {
3150
+ if (!this.socket) {
3151
+ reject(new Error('Socket not initialized'));
3152
+ return;
3153
+ }
3154
+ let sendTimeoutId;
3155
+ let responseTimeoutId;
3156
+ const handleOnData = (data) => {
3157
+ if (checkNotEventUDP(data))
3158
+ return;
3159
+ clearTimeout(sendTimeoutId);
3160
+ clearTimeout(responseTimeoutId);
3161
+ this.socket.removeListener('message', handleOnData);
3162
+ resolve(data);
3163
+ };
3164
+ const onReceiveTimeout = () => {
3165
+ this.socket.removeListener('message', handleOnData);
3166
+ reject(new Error('TIMEOUT_ON_RECEIVING_REQUEST_DATA'));
3167
+ };
3168
+ this.socket.on('message', handleOnData);
3169
+ this.socket.send(msg, 0, msg.length, this.port, this.ip, (err) => {
3170
+ if (err) {
3171
+ this.socket.removeListener('message', handleOnData);
3172
+ reject(err);
3173
+ return;
3174
+ }
3175
+ responseTimeoutId = setTimeout(onReceiveTimeout, this.timeout);
3176
+ });
3177
+ sendTimeoutId = setTimeout(() => {
3178
+ this.socket.removeListener('message', handleOnData);
3179
+ reject(new Error('TIMEOUT_IN_RECEIVING_RESPONSE_AFTER_REQUESTING_DATA'));
3180
+ }, this.timeout);
3181
+ });
3182
+ }
3183
+ async executeCmd(command, data) {
3184
+ try {
3185
+ if (command === COMMANDS.CMD_CONNECT) {
3186
+ this.sessionId = 0;
3187
+ this.replyId = 0;
3188
+ }
3189
+ else {
3190
+ this.replyId++;
3191
+ }
3192
+ const buf = createUDPHeader(command, this.sessionId, this.replyId, data);
3193
+ const reply = await this.writeMessage(buf, command === COMMANDS.CMD_CONNECT || command === COMMANDS.CMD_EXIT);
3194
+ if (reply && reply.length > 0) {
3195
+ if (command === COMMANDS.CMD_CONNECT) {
3196
+ this.sessionId = reply.readUInt16LE(4);
3197
+ }
3198
+ }
3199
+ return reply;
3200
+ }
3201
+ catch (err) {
3202
+ console.error(`Error executing command ${command}:`, err);
3203
+ throw err;
3204
+ }
3205
+ }
3206
+ async sendChunkRequest(start, size) {
3207
+ this.replyId++;
3208
+ const reqData = Buffer.alloc(8);
3209
+ reqData.writeUInt32LE(start, 0);
3210
+ reqData.writeUInt32LE(size, 4);
3211
+ const buf = createUDPHeader(COMMANDS.CMD_DATA_RDY, this.sessionId, this.replyId, reqData);
3212
+ try {
3213
+ await new Promise((resolve, reject) => {
3214
+ this.socket.send(buf, 0, buf.length, this.port, this.ip, (err) => {
3215
+ if (err) {
3216
+ log(`[UDP][SEND_CHUNK_REQUEST] Error sending chunk request: ${err.message}`);
3217
+ reject(err);
3218
+ }
3219
+ else {
3220
+ resolve();
3221
+ }
3222
+ });
3223
+ });
3224
+ }
3225
+ catch (error) {
3226
+ log(`[UDP][SEND_CHUNK_REQUEST] Exception: ${error.message}`);
3227
+ throw error;
3228
+ }
3229
+ }
3230
+ async readWithBuffer(reqData, cb = null) {
3231
+ this.replyId++;
3232
+ const buf = createUDPHeader(COMMANDS.CMD_DATA_WRRQ, this.sessionId, this.replyId, reqData);
3233
+ try {
3234
+ const reply = await this.requestData(buf);
3235
+ const header = decodeUDPHeader(reply.subarray(0, 8));
3236
+ switch (header.commandId) {
3237
+ case COMMANDS.CMD_DATA:
3238
+ return { data: reply.subarray(8), err: null };
3239
+ case COMMANDS.CMD_ACK_OK:
3240
+ case COMMANDS.CMD_PREPARE_DATA:
3241
+ return await this.handleChunkedData(reply, header.commandId, cb);
3242
+ default:
3243
+ throw new Error('ERROR_IN_UNHANDLE_CMD ' + exportErrorMessage(header.commandId));
3244
+ }
3245
+ }
3246
+ catch (err) {
3247
+ return { data: null, err: err };
3248
+ }
3249
+ }
3250
+ async handleChunkedData(reply, commandId, cb) {
3251
+ return new Promise((resolve) => {
3252
+ const recvData = reply.subarray(8);
3253
+ const size = recvData.readUIntLE(1, 4);
3254
+ let totalBuffer = Buffer.from([]);
3255
+ const timeout = 3000;
3256
+ let timer = setTimeout(() => {
3257
+ this.socket.removeListener('message', handleOnData);
3258
+ resolve({ data: null, err: new Error('TIMEOUT WHEN RECEIVING PACKET') });
3259
+ }, timeout);
3260
+ const internalCallback = (replyData, err = null) => {
3261
+ this.socket.removeListener('message', handleOnData);
3262
+ clearTimeout(timer);
3263
+ resolve({ data: err ? null : replyData, err });
3264
+ };
3265
+ const handleOnData = (reply) => {
3266
+ if (checkNotEventUDP(reply))
3267
+ return;
3268
+ clearTimeout(timer);
3269
+ timer = setTimeout(() => {
3270
+ internalCallback(totalBuffer, new Error(`TIMEOUT !! ${(size - totalBuffer.length) / size} % REMAIN !`));
3271
+ }, timeout);
3272
+ const header = decodeUDPHeader(reply);
3273
+ switch (header.commandId) {
3274
+ case COMMANDS.CMD_PREPARE_DATA:
3275
+ break;
3276
+ case COMMANDS.CMD_DATA:
3277
+ totalBuffer = Buffer.concat([totalBuffer, reply.subarray(8)]);
3278
+ cb && cb(totalBuffer.length, size);
3279
+ break;
3280
+ case COMMANDS.CMD_ACK_OK:
3281
+ if (totalBuffer.length === size) {
3282
+ internalCallback(totalBuffer);
3283
+ }
3284
+ break;
3285
+ default:
3286
+ internalCallback(Buffer.from([]), new Error('ERROR_IN_UNHANDLE_CMD ' + exportErrorMessage(header.commandId)));
3287
+ }
3288
+ };
3289
+ this.socket.on('message', handleOnData);
3290
+ const chunkCount = Math.ceil(size / Constants.MAX_CHUNK);
3291
+ for (let i = 0; i < chunkCount; i++) {
3292
+ const start = i * Constants.MAX_CHUNK;
3293
+ const chunkSize = (i === chunkCount - 1) ? size % Constants.MAX_CHUNK : Constants.MAX_CHUNK;
3294
+ this.sendChunkRequest(start, chunkSize).catch(err => {
3295
+ internalCallback(Buffer.from([]), err);
3296
+ });
3297
+ }
3298
+ });
3299
+ }
3300
+ async getUsers() {
3301
+ try {
3302
+ if (this.socket) {
3303
+ await this.freeData();
3304
+ }
3305
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_USERS);
3306
+ if (this.socket) {
3307
+ await this.freeData();
3308
+ }
3309
+ const USER_PACKET_SIZE = 28;
3310
+ let userData = data.data?.subarray(4) || Buffer.from([]);
3311
+ const users = [];
3312
+ while (userData.length >= USER_PACKET_SIZE) {
3313
+ const user = decodeUserData28(userData.subarray(0, USER_PACKET_SIZE));
3314
+ users.push(user);
3315
+ userData = userData.subarray(USER_PACKET_SIZE);
3316
+ }
3317
+ return { data: users };
3318
+ }
3319
+ catch (err) {
3320
+ throw new Error(err.message);
3321
+ }
3322
+ }
3323
+ async getAttendances(callbackInProcess) {
3324
+ try {
3325
+ if (this.socket) {
3326
+ await this.freeData();
3327
+ }
3328
+ const data = await this.readWithBuffer(REQUEST_DATA.GET_ATTENDANCE_LOGS);
3329
+ if (this.socket) {
3330
+ await this.freeData();
3331
+ }
3332
+ const RECORD_PACKET_SIZE = 16;
3333
+ let recordData = data.data?.subarray(4) || Buffer.from([]);
3334
+ const records = [];
3335
+ while (recordData.length >= RECORD_PACKET_SIZE) {
3336
+ const record = decodeRecordData16(recordData.subarray(0, RECORD_PACKET_SIZE));
3337
+ records.push({ ...record, ip: this.ip });
3338
+ recordData = recordData.subarray(RECORD_PACKET_SIZE);
3339
+ }
3340
+ return { data: records, err: data.err };
3341
+ }
3342
+ catch (err) {
3343
+ return { data: [], err: err };
3344
+ }
3345
+ }
3346
+ async freeData() {
3347
+ try {
3348
+ const resp = await this.executeCmd(COMMANDS.CMD_FREE_DATA, Buffer.alloc(0));
3349
+ return !!resp;
3350
+ }
3351
+ catch (err) {
3352
+ console.error('Error freeing data:', err);
3353
+ throw err;
3354
+ }
3355
+ }
3356
+ async getInfo() {
3357
+ try {
3358
+ const data = await this.executeCmd(COMMANDS.CMD_GET_FREE_SIZES, Buffer.alloc(0));
3359
+ return {
3360
+ userCounts: data.readUIntLE(24, 4),
3361
+ logCounts: data.readUIntLE(40, 4),
3362
+ logCapacity: data.readUIntLE(72, 4)
3363
+ };
3364
+ }
3365
+ catch (err) {
3366
+ console.error('Error retrieving info:', err);
3367
+ throw err;
3368
+ }
3369
+ }
3370
+ async getTime() {
3371
+ try {
3372
+ const response = await this.executeCmd(COMMANDS.CMD_GET_TIME, Buffer.alloc(0));
3373
+ const timeValue = response.readUInt32LE(8);
3374
+ return timeParser.decode(timeValue);
3375
+ }
3376
+ catch (err) {
3377
+ console.error('Error retrieving time:', err);
3378
+ throw err;
3379
+ }
3380
+ }
3381
+ async setTime(tm) {
3382
+ try {
3383
+ const commandBuffer = Buffer.alloc(32);
3384
+ commandBuffer.writeUInt32LE(timeParser.encode(new Date(tm)), 0);
3385
+ await this.executeCmd(COMMANDS.CMD_SET_TIME, commandBuffer);
3386
+ return true;
3387
+ }
3388
+ catch (err) {
3389
+ console.error('Error setting time:', err);
3390
+ throw err;
3391
+ }
3392
+ }
3393
+ async clearAttendanceLog() {
3394
+ try {
3395
+ return !!await this.executeCmd(COMMANDS.CMD_CLEAR_ATTLOG, Buffer.alloc(0));
3396
+ }
3397
+ catch (err) {
3398
+ console.error('Error clearing attendance log:', err);
3399
+ throw err;
3400
+ }
3401
+ }
3402
+ async clearData() {
3403
+ try {
3404
+ return !!await this.executeCmd(COMMANDS.CMD_CLEAR_DATA, Buffer.alloc(0));
3405
+ }
3406
+ catch (err) {
3407
+ console.error('Error clearing data:', err);
3408
+ throw err;
3409
+ }
3410
+ }
3411
+ async disableDevice() {
3412
+ try {
3413
+ const resp = await this.executeCmd(COMMANDS.CMD_DISABLEDEVICE, REQUEST_DATA.DISABLE_DEVICE);
3414
+ return !!resp;
3415
+ }
3416
+ catch (err) {
3417
+ console.error('Error disabling device:', err);
3418
+ throw err;
3419
+ }
3420
+ }
3421
+ async enableDevice() {
3422
+ try {
3423
+ const resp = await this.executeCmd(COMMANDS.CMD_ENABLEDEVICE, Buffer.alloc(0));
3424
+ return !!resp;
3425
+ }
3426
+ catch (err) {
3427
+ console.error('Error enabling device:', err);
3428
+ throw err;
3429
+ }
3430
+ }
3431
+ async disconnect() {
3432
+ try {
3433
+ await this.executeCmd(COMMANDS.CMD_EXIT, Buffer.alloc(0));
3434
+ }
3435
+ catch (err) {
3436
+ console.error('Error executing disconnect command:', err);
3437
+ }
3438
+ try {
3439
+ await this.closeSocket();
3440
+ }
3441
+ catch (err) {
3442
+ console.error('Error closing the socket:', err);
3443
+ }
3444
+ }
3445
+ async getRealTimeLogs(cb = () => { }) {
3446
+ this.replyId++;
3447
+ const buf = createUDPHeader(COMMANDS.CMD_REG_EVENT, this.sessionId, this.replyId, REQUEST_DATA.GET_REAL_TIME_EVENT);
3448
+ try {
3449
+ this.socket.send(buf, 0, buf.length, this.port, this.ip, (err) => {
3450
+ if (err) {
3451
+ console.error('Error sending UDP message:', err);
3452
+ return;
3453
+ }
3454
+ console.log('UDP message sent successfully');
3455
+ });
3456
+ }
3457
+ catch (err) {
3458
+ console.error('Error during send operation:', err);
3459
+ return;
3460
+ }
3461
+ const handleMessage = (data) => {
3462
+ if (!checkNotEventUDP(data))
3463
+ return;
3464
+ if (data.length === 18) {
3465
+ cb(decodeRecordRealTimeLog18(data));
3466
+ }
3467
+ };
3468
+ if (this.socket.listenerCount('message') === 0) {
3469
+ this.socket.on('message', handleMessage);
3470
+ }
3471
+ else {
3472
+ console.warn('Multiple message listeners detected. Ensure only one listener is attached.');
3473
+ }
3474
+ }
3475
+ }
3476
+
5
3477
  class Zklib {
6
3478
  set connectionType(value) {
7
3479
  this._connectionType = value;
@@ -29,8 +3501,8 @@ class Zklib {
29
3501
  constructor(ip, port = 4370, timeout = 5000, inport = 10000, comm_key = 0, verbose = false) {
30
3502
  this.ip = ip;
31
3503
  this.comm_key = comm_key;
32
- this.ztcp = new ztcp_1.ZTCP(ip, port, timeout, comm_key, verbose);
33
- this.zudp = new zudp_1.ZUDP(ip, port, timeout, inport);
3504
+ this.ztcp = new ZTCP(ip, port, timeout, comm_key, verbose);
3505
+ this.zudp = new ZUDP(ip, port, timeout, inport);
34
3506
  }
35
3507
  async functionWrapper(tcpCallback, udpCallback, command) {
36
3508
  try {
@@ -40,21 +3512,21 @@ class Zklib {
40
3512
  return await tcpCallback();
41
3513
  }
42
3514
  else {
43
- throw new handler_1.ZkError(new Error("TCP socket isn't connected!"), `[TCP] ${command}`, this.ip);
3515
+ throw new ZkError(new Error("TCP socket isn't connected!"), `[TCP] ${command}`, this.ip);
44
3516
  }
45
3517
  case "udp":
46
3518
  if (this.zudp && this.zudp.socket) {
47
3519
  return await udpCallback();
48
3520
  }
49
3521
  else {
50
- throw new handler_1.ZkError(new Error("UDP socket isn't connected!"), `[UDP] ${command}`, this.ip);
3522
+ throw new ZkError(new Error("UDP socket isn't connected!"), `[UDP] ${command}`, this.ip);
51
3523
  }
52
3524
  default:
53
- throw new handler_1.ZkError(new Error("Unsupported connection type or socket isn't connected!"), "", this.ip);
3525
+ throw new ZkError(new Error("Unsupported connection type or socket isn't connected!"), "", this.ip);
54
3526
  }
55
3527
  }
56
3528
  catch (err) {
57
- throw new handler_1.ZkError(err, `[${this._connectionType?.toUpperCase()}] ${command}`, this.ip);
3529
+ throw new ZkError(err, `[${this._connectionType?.toUpperCase()}] ${command}`, this.ip);
58
3530
  }
59
3531
  }
60
3532
  async createSocket(cbErr, cbClose) {
@@ -67,7 +3539,7 @@ class Zklib {
67
3539
  return true;
68
3540
  }
69
3541
  catch (err) {
70
- throw new handler_1.ZkError(err, "TCP CONNECT", this.ip);
3542
+ throw new ZkError(err, "TCP CONNECT", this.ip);
71
3543
  }
72
3544
  }
73
3545
  else {
@@ -79,7 +3551,7 @@ class Zklib {
79
3551
  return true;
80
3552
  }
81
3553
  catch (err) {
82
- throw new handler_1.ZkError(err, "TCP CONNECT", this.ip);
3554
+ throw new ZkError(err, "TCP CONNECT", this.ip);
83
3555
  }
84
3556
  }
85
3557
  }
@@ -91,8 +3563,8 @@ class Zklib {
91
3563
  catch (disconnectErr) {
92
3564
  console.error("Error disconnecting TCP:", disconnectErr);
93
3565
  }
94
- if (err.code !== handler_1.ERROR_TYPES.ECONNREFUSED) {
95
- throw new handler_1.ZkError(err, "TCP CONNECT", this.ip);
3566
+ if (err.code !== ERROR_TYPES.ECONNREFUSED) {
3567
+ throw new ZkError(err, "TCP CONNECT", this.ip);
96
3568
  }
97
3569
  try {
98
3570
  if (!this.zudp.socket) {
@@ -112,7 +3584,7 @@ class Zklib {
112
3584
  catch (disconnectErr) {
113
3585
  console.error("Error disconnecting UDP:", disconnectErr);
114
3586
  }
115
- throw new handler_1.ZkError(err, "UDP CONNECT", this.ip);
3587
+ throw new ZkError(err, "UDP CONNECT", this.ip);
116
3588
  }
117
3589
  this._connectionType = "udp";
118
3590
  return true;
@@ -337,4 +3809,5 @@ class Zklib {
337
3809
  }, "NETWORK_PARAMS");
338
3810
  }
339
3811
  }
340
- exports.default = Zklib;
3812
+
3813
+ export { Zklib as default };