-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
phpMQTT.php
703 lines (621 loc) · 20.2 KB
/
phpMQTT.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
<?php
namespace Bluerhinos;
/*
phpMQTT
A simple php class to connect/publish/subscribe to an MQTT broker
*/
/*
Licence
Copyright (c) 2010 Blue Rhinos Consulting | Andrew Milsted
[email protected] | http://www.bluerhinos.co.uk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
Modified by Vladimir Kalachikhin on 2022
*/
/* phpMQTT */
class phpMQTT
{
protected $socket; /* holds the socket */
protected $msgid = 1; /* counter for message id */
public $keepalive = 10; /* default keepalive timmer */
public $timesinceping; /* host unix time, used to detect disconects */
public $topics = []; /* used to store currently subscribed topics. Ключ -- собственно топик, строка, значение -- массив ('qos' => 0, 'function' => ''), function -- это имя функции, которой будет передано $topic, $msg, или строка __direct_return_message__, тогда proc вернёт $msg, а не логическое значение*/
public $debug = false; /* should output debug messages */
public $address; /* broker address */
public $port; /* broker port */
public $clientid; /* client id sent to brocker */
public $will; /* stores the will of the client */
public $userData; /* */
protected $username; /* stores username */
protected $password; /* stores password */
public $cafile;
protected static $known_commands = [
1 => 'CONNECT',
2 => 'CONNACK',
3 => 'PUBLISH',
4 => 'PUBACK',
5 => 'PUBREC',
6 => 'PUBREL',
7 => 'PUBCOMP',
8 => 'SUBSCRIBE',
9 => 'SUBACK',
10 => 'UNSUBSCRIBE',
11 => 'UNSUBACK',
12 => 'PINGREQ',
13 => 'PINGRESP',
14 => 'DISCONNECT'
];
/**
* phpMQTT constructor.
*
* @param $address
* @param $port
* @param $clientid
* @param null $cafile
*/
public function __construct($address, $port, $clientid, $cafile = null)
{
$this->broker($address, $port, $clientid, $cafile);
}
/**
* Sets the broker details
*
* @param $address
* @param $port
* @param $clientid
* @param null $cafile
*/
public function broker($address, $port, $clientid, $cafile = null): void
{
$this->address = $address;
$this->port = $port;
$this->clientid = $clientid;
$this->cafile = $cafile;
}
/**
* Will try and connect, if fails it will sleep 10s and try again, this will enable the script to recover from a network outage
*
* @param bool $clean - should the client send a clean session flag
* @param null $will
* @param null $username
* @param null $password
* @param bool $timeout - trying to connect so many second every 3 sec. If not - infinity.
*
* @return bool
*/
public function connect_auto($clean = true, $will = null, $username = null, $password = null, $timeout=FALSE): bool
{
$now = time();
//echo "connect_auto timeout=$timeout;\n ";
while ($this->connect($clean, $will, $username, $password) === false) { // connect может и не произойти
if($timeout and((time()-$now)>=$timeout)) {
return false;
}
sleep(3);
}
return true;
}
/**
* @param bool $clean - should the client send a clean session flag
* @param null $will
* @param null $username
* @param null $password
*
* @return bool
*/
public function connect($clean = true, $will = null, $username = null, $password = null): bool
{
if ($will) {
$this->will = $will;
}
if ($username) {
$this->username = $username;
}
if ($password) {
$this->password = $password;
}
if ($this->cafile) {
$socketContext = stream_context_create(
[
'ssl' => [
'verify_peer_name' => true,
'cafile' => $this->cafile
]
]
);
$this->socket = @stream_socket_client('tls://' . $this->address . ':' . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext);
} else {
$this->socket = @stream_socket_client('tcp://' . $this->address . ':' . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT);
}
if (!$this->socket) {
$this->_errorMessage("stream_socket_create() $errno, $errstr");
return false;
}
stream_set_timeout($this->socket, 5);
stream_set_blocking($this->socket, 0);
$i = 0;
$buffer = '';
$buffer .= chr(0x00);
$i++; // Length MSB
$buffer .= chr(0x04);
$i++; // Length LSB
$buffer .= chr(0x4d);
$i++; // M
$buffer .= chr(0x51);
$i++; // Q
$buffer .= chr(0x54);
$i++; // T
$buffer .= chr(0x54);
$i++; // T
$buffer .= chr(0x04);
$i++; // // Protocol Level
//No Will
$var = 0;
if ($clean) {
$var += 2;
}
//Add will info to header
if ($this->will !== null) {
$var += 4; // Set will flag
$var += ($this->will['qos'] << 3); //Set will qos
if ($this->will['retain']) {
$var += 32;
} //Set will retain
}
if ($this->username !== null) {
$var += 128;
} //Add username to header
if ($this->password !== null) {
$var += 64;
} //Add password to header
$buffer .= chr($var);
$i++;
//Keep alive
$buffer .= chr($this->keepalive >> 8);
$i++;
$buffer .= chr($this->keepalive & 0xff);
$i++;
$buffer .= $this->strwritestring($this->clientid, $i);
//Adding will to payload
if ($this->will !== null) {
$buffer .= $this->strwritestring($this->will['topic'], $i);
$buffer .= $this->strwritestring($this->will['content'], $i);
}
if ($this->username !== null) {
$buffer .= $this->strwritestring($this->username, $i);
}
if ($this->password !== null) {
$buffer .= $this->strwritestring($this->password, $i);
}
$head = chr(0x10);
while ($i > 0) {
$encodedByte = $i % 128;
$i /= 128;
$i = (int)$i;
if ($i > 0) {
$encodedByte |= 128;
}
$head .= chr($encodedByte);
}
fwrite($this->socket, $head, 2);
fwrite($this->socket, $buffer);
$string = $this->read(4);
if (ord($string[0]) >> 4 === 2 && $string[3] === chr(0)) {
$this->_debugMessage('Connected to Broker');
} else {
$this->_errorMessage(
sprintf(
"Connection failed! (Error: 0x%02x 0x%02x)\n",
ord($string[0]),
ord($string[3])
)
);
return false;
}
$this->timesinceping = time();
return true;
}
/**
* Reads in so many bytes
*
* @param int $int
* @param bool $nb
*
* @return false|string
*/
public function read($int = 8192, $nb = false)
{
$string = '';
$togo = $int;
//echo "read(): togo=$togo; nb=$nb; this->socket:".gettype($this->socket)."\n";
if ($nb) {
return @fread($this->socket, $togo); // сокет мог умереть
}
if(gettype($this->socket) != 'resource') return FALSE; // сокет мог и умереть
while (!feof($this->socket) && $togo > 0) { //
$fread = fread($this->socket, $togo);
$string .= $fread;
$togo = $int - strlen($string);
}
//echo "string=$string;\n";
return $string;
}
/**
* Subscribes to a topic, wait for message and return it
*
* @param $topic
* @param $qos
* @param $timeout - trying to connect so many second or do one try
*
* @return string
*/
public function subscribeAndWaitForMessage($topic, $qos, $timeout=10)
{
$this->subscribe(
[
$topic => [
'qos' => $qos,
'function' => '__direct_return_message__'
]
]
);
$return = array();
do {
$ret = $this->proc(TRUE,$timeout); // почему-то с proc(FALSE) не работает: возвращает только одно случайное значение
//echo "ret: \n"; print_r($ret);
if($ret===FALSE and count($return)) break;
elseif($ret===FALSE) continue;
elseif($ret===null) break;
else {
$return[$ret[0]] = $ret[1];
}
} while (true); //
return $return;
}
/**
* subscribes to topics
*
* @param $topics
* @param int $qos
*/
public function subscribe($topics, $qos = 0): void
{
$i = 0;
$buffer = '';
$id = $this->msgid;
$buffer .= chr($id >> 8);
$i++;
$buffer .= chr($id % 256);
$i++;
foreach ($topics as $key => $topic) {
$buffer .= $this->strwritestring($key, $i);
$buffer .= chr($topic['qos']);
$i++;
$this->topics[$key] = $topic;
}
$cmd = 0x82;
//$qos
$cmd += ($qos << 1);
$head = chr($cmd);
$head .= $this->setmsglength($i);
fwrite($this->socket, $head, strlen($head));
$this->_fwrite($buffer);
$string = $this->read(2);
$bytes = ord(substr($string, 1, 1));
$this->read($bytes);
}
/**
* Sends a keep alive ping
*/
public function ping(): void
{
$head = chr(0xc0);
$head .= chr(0x00);
@fwrite($this->socket, $head, 2); // сокет мог умереть. Переподключение -- в proc
$this->timesinceping = time();
$this->_debugMessage('ping sent');
}
/**
* sends a proper disconnect cmd
*/
public function disconnect(): void
{
$head = ' ';
$head[0] = chr(0xe0);
$head[1] = chr(0x00);
fwrite($this->socket, $head, 2);
}
/**
* Sends a proper disconnect, then closes the socket
*/
public function close(): void
{
if($this->socket){ // сокет мог быть и не открыт
$this->disconnect();
stream_socket_shutdown($this->socket, STREAM_SHUT_WR);
}
}
/**
* Publishes $content on a $topic
*
* @param $topic
* @param $content
* @param int $qos
* @param bool $retain
*/
public function publish($topic, $content, $qos = 0, $retain = false): void
{
$i = 0;
$buffer = '';
$buffer .= $this->strwritestring($topic, $i);
if ($qos) {
$id = $this->msgid++;
$buffer .= chr($id >> 8);
$i++;
$buffer .= chr($id % 256);
$i++;
}
$buffer .= $content;
$i += strlen($content);
$head = ' ';
$cmd = 0x30;
if ($qos) {
$cmd += $qos << 1;
}
if (empty($retain) === false) {
++$cmd;
}
$head[0] = chr($cmd);
$head .= $this->setmsglength($i);
@fwrite($this->socket, $head, strlen($head)); // сокет мог умереть. Переподключение -- в proc
$this->_fwrite($buffer);
}
/**
* Writes a string to the socket
*
* @param $buffer
*
* @return bool|int
*/
protected function _fwrite($buffer)
{
$buffer_length = strlen($buffer);
for ($written = 0; $written < $buffer_length; $written += $fwrite) {
@$fwrite = fwrite($this->socket, substr($buffer, $written)); // сокет мог умереть. Переподключение -- в proc
if ($fwrite === false) {
return false;
}
}
return $buffer_length;
}
/**
* Processes a received topic
*
* @param $msg
*
* @retrun bool|string
*/
public function message($msg)
{
$tlen = (ord($msg[0]) << 8) + ord($msg[1]);
$topic = substr($msg, 2, $tlen);
$msg = substr($msg, ($tlen + 2));
$found = false;
foreach ($this->topics as $key => $top) {
if (preg_match(
'/^' . str_replace(
'#',
'.*',
str_replace(
'+',
"[^\/]*",
str_replace(
'/',
"\/",
str_replace(
'$',
'\$',
$key
)
)
)
) . '$/',
$topic
)) {
$found = true;
if ($top['function'] === '__direct_return_message__') {
return array($topic,$msg);
}
if (is_callable($top['function'])) {
call_user_func($top['function'], $topic, $msg);
} else {
$this->_errorMessage('Message received on topic ' . $topic . ' but function is not callable.');
}
}
}
if ($found === false) {
$this->_debugMessage('msg received but no match in subscriptions');
}
return $found;
}
/**
* The processing loop for an "always on" client
* set true when you are doing other stuff in the loop good for
* watching something else at the same time
*
* @param bool $loop
* @param $timeout - trying to connect so many second or do one try
*
* @return bool | string
*/
public function proc(bool $loop = true,$timeout=FALSE)
{
if (@feof($this->socket) or (gettype($this->socket) != 'resource')) {
if(gettype($this->socket) != 'resource') echo "Socket die.\n";
$this->_debugMessage('eof receive going to reconnect for good measure');
@fclose($this->socket);
if(!$timeout) $timeout = 20; // будем пытаться переподключиться 20 секунд
$ret = $this->connect_auto(false,null,null,null,$timeout);
if($ret === FALSE) return null; // обозначим, что всё умерло
if (count($this->topics)) {
$this->subscribe($this->topics);
}
}
$byte = $this->read(1, true);
if ((string)$byte === '') {
if ($loop === true) {
usleep(100000); // 1/10 sec
}
} else {
$cmd = (int)(ord($byte) / 16);
$this->_debugMessage(
sprintf(
'Received CMD: %d (%s)',
$cmd,
isset(static::$known_commands[$cmd]) === true ? static::$known_commands[$cmd] : 'Unknown'
)
);
$multiplier = 1;
$value = 0;
do {
$digit = $this->read(1); // иначе цикл был бы бесконечным при смерти сокета
if($digit === FALSE) return FALSE;
$digit = ord($digit);
$value += ($digit & 127) * $multiplier;
$multiplier *= 128;
} while (($digit & 128) !== 0);
$this->_debugMessage('Fetching: ' . $value . ' bytes');
$string = $value > 0 ? $this->read($value) : ''; // чтение из сокета столько байт
if ($cmd) {
switch ($cmd) {
case 3: //Publish MSG
$return = $this->message($string); // там применяется функция callback
//if (is_bool($return) === false) {
return $return; // логическое значение или полученная строка
//}
break;
}
}
}
if ($this->timesinceping < (time() - $this->keepalive)) {
$this->_debugMessage('not had something in a while so ping');
$this->ping();
}
if ($this->timesinceping < (time() - ($this->keepalive * 2))) {
$this->_debugMessage('not seen a packet in a while, disconnecting/reconnecting');
fclose($this->socket);
if($timeout) $this->connect_auto(false,null,null,null,$timeout);
else $this->connect(false);
if (count($this->topics)) {
$this->subscribe($this->topics);
}
}
return false;
}
/**
* Gets the length of a msg, (and increments $i)
*
* @param $msg
* @param $i
*
* @return float|int
*/
protected function getmsglength(&$msg, &$i)
{
$multiplier = 1;
$value = 0;
do {
$digit = ord($msg[$i]);
$value += ($digit & 127) * $multiplier;
$multiplier *= 128;
$i++;
} while (($digit & 128) !== 0);
return $value;
}
/**
* @param $len
*
* @return string
*/
protected function setmsglength($len): string
{
$string = '';
do {
$digit = $len % 128;
$len >>= 7;
// if there are more digits to encode, set the top bit of this digit
if ($len > 0) {
$digit |= 0x80;
}
$string .= chr($digit);
} while ($len > 0);
return $string;
}
/**
* @param $str
* @param $i
*
* @return string
*/
protected function strwritestring($str, &$i): string
{
$len = strlen($str);
$msb = $len >> 8;
$lsb = $len % 256;
$ret = chr($msb);
$ret .= chr($lsb);
$ret .= $str;
$i += ($len + 2);
return $ret;
}
/**
* Prints a sting out character by character
*
* @param $string
*/
public function printstr($string): void
{
$strlen = strlen($string);
for ($j = 0; $j < $strlen; $j++) {
$num = ord($string[$j]);
if ($num > 31) {
$chr = $string[$j];
} else {
$chr = ' ';
}
printf("%4d: %08b : 0x%02x : %s \n", $j, $num, $num, $chr);
}
}
/**
* @param string $message
*/
protected function _debugMessage(string $message): void
{
if ($this->debug === true) {
echo date('r: ') . $message . PHP_EOL;
}
}
/**
* @param string $message
*/
protected function _errorMessage(string $message): void
{
error_log('phpMQTT Error:' . $message." \n");
}
}