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