-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathUdpZkClient.php
580 lines (504 loc) · 20.1 KB
/
UdpZkClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<?php
namespace ZK;
class UdpZkClient {
const USHRT_MAX = 65535;
const CMD_CONNECT = 1000;
const CMD_EXIT = 1001;
const CMD_ENABLEDEVICE = 1002;
const CMD_DISABLEDEVICE = 1003;
const CMD_RESTART = 1004;
const CMD_POWEROFF = 1005;
const CMD_ACK_OK = 2000;
const CMD_ACK_ERROR = 2001;
const CMD_ACK_DATA = 2002;
const CMD_PREPARE_DATA = 1500;
const CMD_DATA = 1501;
const CMD_USERTEMP_RRQ = 9;
const CMD_ATTLOG_RRQ = 13;
const CMD_CLEAR_DATA = 14;
const CMD_CLEAR_ATTLOG = 15;
const CMD_WRITE_LCD = 66;
const CMD_GET_TIME = 201;
const CMD_SET_TIME = 202;
const CMD_VERSION = 1100;
const CMD_AUTH = 1102;
const CMD_DEVICE = 11;
const CMD_CLEAR_ADMIN = 20;
const CMD_SET_USER = 8;
const CMD_GET_FREE_SIZES = 50;
const CMD_TZ_RRQ = 27;
const CMD_TZ_WRQ = 28;
const CMD_UNLOCK = 31;
const EMPTY_STRING = '';
const CUSTOMIZED_COMMAND_STRING = null;
const DEVICE_GENERAL_INFO_STRING_LENGTH = 184;
const XML_FAIL_RESPONSE = 'Fail!';
const XML_SUCCESS_RESPONSE = 'Successfully!';
private $host;
private $port;
private $encoding;
private $client_socket;
private $data_recv = '';
private $session_id = 0;
private $result;
private $zklib_commands = [
'get_platform' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~Platform',
'should_disconnect' => true,
'result_filter_string' => '~Platform='
],
'get_fingerprint_algorithm' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~ZKFPVersion',
'should_disconnect' => true,
'result_filter_string' => '~ZKFPVersion='
],
'get_serial_number' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~SerialNumber',
'should_disconnect' => true,
'result_filter_string' => '~SerialNumber='
],
'get_oem_vendor' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~OEMVendor',
'should_disconnect' => true,
'result_filter_string' => '~OEMVendor='
],
'get_mac_address' => [
'command_id' => self::CMD_DEVICE,
'command_string' => 'MAC',
'should_disconnect' => true,
'result_filter_string' => 'MAC='
],
'get_device_name' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~DeviceName',
'should_disconnect' => true,
'result_filter_string' => '~DeviceName='
],
'get_manufacture_time' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~ProductTime',
'should_disconnect' => true,
'result_filter_string' => '~ProductTime='
],
'get_anthostassback_mode' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~APBFO',
'should_disconnect' => true,
'result_filter_string' => '~APBFO='
],
'get_workcode' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~WCFO',
'should_disconnect' => true,
'result_filter_string' => '~WCFO='
],
'get_ext_format_mode' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~ExtendFmt',
'should_disconnect' => true,
'result_filter_string' => '~ExtendFmt='
],
'get_encrypted_mode' => [
'command_id' => self::CMD_DEVICE,
'command_string' => 'encrypt_out',
'should_disconnect' => true,
'result_filter_string' => 'encrypt_out='
],
'get_pin2_width' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~PIN2Width',
'should_disconnect' => true,
'result_filter_string' => '~PIN2Width='
],
'get_ssr_mode' => [
'command_id' => self::CMD_DEVICE,
'command_string' => '~SSR',
'should_disconnect' => true,
'result_filter_string' => '~SSR='
],
'get_firmware_version' => [
'command_id' => self::CMD_VERSION,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'get_free_sizes' => [
'command_id' => self::CMD_GET_FREE_SIZES,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'set_date' => [
'command_id' => self::CMD_SET_TIME,
'command_string' => self::CUSTOMIZED_COMMAND_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'delete_admin' => [
'command_id' => self::CMD_CLEAR_ADMIN,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'enable' => [
'command_id' => self::CMD_ENABLEDEVICE,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'disable' => [
'command_id' => self::CMD_DISABLEDEVICE,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => false,
'result_filter_string' => false
],
'restart' => [
'command_id' => self::CMD_RESTART,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'unlock' => [
'command_id' => self::CMD_UNLOCK,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
'poweroff' => [
'command_id' => self::CMD_POWEROFF,
'command_string' => self::EMPTY_STRING,
'should_disconnect' => true,
'result_filter_string' => false
],
];
public function setCommandOption($command_option) {
$command = $command_option["command"];
$option_name = $command_option["option"]["name"];
$value_name = $command_option["option"]["value"];
$filter = $command_option["option"]["filter"];
$this->zklib_commands[$command][$option_name] = $value_name;
$this->zklib_commands[$command]["result_filter_string"] = $filter;
}
public function __construct($option) {
$this->host = $option["host"];
$this->port = $option["port"];
$this->encoding = $option["encoding"];
$this->client_socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$timeout = ['sec' => $option['connection_timeout'], 'usec' => 500000];
socket_set_option($this->client_socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
}
private function connect() {
$command = self::CMD_CONNECT;
$command_string = self::EMPTY_STRING;
$chksum = 0;
$session_id = 0;
$reply_id = -1 + self::USHRT_MAX;
$buf = $this->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
socket_sendto($this->client_socket, $buf, strlen($buf), 0, $this->host, $this->port);
try {
socket_recvfrom($this->client_socket, $this->data_recv, 1024, 0, $this->host, $this->port);
if (strlen($this->data_recv) > 0) {
$u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6', substr($this->data_recv, 0, 8));
$this->session_id = hexdec($u['h6'] . $u['h5']);
return $this->checkValid($this->data_recv);
} else {
return false;
}
} catch (ErrorException $e) {
return false;
} catch (exception $e) {
return false;
}
}
private function disconnect() {
$command = self::CMD_EXIT;
$command_string = '';
$chksum = 0;
$session_id = $this->session_id;
$u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6/H2h7/H2h8', substr($this->data_recv, 0, 8));
$reply_id = hexdec($u['h8'] . $u['h7']);
$buf = $this->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
socket_sendto($this->client_socket, $buf, strlen($buf), 0, $this->host, $this->port);
try {
socket_recvfrom($this->client_socket, $this->data_recv, 1024, 0, $this->host, $this->port);
return $this->checkValid($this->data_recv);
} catch (ErrorException $e) {
return false;
} catch (Exception $e) {
return false;
}
}
/**
* Gets device's information about current device's storage.
*
* @return array device's storage information.
*/
public function zk_get_free_sizes() {
$fs = [];
$free_sizes_info = $this->reverse_hex(bin2hex($this->send_command_to_device(self::CMD_GET_FREE_SIZES)));
if (!$free_sizes_info) {
$fs = false;
} else {
if (self::DEVICE_GENERAL_INFO_STRING_LENGTH > strlen($free_sizes_info)) {
$free_sizes_info = '000000000000000000000000' . $free_sizes_info;
}
$fs['att_logs_available'] = hexdec(substr($free_sizes_info, 27, 5));
$fs['templates_available'] = hexdec(substr($free_sizes_info, 44, 4));
$fs['att_logs_capacity'] = hexdec(substr($free_sizes_info, 51, 5));
$fs['templates_capacity'] = hexdec(substr($free_sizes_info, 60, 4));
$fs['passwords_stored'] = hexdec(substr($free_sizes_info, 76, 4));
$fs['admins_stored'] = hexdec(substr($free_sizes_info, 84, 4));
$fs['att_logs_stored'] = hexdec(substr($free_sizes_info, 116, 4));
$fs['templates_stored'] = hexdec(substr($free_sizes_info, 132, 4));
$fs['users_stored'] = hexdec(substr($free_sizes_info, 148, 4));
}
return $fs;
}
/**
* Helper that allows sending command to device.
*
* @param integer $command command code.
* @param string $command_string subcommand.
* @param int $reply_id device's reply.
* @return boolean <b><code>true</code></b> on successfully, otherwise returns <b><code>false</code></b>.
*/
private function send_command_to_device($command, $command_string = '', $reply_id = null) {
$chksum = 0;
$session_id = $this->session_id;
$u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6/H2h7/H2h8', substr($this->data_recv, 0, 8));
if (is_null($reply_id)) {
$reply_id = hexdec($u['h8'] . $u['h7']);
}
$buf = $this->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
socket_sendto($this->client_socket, $buf, strlen($buf), 0, $this->host, $this->port);
try {
socket_recvfrom($this->client_socket, $this->data_recv, 1024, 0, $this->host, $this->port);
$u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6', substr($this->data_recv, 0, 8));
$this->session_id = hexdec($u['h6'] . $u['h5']);
$this->result = $this->checkValid($this->data_recv);
return substr($this->data_recv, 8);
} catch (ErrorException $e) {
return false;
} catch (exception $e) {
return false;
}
}
public function __call($command, array $args) {
$should_disconnect = true;
$args = count($args) === 0 ? [] : array_shift($args);
$encoding = $this->encoding;
//unset($this->encoding);
$this->connect();
switch ($command) {
case 'set_date':
$response = $this->zk_set_date($args);
break;
case 'get_free_sizes':
$response = $this->zk_get_free_sizes();
break;
default:
$should_disconnect = $this->zklib_commands[$command]['should_disconnect'];
$response = $this->send_command_to_device(
$this->zklib_commands[$command]['command_id'], $this->zklib_commands[$command]['command_string']
);
}
$result_filter_string = $this->zklib_commands[$command]['result_filter_string'];
$response = $this->build_command_response($command, $this->result, $response, $encoding, $result_filter_string);
$should_disconnect && $this->disconnect();
return simplexml_load_string($response);
//return new TADResponse($response, $encoding);
}
/**
* Calculates the chksum of the packet to be sent to the device.
*
* @param string $p packed sent to the device.
* @return string checksum calculated.
*/
private function createChkSum($p) {
/* This function
Copied from zkemsdk.c */
$l = count($p);
$chksum = 0;
$i = $l;
$j = 1;
while ($i > 1) {
$u = unpack('S', pack('C2', $p['c' . $j], $p['c' . ($j + 1)]));
$chksum += $u[1];
if ($chksum > self::USHRT_MAX) {
$chksum -= self::USHRT_MAX;
}
$i-=2;
$j+=2;
}
if ($i) {
$chksum = $chksum + $p['c' . strval(count($p))];
}
while ($chksum > self::USHRT_MAX) {
$chksum -= self::USHRT_MAX;
}
if ($chksum > 0) {
$chksum = -($chksum);
} else {
$chksum = abs($chksum);
}
$chksum -= 1;
while ($chksum < 0) {
$chksum += self::USHRT_MAX;
}
return pack('S', $chksum);
}
/**
* Creates UDP header to be sent to the device.
*
* @param int $command command id.
* @param string $chksum checksum associated.
* @param int $session_id session id associated.
* @param int $reply_id reply id associated.
* @param string $command_string subcomand.
* @return string UDP header.
*/
private function createHeader($command, $chksum, $session_id, $reply_id, $command_string) {
/* This function puts a the parts that make up a packet together and
packs them into a byte string */
$buf = pack('SSSS', $command, $chksum, $session_id, $reply_id) . $command_string;
$buf = unpack('C' . (8 + strlen($command_string)) . 'c', $buf);
$u = unpack('S', $this->createChkSum($buf));
if (is_array($u)) {
while (list($key) = each($u)) {
$u = $u[$key];
break;
}
}
$chksum = $u;
$reply_id += 1;
if ($reply_id >= self::USHRT_MAX) {
$reply_id -= self::USHRT_MAX;
}
$buf = pack('SSSS', $command, $chksum, $session_id, $reply_id);
return $buf . $command_string;
}
/**
* Checks a returned packet to see if it returned CMD_ACK_OK, indicating success.
*
* @param string $reply packet received from the device.
*
* @return boolean <b><code>true</code></b> on valid packet, otherwise returns <b><code>false</code></b>.
*/
private function checkValid($reply) {
$u = unpack('H2h1/H2h2', substr($reply, 0, 8));
$command = hexdec($u['h2'] . $u['h1']);
if ($command == self::CMD_ACK_OK) {
return true;
} else {
return false;
}
}
/**
* Builds a command response with a XML format to keep TAD behavior.
*
* @param string $command command executed.
* @param mixed $result command result.
* @return string XML response.
*/
private function build_command_response($command, $result_code, $result, $encoding, $result_filter_string = false) {
$response_data = [];
$xml_tag = str_replace('_', ' ', $command);
$base_xml_tag = join('', explode(' ', ucwords($xml_tag))) . 'Response';
if (is_array($result)) {
if (0 === count($result)) {
$xml_header = '';
$response = $xml_header . '<' . $base_xml_tag . '>' . '</' . $base_xml_tag . '>';
return $response;
}
$response_data = ['Row' => $result];
} else {
if (!is_bool($result) && true === $result_code) {
$result_filter_string = $result_filter_string ? $result_filter_string : null;
$result_data = str_replace($result_filter_string, '', $result);
} else {
$result_data = ($result_code ? self::XML_SUCCESS_RESPONSE : self::XML_FAIL_RESPONSE);
}
$result_code = $result_code ? '1' : '0';
$response_data = ['Row' => ['Result' => $result_code, 'Information' => $result_data]];
}
return $this->array_to_xml(new \SimpleXMLElement('<' . $base_xml_tag . '/>'), $response_data, $encoding);
}
/**
* Take an array in the form of <code>['date'=>date_value, 'time'=>time_value]</code> y returns
* another array with the following form:
*
* <code>
* ['year'=>foo_year, 'month'=>bar_month, 'day'=>taz_day,
* 'hour'=>foo_hour, 'minute=>bar_minute, 'second'=>taz_minute]
* </code>
*
* Any missing item from input array is replaced by corresponding element generated from
* current date and time.
*
* @param array $dt input 'datetime' array.
* @return array array generated.
*/
private function setup_datetime(array $dt = []) {
$now = explode(' ', date("Y-m-d H:i:s"));
$dt = array_filter($dt, 'strlen');
!isset($dt['date']) ? $dt['date'] = $now[0] : null;
!isset($dt['time']) ? $dt['time'] = $now[1] : null;
$date = explode('-', $dt['date']);
$time = explode(':', $dt['time']);
return [
'year' => $date[0], 'month' => $date[1], 'day' => $date[2],
'hour' => $time[0], 'minute' => $time[1], 'second' => $time[2]];
}
/**
* Method taken from PHPLib @link http://dnaextrim.github.io/php_zklib/ project.
*
* @param string $hexstr hex string.
* @return string hex string reversed.
*/
private function reverse_hex($hexstr) {
$tmp = '';
for ($i = strlen($hexstr); $i >= 0; $i--) {
$tmp .= substr($hexstr, $i, 2);
$i--;
}
return $tmp;
}
/**
* Method taken from PHPZKLib @link http://dnaextrim.github.io/php_zklib/ project.
*
* It's been modified to accept an associative array as input.
*
* @param array $t array with a timestamp data.
* @return int timestamp encoded.
*/
private function encode_time(array $t) {
/* Encode a timestamp send at the timeclock
copied from zkemsdk.c - EncodeTime */
$d = ( ($t['year'] % 100) * 12 * 31 + (($t['month'] - 1) * 31) + $t['day'] - 1) *
(24 * 60 * 60) + ($t['hour'] * 60 + $t['minute']) * 60 + $t['second'];
return $d;
}
/**
* Transforms an array into an XML string.
*
* @param \SimpleXMLElement $object <code>SimpleXMLElement</code> instance.
* @param array $data input array to be transformed.
* @return string XML string generated.
*/
private function array_to_xml(\SimpleXMLElement $object, array $data) {
foreach ($data as $key => $value) {
if (is_array($value)) {
$new_object = $object->addChild($key);
$this->array_to_xml($new_object, $value);
} else {
$object->addChild($key, $value);
}
}
$xml = trim(str_replace("<?xml version=\"1.0\"?>", '', $object->asXML()));
return $xml;
}
}