This repository contains examples for php-mqtt/client
.
When publishing, there is only a noteworthy difference between QoS 0 and QoS 1/2, since QoS 0 is fire and forget, while QoS 1/2 require confirmation. For completeness, an example for each QoS level is provided.
- Publish a message using QoS 0 (unreliable delivery)
- Publish a message using QoS 1 (reliable delivery, but probably multiple times)
- Publish a message using QoS 2 (reliable delivery, exactly once)
When subscribing, there is not really a difference between the QoS levels. All three QoS levels work the same from a library API perspective. Under the hood, each of the QoS levels uses a slightly different implementation, though, to follow the protocol specification. Same as with publishing, an example for each QoS level is provided for completeness.
- Subscribe to a topic using QoS 0 (unreliable delivery)
- Subscribe to a topic using QoS 1 (reliable delivery, but probably multiple times)
- Subscribe to a topic using QoS 2 (reliable delivery, exactly once)
For the connection to the broker, additional settings can be used. For example a username and password for authorization, a customized timeout for the connection attempt or TLS settings for a secured connection. For simplicity, all the following examples will publish a single message using QoS 0 after connecting to the broker.
- Authorize using username and password
- Use TLS without client certificate
- Use TLS with client certificate
- Declare Last Will upon connection
To inject logic into the execution path of our MQTT client, it is possible to use so-called hooks. They are essentially callbacks which can be registered for a specific purpose and which are called upon certain events. The following gives a few examples and ideas what can be done with hooks, although they are a lot more versatile than can be shown here.
- Use a loop event handler to perform periodic actions
- Use a publish event handler to log published messages
- Use a message received event handler to log received messages
- Use a loop event handler to timeout a remote procedure call
Since the event loop provided by MqttClient::loop()
is an infinite loop by design, most applications need a way to escape it.
Most often the primary use case is for a graceful shutdown of the application, to avoid forceful termination.
Simply clone the repository and run composer install
to install the required dependencies.
You can then run the examples one by one, but please don't forget to change the shared settings like the MQTT broker host and port before.
The shared settings can be found in shared/config.php
. Alternatively, the examples can be altered directly.
The examples use a custom logger to give insight about what is happening internally. You can adjust the logging level as needed.
php-mqtt/client-examples
is open-source software licensed under the MIT license.