alexmorbo / react-mqtt
reactphp 中的异步 MQTT 客户端
0.2
2022-02-23 17:32 UTC
Requires
- psr/log: ^3.0
- react/socket: ^1.11.0
This package is auto-updated.
Last update: 2024-09-23 23:03:33 UTC
README
react-mqtt 是一个 PHP 的 MQTT 客户端库。
它基于 reactPHP 的 socket-client 并添加了 MQTT 协议特定功能。同时基于 https://github.com/oliverlorenz/phpMqttClient
目标
此项目的目标是提供一个易于使用的 MQTT 客户端,用于在无需任何 PHP 模块的现代架构中实现 PHP。目前仅实现了协议版本 4(mqtt 3.1.1)。
示例库初始化
// mqtt.php use Morbo\React\Mqtt\Client; use Morbo\React\Mqtt\ConnectionOptions; use Morbo\React\Mqtt\Protocols\Version4; require_once __DIR__ . '/vendor/autoload.php'; // Creating Event Loop $loop = React\EventLoop\Factory::create(); // Connection configuration $config = [ 'host' => '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; require 'mqtt.php'; $connection = $mqtt->connect($config['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; require 'mqtt.php'; $connection = $mqtt->connect($config['host'], $config['port'], $config['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();
可用方法
当前工作
- connect (清洁会话,遗嘱选项,心跳,连接授权)
- disconnect
- publish
- subscribe