PHP code example of alexmorbo / react-mqtt

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

    

alexmorbo / react-mqtt example snippets


// mqtt.php

use Morbo\React\Mqtt\Client;
use Morbo\React\Mqtt\ConnectionOptions;
use Morbo\React\Mqtt\Protocols\Version4;

localhost',
    'port' => 1883,
//    'options' => new ConnectionOptions([
//        'username' => 'auth_user',
//        'password' => 'auth_password',
//        'clientId' => 'react_client', // default is 'react-'.uniqid()
//        'cleanSession' => true, // default is true
//        'cleanSession' => true, // default is true
// .      'willTopic' => '',
// .      'willMessage' => '',
// .      'willQos' => '',
// .      'willRetain' => '',
// .      'keepAlive' => 60, // default is 60
//    ])
];

$mqtt = new Client($loop, new Version4());


use React\Socket\ConnectionInterface;

'host'], $config['port'], $config['options']);

$connection->then(function (ConnectionInterface $stream) use ($mqtt, $loop) {
    /**
     * Stop loop, when client disconnected from mqtt server
     */
    $stream->on('end', function () use ($loop) {
        $loop->stop();
    });

    $data = [
        'foo' => 'bar',
        'bar' => 'baz',
        'time' => time(),
    ];

    $qos = Morbo\React\Mqtt\Packets\QoS\Levels::AT_MOST_ONCE_DELIVERY;  // 0

    $mqtt->publish($stream, 'foo/bar', json_encode($data), $qos)->then(function (ConnectionInterface $stream) use ($mqtt) {
        /**
         * Disconnect when published
         */
        $mqtt->disconnect($stream);
    });
});


$loop->run();

use Morbo\React\Mqtt\Packets;
use React\Socket\ConnectionInterface;

fig['options']);

$connection->then(function (ConnectionInterface $stream) use ($mqtt) {
    $qos = Morbo\React\Mqtt\Packets\QoS\Levels::AT_MOST_ONCE_DELIVERY;  // 0
    $mqtt->subscribe($stream, 'foo/bar', $qos)->then(function (ConnectionInterface $stream) use ($qos) {
        // Success subscription
        $stream->on(Packets\Publish::EVENT, function(Packets\Publish $publish) {
            var_dump($publish);
        });
    }, function ($error) {
        // Subscription error
    });
});

$loop->run();