basttyy/php-mqtt

PHP 编写并针对 PHP 的 MQTT 客户端,https://github.com/php-mqtt/client 的副本

v1.0.0 2022-04-23 12:56 UTC

This package is auto-updated.

Last update: 2024-09-23 19:00:55 UTC


README

Latest Stable Version Total Downloads Coverage Quality Gate Status Maintainability Rating Reliability Rating Security Rating Vulnerabilities License

php-mqtt/clientMarvin Mall 创建并维护。它允许您连接到 MQTT 代理,您可以在其中发布消息并订阅主题。当前实现支持所有 QoS 级别(有局限性)。

安装

该包可在 packagist.org 上获取,并可以使用 composer 安装。

composer require php-mqtt/client

该包需要 PHP 版本 7.4 或更高版本。

用法

以下只给出了一些非常基本的示例。对于更详细的示例,请查看 php-mqtt/client-examples 存储库

发布

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

$server   = 'some-broker.example.com';
$port     = 1883;
$clientId = 'test-publisher';

$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->publish('php-mqtt/client/test', 'Hello World!', 0);
$mqtt->disconnect();

如果您不希望传递 $clientId,将为您生成一个随机的。这基本上会隐式强制一个干净会话。

请注意,大多数方法都可以抛出异常。上述示例没有添加任何异常处理以简短。

订阅

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

$server   = 'some-broker.example.com';
$port     = 1883;
$clientId = 'test-subscriber';

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

当循环活动时,您可以使用 $mqtt->interrupt() 向循环发送中断信号。这将终止循环,在它开始下一次迭代之前。例如,您可以使用 pcntl_signal(SIGINT, $handler) 调用此方法

pcntl_async_signals(true);

$clientId = 'test-subscriber';

$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
pcntl_signal(SIGINT, function (int $signal, $info) use ($mqtt) {
    $mqtt->interrupt();
});
$mqtt->connect();
$mqtt->subscribe('php-mqtt/client/test', function ($topic, $message) {
    echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
$mqtt->disconnect();

客户端设置

如上述示例所示,MqttClient 以服务器、端口和客户端 ID 作为第一个、第二个和第三个参数。作为第四个参数,可以传递协议级别。目前支持 MQTT v3.1,可用作常量 MqttClient::MQTT_3_1。第五个参数允许传递存储库(默认情况下,目前只有 MemoryRepository 可用)。最后,可以传递第六个参数作为记录器。如果没有提供,则使用空记录器。

示例

$mqtt = new \PhpMqtt\Client\MqttClient(
    $server, 
    $port, 
    $clientId,
    \PhpMqtt\Client\MqttClient::MQTT_3_1,
    new \PhpMqtt\Client\Repositories\MemoryRepository(),
    new Logger()
);

Logger 必须实现 Psr\Log\LoggerInterface

连接设置

MqttClientconnect() 方法接受两个可选参数

  1. ConnectionSettings 实例
  2. 一个布尔标志,指示是否应请求干净会话(随机客户端 ID 隐式执行此操作)

示例

$mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);

$connectionSettings = (new \PhpMqtt\Client\ConnectionSettings)
    ->setConnectTimeout(3)
    ->setUseTls(true)
    ->setTlsSelfSignedAllowed(true);
    
$mqtt->connect($connectionSettings, true);

ConnectionSettings 类通过流畅接口提供一些设置。本身是不可变的,并且为每个添加的选项创建一个新的 ConnectionSettings 实例。这也防止在建立连接后更改连接设置。

以下是一份完整的选项列表及其相应的默认值

$connectionSettings = (new \PhpMqtt\Client\ConnectionSettings)

    // The username used for authentication when connecting to the broker.
    ->setUsername(null)
    
    // The password used for authentication when connecting to the broker.
    ->setPassword(null)
    
    // The connect timeout defines the maximum amount of seconds the client will try to establish
    // a socket connection with the broker. The value cannot be less than 1 second.
    ->setConnectTimeout(60)
    
    // The socket timeout is the maximum amount of idle time in seconds for the socket connection.
    // If no data is read or sent for the given amount of seconds, the socket will be closed.
    // The value cannot be less than 1 second.
    ->setSocketTimeout(5)
    
    // The resend timeout is the number of seconds the client will wait before sending a duplicate
    // of pending messages without acknowledgement. The value cannot be less than 1 second.
    ->setResendTimeout(10)
    
    // The keep alive interval is the number of seconds the client will wait without sending a message
    // until it sends a keep alive signal (ping) to the broker. The value cannot be less than 1 second
    // and may not be higher than 65535 seconds. A reasonable value is 10 seconds (the default).
    ->setKeepAliveInterval(10)
    
    // If the broker should publish a last will message in the name of the client when the client
    // disconnects abruptly, this setting defines the topic on which the message will be published.
    //
    // A last will message will only be published if both this setting as well as the last will
    // message are configured.
    ->setLastWillTopic(null)
    
    // If the broker should publish a last will message in the name of the client when the client
    // disconnects abruptly, this setting defines the message which will be published.
    //
    // A last will message will only be published if both this setting as well as the last will
    // topic are configured.
    ->setLastWillMessage(null)
    
    // The quality of service level the last will message of the client will be published with,
    // if it gets triggered.
    ->setLastWillQualityOfService(0)
    
    // This flag determines if the last will message of the client will be retained, if it gets
    // triggered. Using this setting can be handy to signal that a client is offline by publishing
    // a retained offline state in the last will and an online state as first message on connect.
    ->setRetainLastWill(false)
    
    // This flag determines if TLS should be used for the connection. The port which is used to
    // connect to the broker must support TLS connections.
    ->setUseTls(false)
    
    // This flag determines if the peer certificate is verified, if TLS is used.
    ->setTlsVerifyPeer(true)
    
    // This flag determines if the peer name is verified, if TLS is used.
    ->setTlsVerifyPeerName(true)
    
    // This flag determines if self signed certificates of the peer should be accepted.
    // Setting this to TRUE implies a security risk and should be avoided for production
    // scenarios and public services.
    ->setTlsSelfSignedAllowed(false)
    
    // The path to a Certificate Authority certificate which is used to verify the peer
    // certificate, if TLS is used.
    ->setTlsCertificateAuthorityFile(null)
    
    // The path to a directory containing Certificate Authority certificates which are
    // used to verify the peer certificate, if TLS is used.
    ->setTlsCertificateAuthorityPath(null)
    
    // The path to a client certificate file used for authentication, if TLS is used.
    //
    // The client certificate must be PEM encoded. It may optionally contain the
    // certificate chain of issuers.
    ->setTlsClientCertificateFile(null)
    
    // The path to a client certificate key file used for authentication, if TLS is used.
    //
    // This option requires ConnectionSettings::setTlsClientCertificateFile() to be used as well.
    ->setTlsClientCertificateKeyFile(null)
    
    // The passphrase used to decrypt the private key of the client certificate,
    // which in return is used for authentication, if TLS is used.
    //
    // This option requires ConnectionSettings::setTlsClientCertificateFile() and
    // ConnectionSettings::setTlsClientCertificateKeyFile() to be used as well.
    ->setTlsClientCertificateKeyPassphrase(null);

功能

  • 支持的 MQTT 版本
    • v3(不要使用 v3.1 功能,如用户名和密码)
    • v3.1
    • v3.1.1
    • v5.0
  • 传输
    • TCP(未加密)
    • TLS(加密,使用证书授权文件验证对等方)
  • 连接
    • 最后将会话
    • 消息保留
    • 身份验证(用户名和密码)
    • TLS 加密连接
    • 干净会话(可以设置和发送,但客户端对 QoS 2 消息没有持久性)
  • 发布
    • QoS 级别 0
    • QoS 级别 1(限制:会话间无持久状态)
    • QoS 级别 2(限制:会话间无持久状态)
  • 订阅
    • QoS 级别 0
    • QoS 级别 1
    • QoS 级别 2(限制:会话间无持久状态)
  • 支持的消息长度:无限长 (没有限制强制执行,尽管 MQTT 协议支持最多 256MB,但无论如何都不应使用)
  • 日志记录可能(Psr\Log\LoggerInterface 可以传递给客户端)
  • 持久化驱动程序
    • 内存驱动程序
    • Redis 驱动程序

限制

  • QoS 级别高于 0 的消息流默认实现使用内存存储库,因此不会持久化。为了避免消息流损坏的问题,请使用 clean session 标志来表示您不关心旧数据。这不仅将指示代理器将连接视为新的(没有先前状态),还会重置已注册的存储库。

开发与测试

证书(TLS)

要运行测试(尤其是 TLS 测试),您需要创建证书。已提供命令来完成此操作

sh create-certificates.sh

这将创建 .ci/tls/ 目录中所需的所有证书。相同的脚本也用于持续集成。

测试用例的 MQTT 代理

运行测试预期 MQTT 代理正在运行。运行 MQTT 代理的最简单方法是使用 Docker

docker run --rm -it -p 1883:1883 -p 8883:8883 -p 8884:8884 -v $(pwd)/.ci/tls:/mosquitto-certs -v $(pwd)/.ci/mosquitto.conf:/mosquitto/config/mosquitto.conf eclipse-mosquitto:1.6

从项目目录运行时,这将生成一个配置了生成的 TLS 证书和自定义配置的 Mosquitto MQTT 代理。

如果您打算运行不同的代理或使用不同的方法,或者使用公共代理,则需要根据 phpunit.xml 中定义的环境变量进行调整。

许可证

php-mqtt/client 是开源软件,许可协议为 MIT 许可证