-
Notifications
You must be signed in to change notification settings - Fork 16
/
01_publish_with_qos_0.php
31 lines (23 loc) · 1.3 KB
/
01_publish_with_qos_0.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
<?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 0.
$client->publish('foo/bar/baz', 'Hello world!', MqttClient::QOS_AT_MOST_ONCE);
// 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 0 failed. An exception occurred.', ['exception' => $e]);
}