ultraembeddedlab/php-iot 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ultraembeddedlab/php-iot

Composer 安装命令:

composer require ultraembeddedlab/php-iot

包简介

Modern, production-grade MQTT 3.1.1 & 5 client for PHP 8.4+

README 文档

README

CI Latest Stable Version License PHP Version

Modern, production-grade MQTT 3.1.1 & 5.0 client for PHP 8.4+

Features

  • Modern PHP 8.4+ with strict types and modern syntax
  • MQTT 3.1.1 & 5.0 protocol support
  • TLS/SSL & mutual TLS (mTLS) with typed TlsOptions — client certificates, CA verification, ALPN
  • WebSocket transport (ws://, wss://) with RFC 6455 framing
  • Auto-reconnect with exponential backoff and jitter
  • QoS 0, 1, 2 with automatic resend on ACK timeout
  • Session persistence for reliable message delivery
  • Rate limiter (token bucket) to prevent broker flooding
  • Offline message queue with automatic drain on reconnect
  • Topic aliases (MQTT 5.0)
  • Flow control (MQTT 5.0)
  • Shared subscriptions (MQTT 5.0)
  • Byte counters for traffic monitoring (bytesSent() / bytesReceived())
  • PSR-3 logging support
  • PSR-14 event dispatcher support

Requirements

  • PHP 8.4 or higher
  • ext-sockets extension
  • ext-openssl extension (for TLS)

Installation

Install via Composer:

composer require ultraembeddedlab/php-iot

Quick Start

Simple Publish (Fire and Forget)

The easiest way to publish a message:

use ScienceStories\Mqtt\Easy\Mqtt;

Mqtt::publish(
    host: 'broker.example.com',
    topic: 'sensors/temperature',
    payload: '23.5',
);

Publish with TLS and Authentication

use ScienceStories\Mqtt\Easy\Mqtt;

Mqtt::publish(
    host: 'broker.example.com',
    topic: 'sensors/temperature',
    payload: '23.5',
    tls: true,
    username: 'user',
    password: 'secret',
);

Using MQTT 5.0

use ScienceStories\Mqtt\Easy\Mqtt;
use ScienceStories\Mqtt\Protocol\QoS;

Mqtt::publish(
    host: 'broker.example.com',
    topic: 'sensors/temperature',
    payload: '23.5',
    version: 'v5',
    qos: QoS::AtLeastOnce,
    properties: [
        'message_expiry_interval' => 3600,
        'content_type' => 'text/plain',
    ],
);

Subscribe to Topics

For more complex use cases, use the full client:

use ScienceStories\Mqtt\Client\Client;
use ScienceStories\Mqtt\Client\Options;
use ScienceStories\Mqtt\Protocol\MqttVersion;
use ScienceStories\Mqtt\Transport\TcpTransport;

$options = new Options(
    host: 'broker.example.com',
    port: 1883,
    version: MqttVersion::V5_0,
);

$options = $options
    ->withClientId('my-client')
    ->withKeepAlive(60)
    ->withCleanSession(true);

$client = new Client($options, new TcpTransport());
$client->connect();

// Subscribe to topics
$client->subscribe([
    ['filter' => 'sensors/#', 'qos' => 1],
]);

// Handle incoming messages
$client->onMessage(function ($message) {
    echo "Received: {$message->payload} on {$message->topic}\n";
});

// Listen for messages
while (true) {
    $client->loopOnce(1.0);
}

Long-Running Connection

Use the Mqtt::connect() method for sessions that need to publish multiple messages:

use ScienceStories\Mqtt\Easy\Mqtt;
use ScienceStories\Mqtt\Client\PublishOptions;
use ScienceStories\Mqtt\Protocol\QoS;

$client = Mqtt::connect(
    host: 'broker.example.com',
    port: 1883,
    version: 'v5',
);

// Publish multiple messages
$client->publish('sensors/temp', '23.5', new PublishOptions(qos: QoS::AtLeastOnce));
$client->publish('sensors/humidity', '65', new PublishOptions(qos: QoS::AtLeastOnce));

$client->disconnect();

Configuration Options

Client Options

Option Type Default Description
host string required MQTT broker hostname
port int 1883/8883 Broker port (auto-detected based on TLS)
version MqttVersion V3_1_1 MQTT protocol version
clientId string auto Client identifier
keepAlive int 60 Keep alive interval in seconds
cleanSession bool true Start with clean session
username string null Authentication username
password string null Authentication password
ackTimeout float 5.0 Timeout (seconds) waiting for QoS 1/2 ACK before resend
maxResendAttempts int 3 Max resend attempts for unacknowledged QoS 1/2 messages

Publish Options

Option Type Default Description
qos QoS AtMostOnce Quality of Service level
retain bool false Retain message on broker
properties array null MQTT 5.0 properties

TLS Configuration

Simple TLS (server verification only):

use ScienceStories\Mqtt\Client\TlsOptions;

$options = $options->withTls(new TlsOptions());

Mutual TLS with client certificate (AWS IoT, Azure IoT Hub):

use ScienceStories\Mqtt\Client\TlsOptions;

$tls = (new TlsOptions())
    ->withCaFile('/etc/mqtt/certs/ca.pem')
    ->withClientCertificate(
        certFile: '/etc/mqtt/certs/client.pem',
        keyFile: '/etc/mqtt/certs/client.key',
        passphrase: 'optional-passphrase',
    );

$options = $options->withTls($tls);

MQTT over port 443 with ALPN (when 8883 is blocked):

$tls = (new TlsOptions())
    ->withCaFile('/etc/mqtt/certs/ca.pem')
    ->withClientCertificate('/etc/mqtt/certs/client.pem', '/etc/mqtt/certs/client.key')
    ->withAlpn('mqtt');

$options = (new Options('broker.example.com', 443))->withTls($tls);

Self-signed certificates (development):

$tls = (new TlsOptions())
    ->withCaFile('/path/to/my-ca.pem')
    ->withAllowSelfSigned(true);

$options = $options->withTls($tls);
TlsOptions Method Description
withCaFile(?string) CA certificate file for server verification
withCaPath(?string) Directory of CA certificates
withClientCertificate(?string, ?string, ?string) Client cert, key, and optional passphrase
withAlpn(?string) ALPN protocol (e.g., 'mqtt' for port 443)
withVerifyPeer(bool) Verify server certificate (default: true)
withVerifyPeerName(bool) Verify server hostname (default: true)
withAllowSelfSigned(bool) Allow self-signed certs (default: false)
withPeerName(?string) Override peer name for SNI
withSni(bool) Enable/disable SNI (default: true)

Legacy array syntax is still supported for backward compatibility: $options->withTls(['ssl' => ['verify_peer' => true]])

MQTT 5.0 Features

Topic Aliases

Reduce bandwidth by using numeric aliases for frequently used topics:

$client->publish('long/topic/name', 'data', new PublishOptions(
    properties: ['topic_alias' => 1],
));

Message Expiry

Set expiration time for messages:

$client->publish('alerts/warning', 'Alert!', new PublishOptions(
    properties: ['message_expiry_interval' => 300], // 5 minutes
));

User Properties

Attach custom metadata to messages:

$client->publish('events/user', $payload, new PublishOptions(
    properties: [
        'user_properties' => [
            'source' => 'web-app',
            'version' => '1.0',
        ],
    ],
));

Documentation

Detailed documentation is available in the docs/ directory:

Examples

Check the examples/ directory for complete working examples:

  • Basic connect/publish/subscribe (MQTT 3.1.1 and 5.0)
  • QoS 0, 1, 2 demonstrations
  • mTLS with client certificates (tls_mtls_example.php + cert generation script)
  • Session persistence, shared subscriptions, topic aliases
  • Flow control, server disconnect handling

Testing

# Run tests
composer test

# Run tests with coverage
composer test:coverage

# Static analysis
composer stan

# Code style
composer pint

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for details.

License

PHP IoT MQTT Client is open-sourced software licensed under the MIT license.

Credits

Developed by Bogdan Gewald

ultraembeddedlab/php-iot 适用场景与选型建议

ultraembeddedlab/php-iot 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 189 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 01 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「client」 「networking」 「pub-sub」 「iot」 「mqtt」 「message-broker」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 ultraembeddedlab/php-iot 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ultraembeddedlab/php-iot 我们能提供哪些服务?
定制开发 / 二次开发

基于 ultraembeddedlab/php-iot 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 189
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-18