joserf/mqtt-php-api

MQTT客户端PHP API

v1.0.0 2023-03-04 17:33 UTC

This package is auto-updated.

Last update: 2024-09-04 22:47:13 UTC


README

这是一个库,旨在简化PHP7和PHP8的MQTT客户端开发。

安装

composer require joserf/mqtt-php-api

目录

最低要求

  • php >= 7.4

如何使用

一个非常基本的发布示例(QoS 0)只需要三个步骤:连接、发布和断开连接

按照以下示例更改字段,更改IP和端口。

发布

$server   = '192.168.*.*';
$port     = 1883;
$clientId = 'test-publisher';

$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->publish('test/publisher', 'JRF API Teste!', 0);
$mqtt->disconnect();

如果您不想传递一个$clientId,将为您生成一个随机值。这基本上会强制进行隐式清理会话。

订阅

订阅比发布稍微复杂一些,因为它需要执行一个事件循环,该循环读取、分析和处理代理的消息

$server   = '192.168.*.*';
$port     = 1883;
$clientId = 'test-subscriber';

$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->subscribe('test/subscriber', function ($topic, $message, $retained, $matchedWildcards) {
    echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
$mqtt->disconnect();

使用示例

完整的exemplo.php文件。

*我们可以通过Web进行测试:php -S localhost:8000/exemplo.php

<?php

require_once __DIR__ . '/vendor/autoload.php';
error_reporting(E_ALL);

use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;

$server   = '192.168.*.*';
$port     = 1883;
$clientId = rand(5, 15);
$clean_session = true;
$mqtt_version = MqttClient::MQTT_3_1_1;

$connectionSettings = (new ConnectionSettings)
  ->setKeepAliveInterval(60)
  ->setLastWillMessage('client disconnect')
  ->setLastWillQualityOfService(1);

$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);

$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");

$mqtt->subscribe('mqtt/test', function ($topic, $message) {
    printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);

$mqtt->loop(true);

?>