PHP code example of hakhant / mqtt-client

1. Go to this page and download the library: Download hakhant/mqtt-client 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/ */

    

hakhant / mqtt-client example snippets


// config/mqtt.php
return [
    'host'     => env('MQTT_HOST', 'broker.hivemq.com'), // The MQTT broker host
    'port'     => env('MQTT_PORT', 1883),                // MQTT Broker port (default 1883)
    'username' => env('MQTT_USERNAME', ''),               // Optional: MQTT Username (if 

use Hakhant\Broker\Client;

class MqttController extends Controller
{
    protected $mqttClient;

    public function __construct(Client $mqttClient)
    {
        $this->mqttClient = $mqttClient;
    }

    public function publishMessage()
    {
        $topic = 'topic/test';
        $message = 'Hello from Laravel MQTT!';
        $qos = 0; // Quality of Service level
        $retain = false; // Whether the message should be retained

        // Publish message
        $this->mqttClient->publish($topic, $message, $qos, $retain);

        return response()->json(['status' => 'Message Published']);
    }

    public function subscribeToTopic()
    {
        $topic = 'topic/test';
        $this->mqttClient->subscribe($topic, function($topic, $message) {
            // Handle the received message
            echo "Message received on topic {$topic}: {$message}\n";
        });

        // Keep the loop running to listen for messages
        $this->mqttClient->loop()
    }
}

bash 
php artisan vendor:publish --provider="Hakhant\Broker\Providers\ClientServiceProvider" --tag="config"