Home >Backend Development >PHP Problem >What works for PHP protocol parsing and coroutine clients

What works for PHP protocol parsing and coroutine clients

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-06-28 15:44:352434browse

MQTT is a "lightweight" communication protocol based on the publish/subscribe model. As an instant messaging protocol with low overhead and low bandwidth usage, it has become an important part of the Internet of Things. Today I will show you Learn about simps/mqtt.

What works for PHP protocol parsing and coroutine clients

MQTT is a "lightweight" communication protocol based on publish/subscribe (publish/subscribe) mode, as a low-overhead, low-bandwidth instant messaging Protocol has become an important part of the Internet of Things

Swoole also provides PHP with the ability to develop Internet of Things projects. You only need to set an open_mqtt_protocol option. After enabling it, the MQTT header will be parsed. In the Worker process The onReceive event will return a complete MQTT data packet every time

Of course there are others, such as the asynchronous mqtt client library previously provided by Workerman, and other open source libraries, which will not be introduced one by one here

Simps' first version of the MQTT library refers to the implementation of Workerman, enabling it to use Swoole's coroutine capabilities, and also fixes some problems

I would also like to thank @walkor for this Contributions made by the PHP ecosystem

The implementation of the first version was placed in the framework, which restricted the use of some users. So we started refactoring again, and separated MQTT into a library, which not only made it easier for users to use, but also enriched the PHP ecosystem, so that PHP programmers are no longer limited to Web development

After the first version was released, Simps There are also many users asking about MQTT in the communication group. Swoole has also fixed some related bugs. Now using PHP Swoole to develop IoT-related projects should be even more powerful

At the same time, the first version of the MQTT library , only supports MQTT 3.x and does not support MQTT 5.0. There is no relevant supported class library found on GitHub, so after refactoring the 3.x version, MQTT 5.0 is also supported

Maybe this It is the first PHP library to support MQTT v5.0 protocol...

Supports MQTT protocol versions 3.1, 3.1.1 and 5.0, supports QoS 0, QoS 1, QoS 2, then it is here, use Composer to install

composer require simps/mqtt

After successful installation, let’s take a look at the use of subscription and publishing, taking MQTT5.0 as an example

Subscription

The first thing should be subscription, after the subscription is successful In order to receive the publishing message of the corresponding topic, create a subscribe.php and write the following content

include __DIR__ . '/vendor/autoload.php';

use Simps\MQTT\Hex\ReasonCode;
use Swoole\Coroutine;
use Simps\MQTT\Client;
use Simps\MQTT\Types;

$config = [
    'host' => 'broker.emqx.io',
    'port' => 1883,
    'time_out' => 5,
    'user_name' => 'user001',
    'password' => 'hLXQ9ubnZGzkzf',
    'client_id' => Client::genClientID(),
    'keep_alive' => 10,
    'properties' => [
        'session_expiry_interval' => 60,
        'receive_maximum' => 200,
        'topic_alias_maximum' => 200,
    ],
    'protocol_level' => 5,
];

Coroutine\run(function () use ($config) {
    $client = new Client($config, ['open_mqtt_protocol' => true, 'package_max_length' => 2 * 1024 * 1024]);
    while (!$data = $client->connect()) {
        Coroutine::sleep(3);
        $client->connect();
    }
    $topics['simps-mqtt/user001/get'] = [
        'qos' => 1,
        'no_local' => true,
        'retain_as_published' => true,
        'retain_handling' => 2,
    ];
    $timeSincePing = time();
    $res = $client->subscribe($topics);
    // 订阅的结果
    var_dump($res);
    while (true) {
        $buffer = $client->recv();
        if ($buffer && $buffer !== true) {
            $timeSincePing = time();
            // 收到的数据包
            var_dump($buffer);
        }
        if (isset($config[&#39;keep_alive&#39;]) && $timeSincePing < (time() - $config[&#39;keep_alive&#39;])) {
            $buffer = $client->ping();
            if ($buffer) {
                echo &#39;send ping success&#39; . PHP_EOL;
                $timeSincePing = time();
            } else {
                $client->close();
                break;
            }
        }
        // QoS1 发布回复
        if ($buffer[&#39;type&#39;] === Types::PUBLISH && $buffer[&#39;qos&#39;] === 1) {
            $client->send(
                [
                    &#39;type&#39; => Types::PUBACK,
                    &#39;message_id&#39; => $buffer[&#39;message_id&#39;],
                    &#39;code&#39; => ReasonCode::SUCCESS
                ]
            );
        }
    }
});

Execute php subscribe.php, you will get such output

array(3) {
  ["type"]=>
  int(9)
  ["message_id"]=>
  int(1)
  ["codes"]=>
  array(1) {
    [0]=>
    int(1)
  }
}

Indicates that the subscription is successful, and the codes correspond is the QoS level corresponding to the subscription topic

Publish

After the subscription is successful, create a publish.php to test the publication

include __DIR__ . &#39;/vendor/autoload.php&#39;;

use Swoole\Coroutine;
use Simps\MQTT\Client;

$config = [
    &#39;host&#39; => &#39;broker.emqx.io&#39;,
    &#39;port&#39; => 1883,
    &#39;time_out&#39; => 5,
    &#39;user_name&#39; => &#39;user002&#39;,
    &#39;password&#39; => &#39;adIJS1D482sd&#39;,
    &#39;client_id&#39; => Client::genClientID(),
    &#39;keep_alive&#39; => 20,
    &#39;properties&#39; => [
        &#39;session_expiry_interval&#39; => 60,
        &#39;receive_maximum&#39; => 200,
        &#39;topic_alias_maximum&#39; => 200,
    ],
    &#39;protocol_level&#39; => 5,
];

Coroutine\run(function () use ($config) {
    $client = new Client($config, [&#39;open_mqtt_protocol&#39; => true, &#39;package_max_length&#39; => 2 * 1024 * 1024]);
    while (!$client->connect()) {
        Coroutine::sleep(3);
        $client->connect();
    }
    while (true) {
        $response = $client->publish(
            &#39;simps-mqtt/user001/get&#39;,
            &#39;{"time":&#39; . time() . &#39;}&#39;,
            1,
            0,
            0,
            [&#39;topic_alias&#39; => 1]
        );
        var_dump($response);
        Coroutine::sleep(3);
    }
});

The code means to subscribe every 3 seconds The topic simps-mqtt/user001/get publishes a message

Open a new terminal window and execute php publish.php and you will get the output:

array(4) {
  ["type"]=>
  int(4)
  ["message_id"]=>
  int(1)
  ["code"]=>
  int(0)
  ["message"]=>
  string(7) "Success"
}

Message is added here, so that users can Reading, there is no need to look up the corresponding code. What is the meaning?

Return to the subscription window, you will see the printed publication information

array(8) {
  ["type"]=>
  int(3)
  ["topic"]=>
  string(0) ""
  ["message"]=>
  string(19) "{"time":1608017156}"
  ["dup"]=>
  int(1)
  ["qos"]=>
  int(1)
  ["retain"]=>
  int(0)
  ["message_id"]=>
  int(4)
  ["properties"]=>
  array(1) {
    ["topic_alias"]=>
    int(1)
  }
}

Such a simple publish and subscribe function is realized

There are still some parts in this library that are worthy of optimization and have not yet been completed, such as the Auth type that does not yet support MQTT5, and some properties that are not supported yet

Students who want to participate can submit PR, if you have any questions, you can also submit an Issue, let us work together to build the PHP ecosystem

Recommended learning:php video tutorial

The above is the detailed content of What works for PHP protocol parsing and coroutine clients. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete