-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathMqttClient.php
1301 lines (1101 loc) · 48.7 KB
/
MqttClient.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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace PhpMqtt\Client;
use PhpMqtt\Client\Concerns\GeneratesRandomClientIds;
use PhpMqtt\Client\Concerns\OffersHooks;
use PhpMqtt\Client\Concerns\ValidatesConfiguration;
use PhpMqtt\Client\Contracts\MessageProcessor;
use PhpMqtt\Client\Contracts\MqttClient as ClientContract;
use PhpMqtt\Client\Contracts\Repository;
use PhpMqtt\Client\Exceptions\ClientNotConnectedToBrokerException;
use PhpMqtt\Client\Exceptions\ConfigurationInvalidException;
use PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException;
use PhpMqtt\Client\Exceptions\DataTransferException;
use PhpMqtt\Client\Exceptions\InvalidMessageException;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\Exceptions\PendingMessageAlreadyExistsException;
use PhpMqtt\Client\Exceptions\PendingMessageNotFoundException;
use PhpMqtt\Client\Exceptions\ProtocolNotSupportedException;
use PhpMqtt\Client\Exceptions\ProtocolViolationException;
use PhpMqtt\Client\MessageProcessors\Mqtt311MessageProcessor;
use PhpMqtt\Client\MessageProcessors\Mqtt31MessageProcessor;
use PhpMqtt\Client\Repositories\MemoryRepository;
use Psr\Log\LoggerInterface;
/**
* An MQTT client implementing protocol version 3.1.
*
* @package PhpMqtt\Client
*/
class MqttClient implements ClientContract
{
use GeneratesRandomClientIds;
use OffersHooks;
use ValidatesConfiguration;
const MQTT_3_1 = '3.1';
const MQTT_3_1_1 = '3.1.1';
const QOS_AT_MOST_ONCE = 0;
const QOS_AT_LEAST_ONCE = 1;
const QOS_EXACTLY_ONCE = 2;
const SOCKET_READ_BUFFER_SIZE = 8192;
private string $host;
private int $port;
private string $clientId;
private ConnectionSettings $settings;
private string $buffer = '';
private bool $connected = false;
private ?float $lastPingAt = null;
private MessageProcessor $messageProcessor;
private Repository $repository;
private LoggerInterface $logger;
private bool $interrupted = false;
private int $bytesReceived = 0;
private int $bytesSent = 0;
/** @var resource|null */
protected $socket;
/**
* Constructs a new MQTT client which subsequently supports publishing and subscribing
*
* Notes:
* - If no client id is given, a random one is generated, forcing a clean session implicitly.
* - If no protocol is given, MQTT v3 is used by default.
* - If no repository is given, an in-memory repository is created for you. Once you terminate
* your script, all stored data (like resend queues) is lost.
* - If no logger is given, log messages are dropped. Any PSR-3 logger will work.
*
* @param string $host
* @param int $port
* @param string|null $clientId
* @param string $protocol
* @param Repository|null $repository
* @param LoggerInterface|null $logger
* @throws ProtocolNotSupportedException
*/
public function __construct(
string $host,
int $port = 1883,
string $clientId = null,
string $protocol = self::MQTT_3_1,
Repository $repository = null,
LoggerInterface $logger = null
)
{
if (!in_array($protocol, [self::MQTT_3_1, self::MQTT_3_1_1])) {
throw new ProtocolNotSupportedException($protocol);
}
$this->host = $host;
$this->port = $port;
$this->clientId = $clientId ?? $this->generateRandomClientId();
$this->repository = $repository ?? new MemoryRepository();
$this->logger = new Logger($this->host, $this->port, $this->clientId, $logger);
switch ($protocol) {
case self::MQTT_3_1_1:
$this->messageProcessor = new Mqtt311MessageProcessor($this->clientId, $this->logger);
break;
case self::MQTT_3_1:
default:
$this->messageProcessor = new Mqtt31MessageProcessor($this->clientId, $this->logger);
break;
}
$this->initializeEventHandlers();
}
/**
* {@inheritDoc}
*/
public function connect(
ConnectionSettings $settings = null,
bool $useCleanSession = false
): void
{
// Always abruptly close any previous connection if we are opening a new one.
// The caller should make sure this does not happen.
$this->closeSocket();
$this->logger->debug('Connecting to broker.');
$this->settings = $settings ?? new ConnectionSettings();
$this->ensureConnectionSettingsAreValid($this->settings);
// Because a clean session would make reconnects inherently more complex since all subscriptions would need to be replayed after reconnecting,
// we simply do not allow using these two features together.
if ($useCleanSession && $this->settings->shouldReconnectAutomatically()) {
throw new ConfigurationInvalidException('Automatic reconnects cannot be used together with the clean session flag.');
}
// When a clean session is requested, we have to reset the repository to forget about persisted states.
if ($useCleanSession) {
$this->repository->reset();
}
$this->connectInternal($useCleanSession);
}
/**
* Connect to the MQTT broker using the configured settings.
*
* @param bool $useCleanSession
* @return void
* @throws ConnectingToBrokerFailedException
*/
protected function connectInternal(bool $useCleanSession = false): void
{
try {
$this->establishSocketConnection();
$this->performConnectionHandshake($useCleanSession);
} catch (ConnectingToBrokerFailedException $e) {
$this->closeSocket();
throw $e;
}
$this->connected = true;
}
/**
* Opens a socket that connects to the host and port set on the object.
*
* When this method is called, all connection settings have been validated.
*
* @return void
* @throws ConnectingToBrokerFailedException
*/
protected function establishSocketConnection(): void
{
$contextOptions = [];
// Only if TLS is enabled, we add all TLS options to the context options.
if ($this->settings->shouldUseTls()) {
$this->logger->debug('Using TLS for the connection to the broker.');
$shouldVerifyPeer = $this->settings->shouldTlsVerifyPeer()
|| $this->settings->getTlsCertificateAuthorityFile() !== null
|| $this->settings->getTlsCertificateAuthorityPath() !== null;
if (!$shouldVerifyPeer) {
$this->logger->warning('Using TLS without peer verification is discouraged. Are you aware of the security risk?');
}
if ($this->settings->isTlsSelfSignedAllowed()) {
$this->logger->warning('Using TLS with self-signed certificates is discouraged. Please use a CA file to verify it.');
}
$tlsOptions = [
'verify_peer' => $shouldVerifyPeer,
'verify_peer_name' => $this->settings->shouldTlsVerifyPeerName(),
'allow_self_signed' => $this->settings->isTlsSelfSignedAllowed(),
];
if ($this->settings->getTlsCertificateAuthorityFile() !== null) {
$tlsOptions['cafile'] = $this->settings->getTlsCertificateAuthorityFile();
}
if ($this->settings->getTlsCertificateAuthorityPath() !== null) {
$tlsOptions['capath'] = $this->settings->getTlsCertificateAuthorityPath();
}
if ($this->settings->getTlsClientCertificateFile() !== null) {
$tlsOptions['local_cert'] = $this->settings->getTlsClientCertificateFile();
}
if ($this->settings->getTlsClientCertificateKeyFile() !== null) {
$tlsOptions['local_pk'] = $this->settings->getTlsClientCertificateKeyFile();
}
if ($this->settings->getTlsClientCertificateKeyPassphrase() !== null) {
$tlsOptions['passphrase'] = $this->settings->getTlsClientCertificateKeyPassphrase();
}
$contextOptions['ssl'] = $tlsOptions;
}
$connectionString = 'tcp://' . $this->getHost() . ':' . $this->getPort();
$socketContext = stream_context_create($contextOptions);
$socket = @stream_socket_client(
$connectionString,
$errorCode,
$errorMessage,
$this->settings->getConnectTimeout(),
STREAM_CLIENT_CONNECT,
$socketContext
);
// The socket will be set to false if stream_socket_client() returned an error.
if ($socket === false) {
$this->logger->error('Establishing a connection with the broker using the connection string [{connectionString}] failed: {error}', [
'connectionString' => $connectionString,
'error' => $errorMessage,
'code' => $errorCode,
]);
throw new ConnectingToBrokerFailedException(
ConnectingToBrokerFailedException::EXCEPTION_CONNECTION_SOCKET_ERROR,
sprintf('Socket error [%d]: %s', $errorCode, $errorMessage),
(string) $errorCode,
$errorMessage
);
}
// If TLS is enabled, we need to enable it on the already created stream.
// Until now, we only created a normal TCP stream.
if ($this->settings->shouldUseTls()) {
// Since stream_socket_enable_crypto() communicates errors using error_get_last(),
// we need to clear a potentially set error at this point to be sure the error we
// retrieve in the error handling part is actually of this function call and not
// from some unrelated code of the users application.
error_clear_last();
$this->logger->debug('Enabling TLS on the existing socket connection.');
$enableEncryptionResult = @stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
if ($enableEncryptionResult === false) {
// At this point, PHP should have given us something like this:
// SSL operation failed with code 1. OpenSSL Error messages:
// error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed
// We need to get our hands dirty and extract the OpenSSL error
// from the PHP message, which luckily gives us a handy newline.
$this->parseTlsErrorMessage(error_get_last(), $tlsErrorCode, $tlsErrorMessage);
// Before returning an exception, we need to close the already opened socket.
@fclose($socket);
$this->logger->error('Enabling TLS on the connection with the MQTT broker failed (code {errorCode}): {errorMessage}', [
'errorMessage' => $tlsErrorMessage,
'errorCode' => $tlsErrorCode,
]);
throw new ConnectingToBrokerFailedException(
ConnectingToBrokerFailedException::EXCEPTION_CONNECTION_TLS_ERROR,
sprintf('TLS error [%s]: %s', $tlsErrorCode, $tlsErrorMessage),
$tlsErrorCode,
$tlsErrorMessage
);
}
$this->logger->debug('TLS enabled successfully.');
}
stream_set_timeout($socket, $this->settings->getSocketTimeout());
stream_set_blocking($socket, $this->settings->shouldUseBlockingSocket());
$this->logger->debug('Socket opened and ready to use.');
$this->socket = $socket;
}
/**
* Internal parser for SSL-related PHP error messages.
*
* @param array|null $phpError
* @param string|null $tlsErrorCode
* @param string|null $tlsErrorMessage
* @return void
*/
private function parseTlsErrorMessage(?array $phpError, ?string &$tlsErrorCode = null, ?string &$tlsErrorMessage = null): void
{
if (!$phpError || !isset($phpError['message'])) {
$tlsErrorCode = "UNKNOWN:1";
$tlsErrorMessage = "Unknown error";
return;
}
if (!preg_match('/:\n(?:error:([0-9A-Z]+):)?(.+)$/', $phpError['message'], $matches)) {
$tlsErrorCode = "UNKNOWN:2";
$tlsErrorMessage = $phpError['message'];
return;
}
if ($matches[1] == "") {
$tlsErrorCode = "UNKNOWN:3";
$tlsErrorMessage = $matches[2];
return;
}
$tlsErrorCode = $matches[1];
$tlsErrorMessage = $matches[2];
}
/**
* Performs the connection handshake with the help of the configured message processor.
* The connection handshake is expected to have the same flow all the time:
* - Connect request with variable length
* - Connect acknowledgement with variable length
*
* @param bool $useCleanSession
* @return void
* @throws ConnectingToBrokerFailedException
*/
protected function performConnectionHandshake(bool $useCleanSession = false): void
{
try {
$connectionHandshakeStartedAt = microtime(true);
$data = $this->messageProcessor->buildConnectMessage($this->settings, $useCleanSession);
$this->logger->debug('Sending connection handshake to broker.');
$this->writeToSocket($data);
// Start by waiting for the first byte, then using polling logic to fetch all remaining
// data from the socket.
$buffer = $this->readFromSocket(1);
$requiredBytes = -1;
while (true) {
if ($requiredBytes > 0) {
$buffer .= $this->readFromSocket($requiredBytes);
} else {
$buffer .= $this->readAllAvailableDataFromSocket();
}
$message = null;
$result = $this->messageProcessor->tryFindMessageInBuffer($buffer, strlen($buffer), $message, $requiredBytes);
// We only need to wait for the bytes we don't have in the buffer yet.
$requiredBytes = $requiredBytes - strlen($buffer);
if ($result === true) {
/** @var string $message */
// Remove the parsed data from the buffer.
$buffer = substr($buffer, strlen($message));
// Process the acknowledgement message.
$this->messageProcessor->handleConnectAcknowledgement($message);
break;
}
// If no acknowledgement has been received from the broker within the configured connection timeout period,
// we abort the connection attempt and assume broker unavailability.
if (microtime(true) - $this->settings->getConnectTimeout() > $connectionHandshakeStartedAt) {
throw new ConnectingToBrokerFailedException(
ConnectingToBrokerFailedException::EXCEPTION_CONNECTION_BROKER_UNAVAILABLE,
'The broker did not acknowledge the connection attempt within the configured connection timeout period.'
);
}
}
// We need to set the global buffer to the remaining data we might already have read.
$this->buffer = $buffer;
} catch (DataTransferException $e) {
$this->logger->error('While connecting to the broker, a transfer error occurred.');
throw new ConnectingToBrokerFailedException(
ConnectingToBrokerFailedException::EXCEPTION_CONNECTION_FAILED,
'A connection could not be established due to data transfer issues.'
);
}
}
/**
* Attempts to reconnect to the broker. If a connection cannot be established within the configured number of retries,
* the last caught exception is thrown.
*
* @return void
* @throws ConnectingToBrokerFailedException
*/
protected function reconnect(): void
{
$maxReconnectAttempts = $this->settings->getMaxReconnectAttempts();
$delayBetweenReconnectAttempts = $this->settings->getDelayBetweenReconnectAttempts();
for ($i = 1; $i <= $maxReconnectAttempts; $i++) {
try {
$this->connectInternal();
return;
} catch (ConnectingToBrokerFailedException $e) {
if ($i === $maxReconnectAttempts) {
throw $e;
}
if ($delayBetweenReconnectAttempts > 0) {
usleep($delayBetweenReconnectAttempts * 1000);
}
}
}
}
/**
* {@inheritDoc}
*/
public function interrupt(): void
{
$this->interrupted = true;
}
/**
* {@inheritDoc}
*/
public function getHost(): string
{
return $this->host;
}
/**
* {@inheritDoc}
*/
public function getPort(): int
{
return $this->port;
}
/**
* {@inheritDoc}
*/
public function getClientId(): string
{
return $this->clientId;
}
/**
* {@inheritDoc}
*/
public function getReceivedBytes(): int
{
return $this->bytesReceived;
}
/**
* {@inheritDoc}
*/
public function getSentBytes(): int
{
return $this->bytesSent;
}
/**
* {@inheritDoc}
*/
public function isConnected(): bool
{
return $this->connected;
}
/**
* Ensures the client is connected to a broker (or at least thinks it is).
* This method does not account for closed sockets.
*
* @return void
* @throws ClientNotConnectedToBrokerException
*/
protected function ensureConnected(): void
{
if (!$this->isConnected()) {
throw new ClientNotConnectedToBrokerException(
'The client is not connected to a broker. The requested operation is impossible at this point.'
);
}
}
/**
* {@inheritDoc}
*/
public function disconnect(): void
{
$this->ensureConnected();
$this->sendDisconnect();
if ($this->socket !== null && is_resource($this->socket)) {
$this->logger->debug('Closing the socket to the broker.');
stream_socket_shutdown($this->socket, STREAM_SHUT_WR);
}
$this->connected = false;
}
/**
* {@inheritDoc}
*/
public function publish(string $topic, string $message, int $qualityOfService = 0, bool $retain = false): void
{
$this->ensureConnected();
$messageId = null;
if ($qualityOfService > self::QOS_AT_MOST_ONCE) {
$messageId = $this->repository->newMessageId();
$pendingMessage = new PublishedMessage($messageId, $topic, $message, $qualityOfService, $retain);
$this->repository->addPendingOutgoingMessage($pendingMessage);
}
$this->publishMessage($topic, $message, $qualityOfService, $retain, $messageId);
}
/**
* Actually publishes a message after using the configured message processor to build it.
* This is an internal method used for both, initial publishing of messages as well as
* re-publishing in case of timeouts.
*
* @param string $topic
* @param string $message
* @param int $qualityOfService
* @param bool $retain
* @param int|null $messageId
* @param bool $isDuplicate
* @return void
* @throws DataTransferException
*/
protected function publishMessage(
string $topic,
string $message,
int $qualityOfService,
bool $retain,
int $messageId = null,
bool $isDuplicate = false
): void
{
$this->logger->debug('Publishing a message on topic [{topic}]: {message}', [
'topic' => $topic,
'message' => $message,
'qos' => $qualityOfService,
'retain' => $retain,
'messageId' => $messageId,
'isDuplicate' => $isDuplicate,
]);
$this->runPublishEventHandlers($topic, $message, $messageId, $qualityOfService, $retain);
$data = $this->messageProcessor->buildPublishMessage($topic, $message, $qualityOfService, $retain, $messageId, $isDuplicate);
$this->writeToSocketWithAutoReconnect($data);
}
/**
* {@inheritDoc}
*/
public function subscribe(string $topicFilter, callable $callback = null, int $qualityOfService = self::QOS_AT_MOST_ONCE): void
{
$this->ensureConnected();
$this->logger->debug('Subscribing to topic [{topicFilter}] with maximum QoS [{qos}].', [
'topicFilter' => $topicFilter,
'qos' => $qualityOfService,
]);
$messageId = $this->repository->newMessageId();
// Create the subscription representation now, but it will become an
// actual subscription only upon acknowledgement from the broker.
$subscriptions = [new Subscription($topicFilter, $qualityOfService, $callback)];
$pendingMessage = new SubscribeRequest($messageId, $subscriptions);
$this->repository->addPendingOutgoingMessage($pendingMessage);
$data = $this->messageProcessor->buildSubscribeMessage($messageId, $subscriptions);
$this->writeToSocketWithAutoReconnect($data);
}
/**
* {@inheritDoc}
*/
public function unsubscribe(string $topicFilter): void
{
$this->ensureConnected();
$this->logger->debug('Unsubscribing from topic [{topicFilter}].', ['topicFilter' => $topicFilter]);
$messageId = $this->repository->newMessageId();
$topicFilters = [$topicFilter];
$pendingMessage = new UnsubscribeRequest($messageId, $topicFilters);
$this->repository->addPendingOutgoingMessage($pendingMessage);
$data = $this->messageProcessor->buildUnsubscribeMessage($messageId, $topicFilters);
$this->writeToSocketWithAutoReconnect($data);
}
/**
* Returns the next time the broker expects to be pinged.
*
* @return float
*/
protected function nextPingAt(): float
{
return ($this->lastPingAt + $this->settings->getKeepAliveInterval());
}
/**
* {@inheritDoc}
*/
public function loop(bool $allowSleep = true, bool $exitWhenQueuesEmpty = false, int $queueWaitLimit = null): void
{
$this->logger->debug('Starting client loop to process incoming messages and the resend queue.');
$loopStartedAt = microtime(true);
while (true) {
if ($this->interrupted) {
$this->interrupted = false;
break;
}
$this->loopOnce($loopStartedAt, $allowSleep);
// If configured, the loop is exited if all queues are empty or a certain time limit is reached (i.e. retry is aborted).
// In any case, there may not be any active subscriptions though.
if ($exitWhenQueuesEmpty && $this->repository->countSubscriptions() === 0) {
if ($this->allQueuesAreEmpty()) {
break;
}
// The time limit is reached. This most likely means the outgoing queues could not be emptied in time.
// Probably the server did not respond with an acknowledgement.
if ($queueWaitLimit !== null && (microtime(true) - $loopStartedAt) > $queueWaitLimit) {
break;
}
}
}
}
/**
* {@inheritDoc}
*/
public function loopOnce(float $loopStartedAt, bool $allowSleep = false, int $sleepMicroseconds = 100000): void
{
$elapsedTime = microtime(true) - $loopStartedAt;
$this->runLoopEventHandlers($elapsedTime);
// Read data from the socket - as much as available.
$this->buffer .= $this->readAllAvailableDataFromSocket(true);
// Try to parse a message from the buffer and handle it, as long as messages can be parsed.
if (strlen($this->buffer) > 0) {
$this->processMessageBuffer();
} elseif ($allowSleep) {
usleep($sleepMicroseconds);
}
// Republish messages expired without confirmation.
// This includes published messages, subscribe and unsubscribe requests.
$this->resendPendingMessages();
// If the last message of the broker has been received more seconds ago
// than specified by the keep alive time, we will send a ping to ensure
// the connection is kept alive.
if ($this->nextPingAt() <= microtime(true)) {
$this->ping();
}
}
/**
* Processes the incoming message buffer by parsing and handling the messages, until the buffer is empty.
*
* @return void
* @throws DataTransferException
* @throws InvalidMessageException
* @throws MqttClientException
* @throws ProtocolViolationException
*/
private function processMessageBuffer(): void
{
while (true) {
$data = '';
$requiredBytes = -1;
$hasMessage = $this->messageProcessor->tryFindMessageInBuffer($this->buffer, strlen($this->buffer), $data, $requiredBytes);
// When there is no full message in the buffer, we stop processing for now and go on
// with the next iteration.
if ($hasMessage === false) {
break;
}
// If we found a message, the buffer needs to be reduced by the message length.
$this->buffer = substr($this->buffer, strlen($data));
// We then pass the message over to the message processor to parse and validate it.
$message = $this->messageProcessor->parseAndValidateMessage($data);
// The result is used by us to perform required actions according to the protocol.
if ($message !== null) {
$this->handleMessage($message);
}
}
}
/**
* Handles the given message according to its contents.
*
* @param Message $message
* @return void
* @throws DataTransferException
* @throws ProtocolViolationException
*/
protected function handleMessage(Message $message): void
{
// PUBLISH (incoming)
if ($message->getType()->equals(MessageType::PUBLISH())) {
if ($message->getQualityOfService() === self::QOS_AT_LEAST_ONCE) {
// QoS 1.
$this->sendPublishAcknowledgement($message->getMessageId());
}
if ($message->getQualityOfService() === self::QOS_EXACTLY_ONCE) {
// QoS 2, part 1.
try {
$pendingMessage = new PublishedMessage(
$message->getMessageId(),
$message->getTopic(),
$message->getContent(),
2,
false
);
$this->repository->addPendingIncomingMessage($pendingMessage);
} catch (PendingMessageAlreadyExistsException $e) {
// We already received and processed this message.
}
// Always acknowledge, even if we received it multiple times.
$this->sendPublishReceived($message->getMessageId());
// We only deliver this published message as soon as we receive a publish complete.
return;
}
// For QoS 0 and QoS 1 we can deliver right away.
$this->deliverPublishedMessage($message->getTopic(), $message->getContent(), $message->getQualityOfService());
return;
}
// PUBACK (outgoing, QoS 1)
// Receiving an acknowledgement allows us to remove the published message from the retry queue.
if ($message->getType()->equals(MessageType::PUBLISH_ACKNOWLEDGEMENT())) {
$result = $this->repository->removePendingOutgoingMessage($message->getMessageId());
if ($result === false) {
$this->logger->notice('Received publish acknowledgement from the broker for already acknowledged message.', [
'messageId' => $message->getMessageId()
]);
}
return;
}
// PUBREC (outgoing, QoS 2, part 1)
// Receiving a receipt allows us to mark the published message as received.
if ($message->getType()->equals(MessageType::PUBLISH_RECEIPT())) {
try {
$result = $this->repository->markPendingOutgoingPublishedMessageAsReceived($message->getMessageId());
} catch (PendingMessageNotFoundException $e) {
// This should never happen as we should have received all PUBREC messages before we see the first
// PUBCOMP which actually remove the message. So we do this for safety only.
$result = false;
}
if ($result === false) {
$this->logger->notice('Received publish receipt from the broker for already acknowledged message.', [
'messageId' => $message->getMessageId()
]);
}
// We always reply blindly to keep the flow moving.
$this->sendPublishRelease($message->getMessageId());
return;
}
// PUBREL (incoming, QoS 2, part 2)
// When the broker tells us we can release the received published message, we deliver it to subscribed callbacks.
if ($message->getType()->equals(MessageType::PUBLISH_RELEASE())) {
$pendingMessage = $this->repository->getPendingIncomingMessage($message->getMessageId());
if (!$pendingMessage || !$pendingMessage instanceof PublishedMessage) {
$this->logger->notice('Received publish release from the broker for already released message.', [
'messageId' => $message->getMessageId(),
]);
} else {
$this->deliverPublishedMessage(
$pendingMessage->getTopicName(),
$pendingMessage->getMessage(),
$pendingMessage->getQualityOfServiceLevel()
);
$this->repository->removePendingIncomingMessage($message->getMessageId());
}
// Always reply with the PUBCOMP packet so it stops resending it.
$this->sendPublishComplete($message->getMessageId());
return;
}
// PUBCOMP (outgoing, QoS 2 part 3)
// Receiving a completion allows us to remove a published message from the retry queue.
// At this point, the publish process is complete.
if ($message->getType()->equals(MessageType::PUBLISH_COMPLETE())) {
$result = $this->repository->removePendingOutgoingMessage($message->getMessageId());
if ($result === false) {
$this->logger->notice('Received publish completion from the broker for already acknowledged message.', [
'messageId' => $message->getMessageId(),
]);
}
return;
}
// SUBACK
if ($message->getType()->equals(MessageType::SUBSCRIBE_ACKNOWLEDGEMENT())) {
$pendingMessage = $this->repository->getPendingOutgoingMessage($message->getMessageId());
if (!$pendingMessage || !$pendingMessage instanceof SubscribeRequest) {
$this->logger->notice('Received subscribe acknowledgement from the broker for already acknowledged request.', [
'messageId' => $message->getMessageId(),
]);
return;
}
$acknowledgedSubscriptions = $pendingMessage->getSubscriptions();
if (count($acknowledgedSubscriptions) != count($message->getAcknowledgedQualityOfServices())) {
throw new ProtocolViolationException(sprintf(
'The MQTT broker responded with a different amount of QoS acknowledgements (%d) than we expected (%d).',
count($message->getAcknowledgedQualityOfServices()),
count($acknowledgedSubscriptions)
));
}
foreach ($message->getAcknowledgedQualityOfServices() as $index => $qualityOfService) {
// Starting from MQTT 3.1.1, the broker is able to reject individual subscriptions.
// Instead of failing the whole bulk, we log the incident and skip the single subscription.
if ($qualityOfService === 128) {
$this->logger->notice('The broker rejected the subscription to [{topicFilter}].', [
'topicFilter' => $acknowledgedSubscriptions[$index]->getTopicFilter(),
]);
continue;
}
// It may happen that the server registers our subscription
// with a lower quality of service than requested, in this
// case this is the one that we will record.
$acknowledgedSubscriptions[$index]->setQualityOfServiceLevel($qualityOfService);
$this->repository->addSubscription($acknowledgedSubscriptions[$index]);
}
$this->repository->removePendingOutgoingMessage($message->getMessageId());
return;
}
// UNSUBACK
if ($message->getType()->equals(MessageType::UNSUBSCRIBE_ACKNOWLEDGEMENT())) {
$pendingMessage = $this->repository->getPendingOutgoingMessage($message->getMessageId());
if (!$pendingMessage || !$pendingMessage instanceof UnsubscribeRequest) {
$this->logger->notice('Received unsubscribe acknowledgement from the broker for already acknowledged request.', [
'messageId' => $message->getMessageId(),
]);
return;
}
foreach ($pendingMessage->getTopicFilters() as $topicFilter) {
$this->repository->removeSubscription($topicFilter);
}
$this->repository->removePendingOutgoingMessage($message->getMessageId());
return;
}
// PINGREQ
if ($message->getType()->equals(MessageType::PING_REQUEST())) {
// Respond with PINGRESP.
$this->writeToSocketWithAutoReconnect($this->messageProcessor->buildPingResponseMessage());
return;
}
}
/**
* Determines if all queues are empty.
*
* @return bool
*/
protected function allQueuesAreEmpty(): bool
{
return $this->repository->countPendingOutgoingMessages() === 0 &&
$this->repository->countPendingIncomingMessages() === 0;
}
/**
* Delivers a published message to subscribed callbacks.
*
* @param string $topic
* @param string $message
* @param int $qualityOfServiceLevel
* @param bool $retained
* @return void
*/
protected function deliverPublishedMessage(string $topic, string $message, int $qualityOfServiceLevel, bool $retained = false): void
{
$subscribers = $this->repository->getSubscriptionsMatchingTopic($topic);
$this->logger->debug('Delivering message received on topic [{topic}] with QoS [{qos}] from the broker to [{subscribers}] subscribers.', [
'topic' => $topic,
'message' => $message,
'qos' => $qualityOfServiceLevel,
'subscribers' => count($subscribers),
]);
foreach ($subscribers as $subscriber) {
if ($subscriber->getCallback() === null) {
continue;
}
try {
call_user_func($subscriber->getCallback(), $topic, $message, $retained, $subscriber->getMatchedWildcards($topic));
} catch (\Throwable $e) {
$this->logger->error('Subscriber callback threw exception for published message on topic [{topic}].', [
'topic' => $topic,
'message' => $message,
'exception' => $e,
]);
}
}
$this->runMessageReceivedEventHandlers($topic, $message, $qualityOfServiceLevel, $retained);
}
/**
* Republishes pending messages.
*
* @return void
* @throws DataTransferException
* @throws InvalidMessageException
*/
protected function resendPendingMessages(): void
{
/** @noinspection PhpUnhandledExceptionInspection */
$dateTime = (new \DateTime())->sub(new \DateInterval('PT' . $this->settings->getResendTimeout() . 'S'));
$messages = $this->repository->getPendingOutgoingMessagesLastSentBefore($dateTime);
foreach ($messages as $pendingMessage) {
if ($pendingMessage instanceof PublishedMessage) {
$this->logger->debug('Re-publishing pending message to the broker.', [
'messageId' => $pendingMessage->getMessageId(),
]);
$this->publishMessage(
$pendingMessage->getTopicName(),
$pendingMessage->getMessage(),
$pendingMessage->getQualityOfServiceLevel(),
$pendingMessage->wantsToBeRetained(),
$pendingMessage->getMessageId(),
true
);
} elseif ($pendingMessage instanceof SubscribeRequest) {
$this->logger->debug('Re-sending pending subscribe request to the broker.', [
'messageId' => $pendingMessage->getMessageId(),
]);
$data = $this->messageProcessor->buildSubscribeMessage($pendingMessage->getMessageId(), $pendingMessage->getSubscriptions(), true);
$this->writeToSocketWithAutoReconnect($data);
} elseif ($pendingMessage instanceof UnsubscribeRequest) {
$this->logger->debug('Re-sending pending unsubscribe request to the broker.', [
'messageId' => $pendingMessage->getMessageId(),
]);