- Add
php-mqtt/client
library to composer.json
file:
"require": {
"php-mqtt/client": "^1.1"
}
- Install library from the command line:
composer install
- Publish message to MQTT broker:
<?php
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;
require_once __DIR__.'/vendor/autoload.php';
const MQTT_HOST = '192.168.0.174';
const MQTT_PORT = 1883;
const MQTT_CLIENT_ID = 'PHP-MQTT-client';
const MQTT_USER = 'YOUR MQTT USER';
const MQTT_PASSWORD = 'YOUR MQTT USER PASSWORD';
const TOPIC = 'php/test';
$client = new MqttClient(MQTT_HOST, MQTT_PORT, MQTT_CLIENT_ID);
$settings = (new ConnectionSettings)
->setUsername(MQTT_USER)
->setPassword(MQTT_PASSWORD);
$client->connect($settings, true);
$data = 'Hello';
$client->publish(TOPIC, $data);
Leave a Comment
Cancel reply