PHP code example of elemenx / laravel-mqtt

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

    

elemenx / laravel-mqtt example snippets


'aliases' => [

    'Mqtt' => \Elemenx\Mqtt\Facades\Mqtt::class,

];

php artisan vendor:publish --provider="Elemenx\Mqtt\MqttServiceProvider"

use Elemenx\Mqtt\MqttClass\Mqtt;

public function sendMsgViaMqtt($topic, $message)
{
    $mqtt = new Mqtt();
    $client_id = Auth::user()->id;
    $output = $mqtt->connectAndPublish($topic, $message, $client_id);

    if ($output === true)
    {
        return "published";
    }
    
    return "Failed";
}

use Mqtt;

public function sendMsgViaMqtt($topic, $message)
{
    $client_id = Auth::user()->id;
    
    $output = Mqtt::connectAndPublish($topic, $message, $client_id);

    if ($output === true)
    {
        return "published";
    }

    return "Failed";
}

use Elemenx\Mqtt\MqttClass\Mqtt;

public function subscribetoTopic($topic)
{
    $mqtt = new Mqtt();
    $client_id = Auth::user()->id;
    $mqtt->connectAndSubscribe($topic, function($topic, $msg){
        echo "Msg Received: \n";
        echo "Topic: {$topic}\n\n";
        echo "\t$msg\n\n";
    }, $client_id);
}

use Mqtt;

public function subscribetoTopic($topic)
{
    //You can also subscribe to multiple topics using the same function $topic can be array of topics e.g ['topic1', 'topic2']

    Mqtt::connectAndSubscribe($topic, function($topic, $msg){
        echo "Msg Received: \n";
        echo "Topic: {$topic}\n\n";
        echo "\t$msg\n\n";
    },$client_id);
}


public function sendMsgViaMqtt($topic, $message)
{
    $client_id = Auth::user()->id;
    
    $output = connectToPublish($topic, $message, $client_id);

    if ($output === true)
    {
        return "published";
    }

    return "Failed";
}