-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path03_publish_with_qos_2.php
36 lines (27 loc) · 1.63 KB
/
03_publish_with_qos_2.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
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../shared/config.php';
use PhpMqtt\Client\Examples\Shared\SimpleLogger;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\MqttClient;
use Psr\Log\LogLevel;
// Create an instance of a PSR-3 compliant logger. For this example, we will also use the logger to log exceptions.
$logger = new SimpleLogger(LogLevel::INFO);
try {
// Create a new instance of an MQTT client and configure it to use the shared broker host and port.
$client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_PORT, 'test-publisher', MqttClient::MQTT_3_1, null, $logger);
// Connect to the broker without specific connection settings but with a clean session.
$client->connect(null, true);
// Publish the message 'Hello world!' on the topic 'foo/bar/baz' using QoS 2.
$client->publish('foo/bar/baz', 'Hello world!', MqttClient::QOS_EXACTLY_ONCE);
// Since QoS 2 requires the publisher to await confirmation and resend the message if no confirmation is received,
// we need to start the client loop which takes care of that. By passing `true` as second parameter,
// we allow the loop to exit as soon as all confirmations have been received.
$client->loop(true, true);
// Gracefully terminate the connection to the broker.
$client->disconnect();
} catch (MqttClientException $e) {
// MqttClientException is the base exception of all exceptions in the library. Catching it will catch all MQTT related exceptions.
$logger->error('Publishing a message using QoS 2 failed. An exception occurred.', ['exception' => $e]);
}