PHP code example of joserf / mqtt-php-api
1. Go to this page and download the library: Download joserf/mqtt-php-api library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
joserf / mqtt-php-api example snippets
$server = '192.168.*.*';
$port = 1883;
$clientId = 'test-publisher';
$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->publish('test/publisher', 'JRF API Teste!', 0);
$mqtt->disconnect();
$server = '192.168.*.*';
$port = 1883;
$clientId = 'test-subscriber';
$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->subscribe('test/subscriber', function ($topic, $message, $retained, $matchedWildcards) {
echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
$mqtt->disconnect();
reporting(E_ALL);
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
$server = '192.168.*.*';
$port = 1883;
$clientId = rand(5, 15);
$clean_session = true;
$mqtt_version = MqttClient::MQTT_3_1_1;
$connectionSettings = (new ConnectionSettings)
->setKeepAliveInterval(60)
->setLastWillMessage('client disconnect')
->setLastWillQualityOfService(1);
$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");
$mqtt->subscribe('mqtt/test', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
shell
composer