PHP code example of zoujingli / type-mqtt

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

    

zoujingli / type-mqtt example snippets




declare(strict_types=1);

use Type\Mqtt\ConnectPacket;
use Type\Mqtt\Message;
use Type\Mqtt\ProtocolError;

/** 验证公开消息类型的离线协议边界,不启动 Broker 或认证任何客户端。 */
function main(): void
{
    $clientId = 'guide-client';
    $connectBody = pack('n', 4) . 'MQTT' . "\x05\x02" . pack('n', 30)
        . "\x00" . pack('n', strlen($clientId)) . $clientId;
    $connect = new ConnectPacket();
    $connect->decode($connectBody);

    $message = new Message('example/up', '{"temperature":23}', qos: 0);
    $packet = $message->packet(5);
    $invalidTopicRejected = false;
    try {
        new Message('example/+', '23');
    } catch (ProtocolError $error) {
        $invalidTopicRejected = $error->reason === 0x90;
    }
    echo json_encode([
        'protocol' => $connect->version,
        'client_id' => $connect->clientId,
        'topic' => $message->topic,
        'qos' => $message->qos,
        'packet_bytes' => strlen($packet),
        'publish_header' => ord($packet[0]),
        'invalid_topic_rejected' => $invalidTopicRejected,
    ], JSON_THROW_ON_ERROR) . "\n";
}

$client = new \Type\Mqtt\Client(
    host: '127.0.0.1',
    port: 8883,
    clientId: 'ingestion-1',
    username: 'service',
    password: (string) getenv('MQTT_SERVICE_PASSWORD'),
    caFile: 'certificates/ca.pem',
    peerName: 'mqtt.example.com'
);
try {
    $present = $client->connect(cleanStart: false, timeout: 5.0);
    if (!$present) {
        $client->subscribe('example/up', options: 1);
    }
    $delivery = $client->receive(timeout: 1.0);
    if ($delivery !== null) {
        // 此处调用应用自己的接收账本和同步持久证明;尚未确认时保持receipt未确认。
        // 应用确认完成后才调用:$client->acknowledge($delivery['receipt']);
    }
} finally {
    $client->close();
}