From 3dc5bcd59ba16eaacfe2d5056bc3c0119fe2c130 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 14:16:13 +0800 Subject: [PATCH 01/10] PHP 7.0 is no longer supported --- README-CN.md | 2 +- README.md | 2 +- composer.json | 2 +- docs/en/README.md | 2 +- docs/zh-cn/README.md | 2 +- src/Tools/UnPackTool.php | 4 ++-- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README-CN.md b/README-CN.md index a50dfdd..3fb2e0e 100644 --- a/README-CN.md +++ b/README-CN.md @@ -10,7 +10,7 @@ [![Total Downloads](https://poser.pugx.org/simps/mqtt/downloads)](//packagist.org/packages/simps/mqtt) [![Latest Unstable Version](https://poser.pugx.org/simps/mqtt/v/unstable)](//packagist.org/packages/simps/mqtt) [![License](https://poser.pugx.org/simps/mqtt/license)](LICENSE) -[![PHP Version](https://img.shields.io/badge/php-%3E=7.0-blue.svg)](https://www.php.net) +[![PHP Version](https://img.shields.io/badge/php-%3E=7.1-blue.svg)](https://www.php.net) [![Swoole Version](https://img.shields.io/badge/swoole-%3E=4.4.19-blue.svg)](https://github.com/swoole/swoole-src) [![GitHub Actions](https://github.com/simps/mqtt/workflows/PHPUnit%20for%20MQTT/badge.svg)](https://github.com/simps/mqtt/actions) diff --git a/README.md b/README.md index 8d283bb..fdfd7ab 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Support for `QoS 0`, `QoS 1`, `QoS 2`. [![Total Downloads](https://poser.pugx.org/simps/mqtt/downloads)](//packagist.org/packages/simps/mqtt) [![Latest Unstable Version](https://poser.pugx.org/simps/mqtt/v/unstable)](//packagist.org/packages/simps/mqtt) [![License](https://poser.pugx.org/simps/mqtt/license)](LICENSE) -[![PHP Version](https://img.shields.io/badge/php-%3E=7.0-blue.svg)](https://www.php.net) +[![PHP Version](https://img.shields.io/badge/php-%3E=7.1-blue.svg)](https://www.php.net) [![Swoole Version](https://img.shields.io/badge/swoole-%3E=4.4.19-blue.svg)](https://github.com/swoole/swoole-src) [![GitHub Actions](https://github.com/simps/mqtt/workflows/PHPUnit%20for%20MQTT/badge.svg)](https://github.com/simps/mqtt/actions) diff --git a/composer.json b/composer.json index d7c2eca..eda5463 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ } ], "require": { - "php": ">=7.0", + "php": ">=7.1", "ext-mbstring": "*" }, "require-dev": { diff --git a/docs/en/README.md b/docs/en/README.md index 9d11dad..8861af2 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -8,7 +8,7 @@ Support for `QoS 0`, `QoS 1`, `QoS 2`. ## Requirements -* PHP >= `7.0` +* PHP >= `7.1` * ext-mbstring * [ext-swoole](https://github.com/swoole/swoole-src) >= `4.4.19` (The ext-swoole >= `v4.4.19` needs to be loaded when using [the MQTT Client](/en/client)) diff --git a/docs/zh-cn/README.md b/docs/zh-cn/README.md index 665bb24..f7f25cf 100644 --- a/docs/zh-cn/README.md +++ b/docs/zh-cn/README.md @@ -6,7 +6,7 @@ ## 依赖要求 -* PHP >= `7.0` +* PHP >= `7.1` * mbstring PHP 扩展 * [Swoole 扩展](https://github.com/swoole/swoole-src) >= `4.4.19` (使用 [Client](/zh-cn/client) 时需要) diff --git a/src/Tools/UnPackTool.php b/src/Tools/UnPackTool.php index ec7f053..678dfa7 100644 --- a/src/Tools/UnPackTool.php +++ b/src/Tools/UnPackTool.php @@ -58,7 +58,7 @@ public static function byte(string &$remaining): int return $tmp; } - public static function varInt(string &$remaining, &$len): int + public static function varInt(string &$remaining, ?int &$len): int { $remainingLength = static::getRemainingLength($remaining, $headBytes); $len = $headBytes; @@ -74,7 +74,7 @@ public static function varInt(string &$remaining, &$len): int return $result; } - private static function getRemainingLength(string $data, &$headBytes): int + private static function getRemainingLength(string $data, ?int &$headBytes): int { $headBytes = $multiplier = 1; $value = 0; From 0176469b93ffba1343b0aeac3b500b46d0537aaf Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 14:25:05 +0800 Subject: [PATCH 02/10] Add visibility on all constants --- src/ProtocolInterface.php | 16 ++++++++-------- src/Types.php | 30 +++++++++++++++--------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/ProtocolInterface.php b/src/ProtocolInterface.php index 4347255..7c55bd4 100644 --- a/src/ProtocolInterface.php +++ b/src/ProtocolInterface.php @@ -15,21 +15,21 @@ interface ProtocolInterface { - const MQTT_PROTOCOL_LEVEL_3_1 = 3; + public const MQTT_PROTOCOL_LEVEL_3_1 = 3; - const MQTT_PROTOCOL_LEVEL_3_1_1 = 4; + public const MQTT_PROTOCOL_LEVEL_3_1_1 = 4; - const MQTT_PROTOCOL_LEVEL_5_0 = 5; + public const MQTT_PROTOCOL_LEVEL_5_0 = 5; - const MQISDP_PROTOCOL_NAME = 'MQIsdp'; + public const MQISDP_PROTOCOL_NAME = 'MQIsdp'; - const MQTT_PROTOCOL_NAME = 'MQTT'; + public const MQTT_PROTOCOL_NAME = 'MQTT'; - const MQTT_QOS_0 = 0; + public const MQTT_QOS_0 = 0; - const MQTT_QOS_1 = 1; + public const MQTT_QOS_1 = 1; - const MQTT_QOS_2 = 2; + public const MQTT_QOS_2 = 2; public static function pack(array $array): string; diff --git a/src/Types.php b/src/Types.php index bd558b0..2e5c16e 100644 --- a/src/Types.php +++ b/src/Types.php @@ -15,33 +15,33 @@ class Types { - const CONNECT = 1; // Client request to connect to Server + public const CONNECT = 1; // Client request to connect to Server - const CONNACK = 2; // Connect acknowledgment + public const CONNACK = 2; // Connect acknowledgment - const PUBLISH = 3; // Publish message + public const PUBLISH = 3; // Publish message - const PUBACK = 4; // Publish acknowledgment + public const PUBACK = 4; // Publish acknowledgment - const PUBREC = 5; // Publish received (assured delivery part 1) + public const PUBREC = 5; // Publish received (assured delivery part 1) - const PUBREL = 6; // Publish release (assured delivery part 2) + public const PUBREL = 6; // Publish release (assured delivery part 2) - const PUBCOMP = 7; // Publish complete (assured delivery part 3) + public const PUBCOMP = 7; // Publish complete (assured delivery part 3) - const SUBSCRIBE = 8; // Client subscribe request + public const SUBSCRIBE = 8; // Client subscribe request - const SUBACK = 9; // Subscribe acknowledgment + public const SUBACK = 9; // Subscribe acknowledgment - const UNSUBSCRIBE = 10; // Unsubscribe request + public const UNSUBSCRIBE = 10; // Unsubscribe request - const UNSUBACK = 11; // Unsubscribe acknowledgment + public const UNSUBACK = 11; // Unsubscribe acknowledgment - const PINGREQ = 12; // PING request + public const PINGREQ = 12; // PING request - const PINGRESP = 13; // PING response + public const PINGRESP = 13; // PING response - const DISCONNECT = 14; // Client is disconnecting + public const DISCONNECT = 14; // Client is disconnecting - const AUTH = 15; // Authentication exchange + public const AUTH = 15; // Authentication exchange } From 2204df6f38188b3d4c4c2f307f291e45d38581b8 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 16:12:10 +0800 Subject: [PATCH 03/10] Update Protocol --- src/{ => Protocol}/ProtocolInterface.php | 2 +- src/{ => Protocol}/Types.php | 2 +- src/{Protocol.php => Protocol/V3.php} | 4 ++-- src/{ProtocolV5.php => Protocol/V5.php} | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename src/{ => Protocol}/ProtocolInterface.php (96%) rename src/{ => Protocol}/Types.php (97%) rename src/{Protocol.php => Protocol/V3.php} (98%) rename src/{ProtocolV5.php => Protocol/V5.php} (98%) diff --git a/src/ProtocolInterface.php b/src/Protocol/ProtocolInterface.php similarity index 96% rename from src/ProtocolInterface.php rename to src/Protocol/ProtocolInterface.php index 7c55bd4..ea88388 100644 --- a/src/ProtocolInterface.php +++ b/src/Protocol/ProtocolInterface.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Simps\MQTT; +namespace Simps\MQTT\Protocol; interface ProtocolInterface { diff --git a/src/Types.php b/src/Protocol/Types.php similarity index 97% rename from src/Types.php rename to src/Protocol/Types.php index 2e5c16e..3c82ce1 100644 --- a/src/Types.php +++ b/src/Protocol/Types.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Simps\MQTT; +namespace Simps\MQTT\Protocol; class Types { diff --git a/src/Protocol.php b/src/Protocol/V3.php similarity index 98% rename from src/Protocol.php rename to src/Protocol/V3.php index d328b4c..feeb90b 100644 --- a/src/Protocol.php +++ b/src/Protocol/V3.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Simps\MQTT; +namespace Simps\MQTT\Protocol; use Simps\MQTT\Exception\InvalidArgumentException; use Simps\MQTT\Exception\RuntimeException; @@ -22,7 +22,7 @@ use Throwable; use TypeError; -class Protocol implements ProtocolInterface +class V3 implements ProtocolInterface { public static function pack(array $array): string { diff --git a/src/ProtocolV5.php b/src/Protocol/V5.php similarity index 98% rename from src/ProtocolV5.php rename to src/Protocol/V5.php index 7ac6786..7ebb46b 100644 --- a/src/ProtocolV5.php +++ b/src/Protocol/V5.php @@ -11,7 +11,7 @@ declare(strict_types=1); -namespace Simps\MQTT; +namespace Simps\MQTT\Protocol; use Simps\MQTT\Exception\InvalidArgumentException; use Simps\MQTT\Packet\PackV5; @@ -19,7 +19,7 @@ use Simps\MQTT\Tools\PackTool; use Simps\MQTT\Tools\UnPackTool; -class ProtocolV5 implements ProtocolInterface +class V5 implements ProtocolInterface { public static function pack(array $array): string { From d90b9dce23d4792c5df2006e8214b3998d28dcf0 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 16:14:59 +0800 Subject: [PATCH 04/10] Add ClientConfig --- src/Config/AbstractConfig.php | 29 +++++++ src/Config/ClientConfig.php | 159 ++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 src/Config/AbstractConfig.php create mode 100644 src/Config/ClientConfig.php diff --git a/src/Config/AbstractConfig.php b/src/Config/AbstractConfig.php new file mode 100644 index 0000000..fe3db17 --- /dev/null +++ b/src/Config/AbstractConfig.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, + * please view the LICENSE file that was distributed with this source code + */ + +declare(strict_types=1); + +namespace Simps\MQTT\Config; + +class AbstractConfig +{ + public function __construct(array $data = []) + { + foreach ($data as $k => $v) { + $methodName = 'set' . ucfirst($k); + if (method_exists($this, $methodName)) { + $this->{$methodName}($v); + } else { + $this->{$k} = $v; + } + } + } +} diff --git a/src/Config/ClientConfig.php b/src/Config/ClientConfig.php new file mode 100644 index 0000000..70a4e5f --- /dev/null +++ b/src/Config/ClientConfig.php @@ -0,0 +1,159 @@ + + * + * For the full copyright and license information, + * please view the LICENSE file that was distributed with this source code + */ + +declare(strict_types=1); + +namespace Simps\MQTT\Config; + +use Simps\MQTT\Protocol\ProtocolInterface; + +class ClientConfig extends AbstractConfig +{ + protected $clientId; + + protected $swooleConfig = []; + + protected $userName; + + protected $password; + + protected $keepAlive = 0; + + protected $protocolName = ProtocolInterface::MQTT_PROTOCOL_NAME; + + protected $protocolLevel = ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1; + + protected $properties = []; + + protected $reconnectDelay = 3; + + protected $sockType = SWOOLE_SOCK_TCP; + + public function getClientId(): ?string + { + return $this->clientId; + } + + public function setClientId(?string $clientId): self + { + $this->clientId = $clientId; + + return $this; + } + + public function getSwooleConfig(): array + { + return $this->swooleConfig; + } + + public function setSwooleConfig(array $config): self + { + $this->swooleConfig = $config; + + return $this; + } + + public function getUserName(): ?string + { + return $this->userName; + } + + public function setUserName(?string $userName): self + { + $this->userName = $userName; + + return $this; + } + + public function getPassword(): ?string + { + return $this->password; + } + + public function setPassword(?string $password): self + { + $this->password = $password; + + return $this; + } + + public function getKeepAlive(): int + { + return $this->keepAlive; + } + + public function setKeepAlive(int $keepAlive): self + { + $this->keepAlive = $keepAlive; + + return $this; + } + + public function getProtocolName(): string + { + return $this->protocolName; + } + + public function setProtocolName(string $protocolName): self + { + $this->protocolName = $protocolName; + + return $this; + } + + public function getProtocolLevel(): int + { + return $this->protocolLevel; + } + + public function setProtocolLevel(int $protocolLevel): self + { + $this->protocolLevel = $protocolLevel; + + return $this; + } + + public function getProperties(): array + { + return $this->properties; + } + + public function setProperties(array $properties): self + { + $this->properties = $properties; + + return $this; + } + + public function getReconnectDelay(): int + { + return $this->reconnectDelay; + } + + public function setReconnectDelay(int $delay): self + { + $this->reconnectDelay = $delay; + + return $this; + } + + public function getSockType(): int + { + return $this->sockType; + } + + public function setSockType(int $sockType): self + { + $this->sockType = $sockType; + + return $this; + } +} From 28f8abe065ad0e758d89b086f5b744be91b12ab1 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 16:15:52 +0800 Subject: [PATCH 05/10] Update packet namespace --- src/Packet/Pack.php | 4 ++-- src/Packet/PackV5.php | 2 +- src/Packet/UnPack.php | 2 +- src/Packet/UnPackV5.php | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Packet/Pack.php b/src/Packet/Pack.php index f82abe2..18dbc04 100644 --- a/src/Packet/Pack.php +++ b/src/Packet/Pack.php @@ -14,9 +14,9 @@ namespace Simps\MQTT\Packet; use Simps\MQTT\Exception\ProtocolException; -use Simps\MQTT\ProtocolInterface; +use Simps\MQTT\Protocol\ProtocolInterface; +use Simps\MQTT\Protocol\Types; use Simps\MQTT\Tools\PackTool; -use Simps\MQTT\Types; class Pack { diff --git a/src/Packet/PackV5.php b/src/Packet/PackV5.php index 582ebff..5b4c5bd 100644 --- a/src/Packet/PackV5.php +++ b/src/Packet/PackV5.php @@ -15,8 +15,8 @@ use Simps\MQTT\Hex\ReasonCode; use Simps\MQTT\Property\PackProperty; +use Simps\MQTT\Protocol\Types; use Simps\MQTT\Tools\PackTool; -use Simps\MQTT\Types; class PackV5 { diff --git a/src/Packet/UnPack.php b/src/Packet/UnPack.php index 455e4a2..720c2a7 100644 --- a/src/Packet/UnPack.php +++ b/src/Packet/UnPack.php @@ -13,8 +13,8 @@ namespace Simps\MQTT\Packet; +use Simps\MQTT\Protocol\Types; use Simps\MQTT\Tools\UnPackTool; -use Simps\MQTT\Types; class UnPack { diff --git a/src/Packet/UnPackV5.php b/src/Packet/UnPackV5.php index db4b1c5..b0b6a3a 100644 --- a/src/Packet/UnPackV5.php +++ b/src/Packet/UnPackV5.php @@ -15,8 +15,8 @@ use Simps\MQTT\Hex\ReasonCode; use Simps\MQTT\Property\UnPackProperty; +use Simps\MQTT\Protocol\Types; use Simps\MQTT\Tools\UnPackTool; -use Simps\MQTT\Types; class UnPackV5 { From 92292244d1bb08bb2e12f43290e8fb71db485cd1 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 16:15:59 +0800 Subject: [PATCH 06/10] Update client --- src/Client.php | 125 ++++++++++++++++++++++++++++--------------------- 1 file changed, 71 insertions(+), 54 deletions(-) diff --git a/src/Client.php b/src/Client.php index 640bad5..b4a4ef5 100644 --- a/src/Client.php +++ b/src/Client.php @@ -13,6 +13,7 @@ namespace Simps\MQTT; +use Simps\MQTT\Config\ClientConfig; use Simps\MQTT\Exception\ProtocolException; use Simps\MQTT\Exception\RuntimeException; use Simps\MQTT\Hex\ReasonCode; @@ -23,62 +24,56 @@ class Client /** @var Coroutine\Client|\Swoole\Client */ private $client; - private $config = [ - 'host' => '127.0.0.1', - 'port' => 1883, - 'user_name' => '', - 'password' => '', - 'client_id' => '', - 'keep_alive' => 0, - 'protocol_name' => ProtocolInterface::MQTT_PROTOCOL_NAME, - 'protocol_level' => ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1, - 'properties' => [], - 'reconnect_delay' => 3, - ]; - private $messageId = 0; private $connectData = []; + private $host; + + private $port; + + private $config; + private $clientType; - const COROUTINE_CLIENT_TYPE = 1; + public const COROUTINE_CLIENT_TYPE = 1; - const SYNC_CLIENT_TYPE = 2; + public const SYNC_CLIENT_TYPE = 2; public function __construct( - array $config, - array $swConfig = [], - int $type = SWOOLE_SOCK_TCP, + string $host, + int $port, + ?ClientConfig $config = null, int $clientType = self::COROUTINE_CLIENT_TYPE ) { - $this->config = array_replace_recursive($this->config, $config); + $this->host = $host; + $this->port = $port; + $this->config = $config; $this->clientType = $clientType; + if ($this->isCoroutineClientType()) { - $this->client = new Coroutine\Client($type); + $this->client = new Coroutine\Client($config->getSockType()); } else { - $this->client = new \Swoole\Client($type); + $this->client = new \Swoole\Client($config->getSockType()); } - if (!empty($swConfig)) { - $this->client->set($swConfig); - } - if (!$this->client->connect($this->config['host'], $this->config['port'])) { - $this->reConnect($this->config['reconnect_delay']); + $this->client->set($config->getSwooleConfig()); + if (!$this->client->connect($host, $port)) { + $this->reConnect($config->getReconnectDelay()); } } public function connect(bool $clean = true, array $will = []) { $data = [ - 'type' => Types::CONNECT, - 'protocol_name' => $this->config['protocol_name'], - 'protocol_level' => (int) $this->config['protocol_level'], + 'type' => Protocol\Types::CONNECT, + 'protocol_name' => $this->getConfig()->getProtocolName(), + 'protocol_level' => $this->getConfig()->getProtocolLevel(), 'clean_session' => $clean, - 'client_id' => $this->config['client_id'], - 'keep_alive' => $this->config['keep_alive'], - 'properties' => $this->config['properties'], - 'user_name' => $this->config['user_name'], - 'password' => $this->config['password'], + 'client_id' => $this->getConfig()->getClientId(), + 'keep_alive' => $this->getConfig()->getKeepAlive(), + 'properties' => $this->getConfig()->getProperties(), + 'user_name' => $this->getConfig()->getUserName(), + 'password' => $this->getConfig()->getPassword(), ]; if (!empty($will)) { $data['will'] = $will; @@ -92,7 +87,7 @@ public function connect(bool $clean = true, array $will = []) public function subscribe(array $topics, array $properties = []) { $data = [ - 'type' => Types::SUBSCRIBE, + 'type' => Protocol\Types::SUBSCRIBE, 'message_id' => $this->buildMessageId(), 'properties' => $properties, 'topics' => $topics, @@ -104,7 +99,7 @@ public function subscribe(array $topics, array $properties = []) public function unSubscribe(array $topics, array $properties = []) { $data = [ - 'type' => Types::UNSUBSCRIBE, + 'type' => Protocol\Types::UNSUBSCRIBE, 'message_id' => $this->buildMessageId(), 'properties' => $properties, 'topics' => $topics, @@ -122,8 +117,8 @@ public function publish( array $properties = [] ) { if (empty($topic)) { - switch ($this->config['protocol_level']) { - case ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0: + switch ($this->getConfig()->getProtocolLevel()) { + case Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0: if (!isset($properties['topic_alias'])) { throw new ProtocolException( 'Protocol Error, Topic cannot be empty or need to set topic_alias' @@ -139,7 +134,7 @@ public function publish( return $this->send( [ - 'type' => Types::PUBLISH, + 'type' => Protocol\Types::PUBLISH, 'qos' => $qos, 'dup' => $dup, 'retain' => $retain, @@ -154,24 +149,23 @@ public function publish( public function ping() { - return $this->send(['type' => Types::PINGREQ]); + return $this->send(['type' => Protocol\Types::PINGREQ]); } public function close(int $code = ReasonCode::NORMAL_DISCONNECTION, array $properties = []): bool { - $this->send(['type' => Types::DISCONNECT, 'code' => $code, 'properties' => $properties], false); + $this->send(['type' => Protocol\Types::DISCONNECT, 'code' => $code, 'properties' => $properties], false); return $this->client->close(); } public function auth(int $code = ReasonCode::SUCCESS, array $properties = []) { - return $this->send(['type' => Types::AUTH, 'code' => $code, 'properties' => $properties]); + return $this->send(['type' => Protocol\Types::AUTH, 'code' => $code, 'properties' => $properties]); } private function reConnect(int $delay) { - $reConnectTime = 1; $result = false; while (!$result) { if ($this->isCoroutineClientType()) { @@ -180,17 +174,16 @@ private function reConnect(int $delay) sleep($delay); } $this->client->close(); - $result = $this->client->connect($this->config['host'], $this->config['port']); - ++$reConnectTime; + $result = $this->client->connect($this->getHost(), $this->getPort()); } } public function send(array $data, bool $response = true) { - if ($this->config['protocol_level'] === 5) { - $package = ProtocolV5::pack($data); + if ($this->getConfig()->getProtocolLevel() === Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0) { + $package = Protocol\V5::pack($data); } else { - $package = Protocol::pack($data); + $package = Protocol\V3::pack($data); } $this->client->send($package); if ($response) { @@ -204,8 +197,8 @@ public function recv() { $response = $this->getResponse(); if ($response === '' || !$this->client->isConnected()) { - $this->reConnect($this->config['reconnect_delay']); - $this->connect($this->connectData['clean_session'] ?? true, $this->connectData['will'] ?? []); + $this->reConnect($this->getConfig()->getReconnectDelay()); + $this->connect($this->getConnectData('clean_session') ?? true, $this->getConnectData('will') ?? []); } elseif ($response === false) { if ($this->client->errCode === SOCKET_ECONNRESET) { $this->client->close(); @@ -218,17 +211,17 @@ public function recv() throw new RuntimeException($errMsg, $this->client->errCode); } } elseif (is_string($response) && strlen($response) > 0) { - if ($this->config['protocol_level'] === 5) { - return ProtocolV5::unpack($response); + if ($this->getConfig()->getProtocolLevel() === Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0) { + return Protocol\V5::unpack($response); } - return Protocol::unpack($response); + return Protocol\V3::unpack($response); } return true; } - protected function getResponse() + protected function getResponse(): ?string { if ($this->isCoroutineClientType()) { $response = $this->client->recv(); @@ -268,4 +261,28 @@ public static function genClientID(string $prefix = 'Simps_'): string { return uniqid($prefix); } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): int + { + return $this->port; + } + + public function getConfig(): ClientConfig + { + return $this->config; + } + + public function getConnectData(?string $key = null) + { + if ($key && isset($this->connectData[$key])) { + return $this->connectData[$key]; + } + + return $this->connectData; + } } From 959a21d98c3503d525fd1b6de044d69c282ce30e Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 16:32:04 +0800 Subject: [PATCH 07/10] Update tests --- examples/bootstrap.php | 52 ++++++++++++++++++----------------------- tests/V3/PacketTest.php | 50 ++++++++++++++++----------------------- tests/V5/PacketTest.php | 43 ++++++++++++++-------------------- 3 files changed, 61 insertions(+), 84 deletions(-) diff --git a/examples/bootstrap.php b/examples/bootstrap.php index 23fd5af..09f876e 100644 --- a/examples/bootstrap.php +++ b/examples/bootstrap.php @@ -22,6 +22,8 @@ } } +use Simps\MQTT\Config\ClientConfig; + const SSL_CERTS_DIR = __DIR__ . '/ssl_certs'; const SWOOLE_MQTT_CONFIG = [ @@ -32,40 +34,32 @@ 'read_timeout' => 0.5, ]; -function getTestConnectConfig(bool $isLocal = true, string $host = 'broker.emqx.io') -{ - if ($isLocal) { - $host = '127.0.0.1'; - } +const SIMPS_MQTT_LOCAL_HOST = '127.0.0.1'; +const SIMPS_MQTT_REMOTE_HOST = 'broker.emqx.io'; +const SIMPS_MQTT_PORT = 1883; - return [ - 'host' => $host, - 'port' => 1883, - 'user_name' => 'username', - 'password' => 'password', - 'client_id' => \Simps\MQTT\Client::genClientID(), - 'keep_alive' => 10, - ]; +function getTestConnectConfig() +{ + $config = new ClientConfig(); + return $config->setUserName('username') + ->setPassword('password') + ->setClientId(\Simps\MQTT\Client::genClientID()) + ->setKeepAlive(10) + ->setSwooleConfig(SWOOLE_MQTT_CONFIG); } -function getTestMQTT5ConnectConfig(bool $isLocal = true, string $host = 'broker.emqx.io') +function getTestMQTT5ConnectConfig() { - if ($isLocal) { - $host = '127.0.0.1'; - } - - return [ - 'host' => $host, - 'port' => 1883, - 'user_name' => 'username', - 'password' => 'password', - 'client_id' => \Simps\MQTT\Client::genClientID(), - 'keep_alive' => 10, - 'properties' => [ + $config = new ClientConfig(); + return $config->setUserName('username') + ->setPassword('password') + ->setClientId(\Simps\MQTT\Client::genClientID()) + ->setKeepAlive(10) + ->setProperties([ 'session_expiry_interval' => 60, 'receive_maximum' => 65535, 'topic_alias_maximum' => 65535, - ], - 'protocol_level' => 5, - ]; + ]) + ->setProtocolLevel(5) + ->setSwooleConfig(SWOOLE_MQTT_CONFIG); } diff --git a/tests/V3/PacketTest.php b/tests/V3/PacketTest.php index 05840f6..492b501 100644 --- a/tests/V3/PacketTest.php +++ b/tests/V3/PacketTest.php @@ -17,7 +17,7 @@ use Simps\MQTT\Client; use Simps\MQTT\Exception\ProtocolException; use Simps\MQTT\Hex\ReasonCode; -use Simps\MQTT\Types; +use Simps\MQTT\Protocol\Types; /** * @internal @@ -27,106 +27,96 @@ class PacketTest extends TestCase { private static $topic = ''; + private static $client; + public static function setUpBeforeClass() { self::$topic = 'testtopic/simps-' . rand(100, 999); + self::$client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); } public static function tearDownAfterClass() { self::$topic = ''; + self::$client = null; } public function testConnect() { - $config = getTestConnectConfig(false); - $client = new Client($config, SWOOLE_MQTT_CONFIG); - $res = $client->connect(); + $res = self::$client->connect(); $this->assertIsArray($res); $this->assertSame($res['type'], Types::CONNACK); - - return $client; } /** * @depends testConnect */ - public function testSubscribe(Client $client) + public function testSubscribe() { $topics[self::$topic] = 1; - $res = $client->subscribe($topics); + $res = self::$client->subscribe($topics); $this->assertIsArray($res); $this->assertSame($res['type'], Types::SUBACK); $this->assertSame($res['codes'][0], ReasonCode::GRANTED_QOS_1); - - return $client; } /** * @depends testSubscribe */ - public function testPublish(Client $client) + public function testPublish() { - $buffer = $client->publish(self::$topic, 'hello,simps', 1); + $buffer = self::$client->publish(self::$topic, 'hello,simps', 1); $this->assertIsArray($buffer); $this->assertSame($buffer['type'], Types::PUBACK); - - return $client; } /** * @depends testPublish */ - public function testRecv(Client $client) + public function testRecv() { - $buffer = $client->recv(); + $buffer = self::$client->recv(); $this->assertIsArray($buffer); $this->assertSame($buffer['type'], Types::PUBLISH); $this->assertSame($buffer['topic'], self::$topic); $this->assertSame($buffer['message'], 'hello,simps'); - - return $client; } /** * @depends testRecv */ - public function testPing(Client $client) + public function testPing() { - $buffer = $client->ping(); + $buffer = self::$client->ping(); $this->assertIsArray($buffer); $this->assertSame($buffer['type'], Types::PINGRESP); - - return $client; } /** * @depends testPing */ - public function testUnsubscribe(Client $client) + public function testUnsubscribe() { - $status = $client->unSubscribe([self::$topic]); + $status = self::$client->unSubscribe([self::$topic]); $this->assertIsArray($status); $this->assertSame($status['type'], Types::UNSUBACK); - - return $client; } /** * @depends testUnsubscribe */ - public function testClose(Client $client) + public function testClose() { - $status = $client->close(); + $status = self::$client->close(); $this->assertTrue($status); } public function testPublishNonTopic() { - $client = new Client(getTestMQTT5ConnectConfig(false), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); $client->connect(); $this->expectException(ProtocolException::class); - $this->expectExceptionMessage('Protocol Error, Topic cannot be empty or need to set topic_alias'); + $this->expectExceptionMessage('Protocol Error, Topic cannot be empty'); $client->publish('', 'hello,simps'); return $client; diff --git a/tests/V5/PacketTest.php b/tests/V5/PacketTest.php index 2d4862b..df62887 100644 --- a/tests/V5/PacketTest.php +++ b/tests/V5/PacketTest.php @@ -17,7 +17,7 @@ use Simps\MQTT\Client; use Simps\MQTT\Exception\ProtocolException; use Simps\MQTT\Hex\ReasonCode; -use Simps\MQTT\Types; +use Simps\MQTT\Protocol\Types; /** * @internal @@ -27,30 +27,31 @@ class PacketTest extends TestCase { private static $topic = ''; + private static $client; + public static function setUpBeforeClass() { self::$topic = 'testtopic/simps-' . rand(100, 999); + self::$client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); } public static function tearDownAfterClass() { self::$topic = ''; + self::$client = null; } public function testConnect() { - $client = new Client(getTestMQTT5ConnectConfig(false), SWOOLE_MQTT_CONFIG); - $res = $client->connect(); + $res = self::$client->connect(); $this->assertIsArray($res); $this->assertSame($res['type'], Types::CONNACK); - - return $client; } /** * @depends testConnect */ - public function testSubscribe(Client $client) + public function testSubscribe() { $topics = [ self::$topic . '/get' => [ @@ -66,14 +67,12 @@ public function testSubscribe(Client $client) 'retain_handling' => 2, ], ]; - $res = $client->subscribe($topics); + $res = self::$client->subscribe($topics); $this->assertIsArray($res); $this->assertSame($res['type'], Types::SUBACK); $this->assertIsArray($res['codes']); $this->assertSame($res['codes'][0], ReasonCode::GRANTED_QOS_1); $this->assertSame($res['codes'][1], ReasonCode::GRANTED_QOS_2); - - return $client; } /** @@ -82,7 +81,7 @@ public function testSubscribe(Client $client) public function testPublish() { go(function () { - $client = new Client(getTestMQTT5ConnectConfig(false), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); $res = $client->connect(); $this->assertIsArray($res); $buffer = $client->publish(self::$topic . '/get', 'hello,simps', 1); @@ -95,54 +94,48 @@ public function testPublish() /** * @depends testSubscribe */ - public function testRecv(Client $client) + public function testRecv() { - $buffer = $client->recv(); + $buffer = self::$client->recv(); $this->assertIsArray($buffer); $this->assertSame($buffer['type'], Types::PUBLISH); $this->assertSame($buffer['topic'], self::$topic . '/get'); $this->assertSame($buffer['message'], 'hello,simps'); - - return $client; } /** * @depends testRecv */ - public function testPing(Client $client) + public function testPing() { - $buffer = $client->ping(); + $buffer = self::$client->ping(); $this->assertIsArray($buffer); $this->assertSame($buffer['type'], Types::PINGRESP); - - return $client; } /** * @depends testPing */ - public function testUnsubscribe(Client $client) + public function testUnsubscribe() { - $status = $client->unSubscribe([self::$topic . '/get']); + $status = self::$client->unSubscribe([self::$topic . '/get']); $this->assertIsArray($status); $this->assertSame($status['type'], Types::UNSUBACK); $this->assertSame(ReasonCode::getReasonPhrase($status['code']), 'Success'); - - return $client; } /** * @depends testUnsubscribe */ - public function testClose(Client $client) + public function testClose() { - $status = $client->close(); + $status = self::$client->close(); $this->assertTrue($status); } public function testPublishNonTopic() { - $client = new Client(getTestMQTT5ConnectConfig(false), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); $client->connect(); $this->expectException(ProtocolException::class); $this->expectExceptionMessage('Protocol Error, Topic cannot be empty or need to set topic_alias'); From b3e5778a62682532167926ed24993dcb4c2121b2 Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 17:08:45 +0800 Subject: [PATCH 08/10] Remove getResponse return value type --- src/Client.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Client.php b/src/Client.php index b4a4ef5..69ec72a 100644 --- a/src/Client.php +++ b/src/Client.php @@ -221,7 +221,7 @@ public function recv() return true; } - protected function getResponse(): ?string + protected function getResponse() { if ($this->isCoroutineClientType()) { $response = $this->client->recv(); From 08531ac350fa9225776b67ee7c7627752836031d Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 17:23:38 +0800 Subject: [PATCH 09/10] Update examples code --- examples/publish.php | 2 +- examples/publish_fpm.php | 2 +- examples/server.php | 18 +++++++++--------- examples/ssl_ca.php | 22 +++++++++++----------- examples/ssl_ca_client.php | 22 +++++++++++----------- examples/subscribe.php | 5 ++--- examples/unsubscribe.php | 2 +- examples/v5/publish.php | 2 +- examples/v5/publish_fpm.php | 2 +- examples/v5/server.php | 18 +++++++++--------- examples/v5/subscribe.php | 5 ++--- examples/v5/unsubscribe.php | 2 +- 12 files changed, 50 insertions(+), 52 deletions(-) diff --git a/examples/publish.php b/examples/publish.php index e36d11f..efbcfe1 100644 --- a/examples/publish.php +++ b/examples/publish.php @@ -15,7 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $client = new Client(getTestConnectConfig(), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); while (!$client->connect()) { Coroutine::sleep(3); $client->connect(); diff --git a/examples/publish_fpm.php b/examples/publish_fpm.php index eec5d94..dabafdb 100644 --- a/examples/publish_fpm.php +++ b/examples/publish_fpm.php @@ -16,7 +16,7 @@ /** * Support publish in fpm, need to specify clientType as Client::SYNC_CLIENT_TYPE */ -$client = new Client(getTestConnectConfig(), SWOOLE_MQTT_CONFIG, SWOOLE_SOCK_TCP, Client::SYNC_CLIENT_TYPE); +$client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestConnectConfig(), Client::SYNC_CLIENT_TYPE); while (!$client->connect()) { sleep(3); diff --git a/examples/server.php b/examples/server.php index 853a38f..693d58e 100644 --- a/examples/server.php +++ b/examples/server.php @@ -11,9 +11,9 @@ include __DIR__ . '/bootstrap.php'; -use Simps\MQTT\Protocol; use Simps\MQTT\Tools\Common; -use Simps\MQTT\Types; +use Simps\MQTT\Protocol\Types; +use Simps\MQTT\Protocol\V3; $server = new Swoole\Server('127.0.0.1', 1883, SWOOLE_BASE); @@ -33,7 +33,7 @@ try { // debug // Common::printf($data); - $data = Protocol::unpack($data); + $data = V3::unpack($data); if (is_array($data) && isset($data['type'])) { switch ($data['type']) { case Types::CONNECT: @@ -48,7 +48,7 @@ $server->send( $fd, - Protocol::pack( + V3::pack( [ 'type' => Types::CONNACK, 'code' => 0, @@ -58,7 +58,7 @@ ); break; case Types::PINGREQ: - $server->send($fd, Protocol::pack(['type' => Types::PINGRESP])); + $server->send($fd, V3::pack(['type' => Types::PINGRESP])); break; case Types::DISCONNECT: if ($server->exist($fd)) { @@ -71,7 +71,7 @@ if ($sub_fd != $fd) { $server->send( $sub_fd, - Protocol::pack( + V3::pack( [ 'type' => $data['type'], 'topic' => $data['topic'], @@ -89,7 +89,7 @@ if ($data['qos'] === 1) { $server->send( $fd, - Protocol::pack( + V3::pack( [ 'type' => Types::PUBACK, 'message_id' => $data['message_id'] ?? '', @@ -110,7 +110,7 @@ } $server->send( $fd, - Protocol::pack( + V3::pack( [ 'type' => Types::SUBACK, 'message_id' => $data['message_id'] ?? '', @@ -122,7 +122,7 @@ case Types::UNSUBSCRIBE: $server->send( $fd, - Protocol::pack( + V3::pack( [ 'type' => Types::UNSUBACK, 'message_id' => $data['message_id'] ?? '', diff --git a/examples/ssl_ca.php b/examples/ssl_ca.php index e5b7a42..f636e77 100644 --- a/examples/ssl_ca.php +++ b/examples/ssl_ca.php @@ -13,17 +13,9 @@ use Simps\MQTT\Client; use Swoole\Coroutine; +use Simps\MQTT\Config\ClientConfig; Coroutine\run(function () { - $config = [ - 'host' => 'test.mosquitto.org', - 'port' => 8883, - 'user_name' => '', - 'password' => '', - 'client_id' => Client::genClientID(), - 'keep_alive' => 20, - ]; - $swooleConfig = [ 'open_mqtt_protocol' => true, 'package_max_length' => 2 * 1024 * 1024, @@ -32,7 +24,15 @@ 'ssl_verify_peer' => true, ]; - $client = new Client($config, $swooleConfig, SWOOLE_SOCK_TCP | SWOOLE_SSL); + $config = new ClientConfig(); + $config->setClientId(Client::genClientID()) + ->setKeepAlive(20) + ->setUserName('') + ->setPassword('') + ->setSwooleConfig($swooleConfig) + ->setSockType(SWOOLE_SOCK_TCP | SWOOLE_SSL); + + $client = new Client('test.mosquitto.org', 8883, $config); while (!$data = $client->connect()) { Coroutine::sleep(3); @@ -47,7 +47,7 @@ if ($buffer && $buffer !== true) { $timeSincePing = time(); } - if (isset($config['keep_alive']) && $timeSincePing < (time() - $config['keep_alive'])) { + if ($timeSincePing < (time() - $config->getKeepAlive())) { $buffer = $client->ping(); if ($buffer) { echo 'send ping success' . PHP_EOL; diff --git a/examples/ssl_ca_client.php b/examples/ssl_ca_client.php index ef10897..21cd95e 100644 --- a/examples/ssl_ca_client.php +++ b/examples/ssl_ca_client.php @@ -13,17 +13,9 @@ use Simps\MQTT\Client; use Swoole\Coroutine; +use Simps\MQTT\Config\ClientConfig; Coroutine\run(function () { - $config = [ - 'host' => 'test.mosquitto.org', - 'port' => 8884, - 'user_name' => '', - 'password' => '', - 'client_id' => Client::genClientID(), - 'keep_alive' => 20, - ]; - $swooleConfig = [ 'open_mqtt_protocol' => true, 'package_max_length' => 2 * 1024 * 1024, @@ -34,7 +26,15 @@ 'ssl_cert_file' => SSL_CERTS_DIR . '/client.crt', // Please go to https://test.mosquitto.org/ssl to generate. ]; - $client = new Client($config, $swooleConfig, SWOOLE_SOCK_TCP | SWOOLE_SSL); + $config = new ClientConfig(); + $config->setClientId(Client::genClientID()) + ->setKeepAlive(20) + ->setUserName('') + ->setPassword('') + ->setSwooleConfig($swooleConfig) + ->setSockType(SWOOLE_SOCK_TCP | SWOOLE_SSL); + + $client = new Client('test.mosquitto.org', 8884, $config); while (!$client->connect()) { Coroutine::sleep(3); $client->connect(); @@ -48,7 +48,7 @@ if ($buffer && $buffer !== true) { $timeSincePing = time(); } - if (isset($config['keep_alive']) && $timeSincePing < (time() - $config['keep_alive'])) { + if ($timeSincePing < (time() - $config->getKeepAlive())) { $buffer = $client->ping(); if ($buffer) { echo 'send ping success' . PHP_EOL; diff --git a/examples/subscribe.php b/examples/subscribe.php index 55c2735..2a3d89a 100644 --- a/examples/subscribe.php +++ b/examples/subscribe.php @@ -15,8 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $config = getTestConnectConfig(); - $client = new Client($config, SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); $will = [ 'topic' => 'simps-mqtt/user001/update', 'qos' => 1, @@ -37,7 +36,7 @@ if ($buffer && $buffer !== true) { $timeSincePing = time(); } - if (isset($config['keep_alive']) && $timeSincePing < (time() - $config['keep_alive'])) { + if ($timeSincePing < (time() - $client->getConfig()->getKeepAlive())) { $buffer = $client->ping(); if ($buffer) { echo 'send ping success' . PHP_EOL; diff --git a/examples/unsubscribe.php b/examples/unsubscribe.php index 34bd6a9..8c35e01 100644 --- a/examples/unsubscribe.php +++ b/examples/unsubscribe.php @@ -15,7 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $client = new Client(getTestConnectConfig(), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_REMOTE_HOST, SIMPS_MQTT_PORT, getTestConnectConfig()); while (!$client->connect()) { Coroutine::sleep(3); $client->connect(); diff --git a/examples/v5/publish.php b/examples/v5/publish.php index d3d5ee1..a5acf15 100644 --- a/examples/v5/publish.php +++ b/examples/v5/publish.php @@ -15,7 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $client = new Client(getTestMQTT5ConnectConfig(), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); while (!$client->connect()) { Coroutine::sleep(3); $client->connect(); diff --git a/examples/v5/publish_fpm.php b/examples/v5/publish_fpm.php index 97eb341..87a33c8 100644 --- a/examples/v5/publish_fpm.php +++ b/examples/v5/publish_fpm.php @@ -16,7 +16,7 @@ /** * Support publish in fpm, need to specify clientType as Client::SYNC_CLIENT_TYPE */ -$client = new Client(getTestMQTT5ConnectConfig(), SWOOLE_MQTT_CONFIG, SWOOLE_SOCK_TCP, Client::SYNC_CLIENT_TYPE); +$client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig(), Client::SYNC_CLIENT_TYPE); while (!$client->connect()) { sleep(3); diff --git a/examples/v5/server.php b/examples/v5/server.php index bede012..7ca0525 100644 --- a/examples/v5/server.php +++ b/examples/v5/server.php @@ -11,9 +11,9 @@ include __DIR__ . '/../bootstrap.php'; -use Simps\MQTT\ProtocolV5; +use Simps\MQTT\Protocol\V5; use Simps\MQTT\Tools\Common; -use Simps\MQTT\Types; +use Simps\MQTT\Protocol\Types; $server = new Swoole\Server('127.0.0.1', 1883, SWOOLE_BASE); @@ -33,7 +33,7 @@ try { // debug // Common::printf($data); - $data = ProtocolV5::unpack($data); + $data = V5::unpack($data); if (is_array($data) && isset($data['type'])) { switch ($data['type']) { case Types::CONNECT: @@ -48,7 +48,7 @@ $server->send( $fd, - ProtocolV5::pack( + V5::pack( [ 'type' => Types::CONNACK, 'code' => 0, @@ -66,7 +66,7 @@ ); break; case Types::PINGREQ: - $server->send($fd, ProtocolV5::pack(['type' => Types::PINGRESP])); + $server->send($fd, V5::pack(['type' => Types::PINGRESP])); break; case Types::DISCONNECT: if ($server->exist($fd)) { @@ -79,7 +79,7 @@ if ($sub_fd != $fd) { $server->send( $sub_fd, - ProtocolV5::pack( + V5::pack( [ 'type' => $data['type'], 'topic' => $data['topic'], @@ -97,7 +97,7 @@ if ($data['qos'] === 1) { $server->send( $fd, - ProtocolV5::pack( + V5::pack( [ 'type' => Types::PUBACK, 'message_id' => $data['message_id'] ?? '', @@ -119,7 +119,7 @@ } $server->send( $fd, - ProtocolV5::pack( + V5::pack( [ 'type' => Types::SUBACK, 'message_id' => $data['message_id'] ?? '', @@ -131,7 +131,7 @@ case Types::UNSUBSCRIBE: $server->send( $fd, - ProtocolV5::pack( + V5::pack( [ 'type' => Types::UNSUBACK, 'message_id' => $data['message_id'] ?? '', diff --git a/examples/v5/subscribe.php b/examples/v5/subscribe.php index a6aefc4..3146e33 100644 --- a/examples/v5/subscribe.php +++ b/examples/v5/subscribe.php @@ -15,8 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $config = getTestMQTT5ConnectConfig(); - $client = new Client($config, SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); $will = [ 'topic' => 'simps-mqtt/user001/update', 'qos' => 1, @@ -56,7 +55,7 @@ if ($buffer && $buffer !== true) { $timeSincePing = time(); } - if (isset($config['keep_alive']) && $timeSincePing < (time() - $config['keep_alive'])) { + if ($timeSincePing < (time() - $client->getConfig()->getKeepAlive())) { $buffer = $client->ping(); if ($buffer) { echo 'send ping success' . PHP_EOL; diff --git a/examples/v5/unsubscribe.php b/examples/v5/unsubscribe.php index 0ad3278..275d4ed 100644 --- a/examples/v5/unsubscribe.php +++ b/examples/v5/unsubscribe.php @@ -15,7 +15,7 @@ use Swoole\Coroutine; Coroutine\run(function () { - $client = new Client(getTestMQTT5ConnectConfig(), SWOOLE_MQTT_CONFIG); + $client = new Client(SIMPS_MQTT_LOCAL_HOST, SIMPS_MQTT_PORT, getTestMQTT5ConnectConfig()); while (!$client->connect()) { Coroutine::sleep(3); $client->connect(); From 95575e26791175a0c83a63a4533611e8f28fd52e Mon Sep 17 00:00:00 2001 From: sy-records <52o@qq52o.cn> Date: Mon, 18 Jan 2021 18:33:22 +0800 Subject: [PATCH 10/10] Update docs --- docs/en/_sidebar.md | 3 ++ docs/en/client.md | 43 +++++++++--------- docs/en/protocol.md | 18 ++++---- docs/en/upgrade/1.2.md | 93 +++++++++++++++++++++++++++++++++++++++ docs/zh-cn/_sidebar.md | 3 ++ docs/zh-cn/client.md | 41 +++++++++-------- docs/zh-cn/protocol.md | 18 ++++---- docs/zh-cn/upgrade/1.2.md | 93 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 255 insertions(+), 57 deletions(-) create mode 100644 docs/en/upgrade/1.2.md create mode 100644 docs/zh-cn/upgrade/1.2.md diff --git a/docs/en/_sidebar.md b/docs/en/_sidebar.md index eb29008..e4ecc1e 100644 --- a/docs/en/_sidebar.md +++ b/docs/en/_sidebar.md @@ -3,3 +3,6 @@ * MQTT Protocol Analysis * [Protocol API](en/protocol) + +* Upgrade Guide + * [1.2 Upgrade Guide](en/upgrade/1.2.md) \ No newline at end of file diff --git a/docs/en/client.md b/docs/en/client.md index b760464..2a6cd1f 100644 --- a/docs/en/client.md +++ b/docs/en/client.md @@ -5,38 +5,41 @@ Create a MQTT client instance ```php -Simps\MQTT\Client::__construct(array $config, array $swConfig = [], int $type = SWOOLE_SOCK_TCP, int $clientType = Client::COROUTINE_CLIENT_TYPE) +Simps\MQTT\Client::__construct(string $host, int $port, ?ClientConfig $config = null, int $clientType = Client::COROUTINE_CLIENT_TYPE) ``` -* `array $config` +* `string $host` -An array of client options, you can set the following options: +Broker's host + +* `int $port` + +Broker's port + +* `ClientConfig $config` + +ClientConfig object. + +Example. ```php $config = [ - 'host' => '127.0.0.1', - 'port' => 1883, - 'user_name' => '', - 'password' => '', - 'client_id' => '', - 'keep_alive' => 10, - 'protocol_name' => 'MQTT', // or MQIsdp - 'protocol_level' => 4, // or 3, 5 + 'userName' => '', // 用户名 + 'password' => '', // 密码 + 'clientId' => '', // 客户端id + 'keepAlive' => 10, // 默认0秒,设置成0代表禁用 + 'protocolName' => 'MQTT', // or MQIsdp + 'protocolLevel' => 4, // or 3, 5 'properties' => [], // optional in MQTT5 - 'reconnect_delay' => 3, + 'reconnectDelay' => 3, + 'swooleConfig' => [] ]; +$configObj = new Simps\MQTT\Config\ClientConfig($config); +$client = new Simps\MQTT\Client('127.0.0.1', 1883, $configObj); ``` !> The Client will use the corresponding protocol resolution according to the `protocol_level` set. -* `array $swConfig` - -To set the configuration of `Swoole\Coroutine\Client`, please see Swoole document: [set()](https://www.swoole.co.uk/docs/modules/swoole-coroutine-client-set) - -* `int $type` - -Set `sockType`, such as: `SWOOLE_TCP`, `SWOOLE_TCP | SWOOLE_SSL` - * `int $clientType` Set the client type, use a Coroutine Client or a Sync Client, the default is Coroutine Client. diff --git a/docs/en/protocol.md b/docs/en/protocol.md index 28f3399..a6a56ab 100644 --- a/docs/en/protocol.md +++ b/docs/en/protocol.md @@ -5,17 +5,17 @@ Use `pack` and `unpack` to package and parse according to the MQTT protocol. ## MQTT 3.1.x ```php -Simps\MQTT\Protocol::pack(array $array) +Simps\MQTT\Protocol\V3::pack(array $array) -Simps\MQTT\Protocol::unpack(string $data) +Simps\MQTT\Protocol\V3::unpack(string $data) ``` ## MQTT 5.0 ```php -Simps\MQTT\ProtocolV5::pack(array $array) +Simps\MQTT\Protocol\V5::pack(array $array) -Simps\MQTT\ProtocolV5::unpack(string $data) +Simps\MQTT\Protocol\V5::unpack(string $data) ``` ## Constants @@ -23,12 +23,12 @@ Simps\MQTT\ProtocolV5::unpack(string $data) Constants for MQTT protocol levels and names ```php -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; // 3.1 -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1; // 3.1.1 -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0; // 5.0 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; // 3.1 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1; // 3.1.1 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0; // 5.0 -Simps\MQTT\ProtocolInterface::MQISDP_PROTOCOL_NAME; // MQIsdp -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_NAME; // MQTT +Simps\MQTT\Protocol\ProtocolInterface::MQISDP_PROTOCOL_NAME; // MQIsdp +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_NAME; // MQTT ``` ## ReasonCode diff --git a/docs/en/upgrade/1.2.md b/docs/en/upgrade/1.2.md new file mode 100644 index 0000000..77bcba0 --- /dev/null +++ b/docs/en/upgrade/1.2.md @@ -0,0 +1,93 @@ +# 1.2 Upgrade Guide + +Version 1.2 mainly changes the `__construct` parameters of the Client and the namespace of the Protocol. + +## Protocol + +A new layer of `Protocol` has been added, using `V3` and `V5` to differentiate between MQTT protocol levels. + +Also moved `Simps\MQTT\Types` to `Protocol` as well, changing it to `Simps\MQTT\Protocol\Types`. + +### 1.1 + +```php +Simps\MQTT\Protocol::pack(array $array) +Simps\MQTT\ProtocolV5::pack(array $array) +Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; + +Simps\MQTT\Types::CONNECT; +``` + +### 1.2 + +```php +Simps\MQTT\Protocol\V3::pack(array $array) +Simps\MQTT\Protocol\V5::pack(array $array) +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; + +Simps\MQTT\Protocol\Types::CONNECT; +``` + +## Client + +Client was previously passing array parameters directly, now it is an object. + +### 1.1 + +```php +use Simps\MQTT\Client; + +$config = [ + 'host' => '127.0.0.1', + 'port' => 1883, + 'user_name' => '', + 'password' => '', + 'client_id' => Client::genClientID(), + 'keep_alive' => 10, +]; +$swooleConfig = [ + 'open_mqtt_protocol' => true, + 'package_max_length' => 2 * 1024 * 1024, + 'connect_timeout' => 1.0, + 'write_timeout' => 3.0, + 'read_timeout' => 0.5, +]; +$client = new Client($config, $swooleConfig); +``` + +### 1.2 + +```php +use Simps\MQTT\Client; +use Simps\MQTT\Config\ClientConfig; + +$config = new ClientConfig(); +$config->setUserName('') + ->setPassword('') + ->setClientId(Client::genClientID()) + ->setKeepAlive(10); + +$swooleConfig = [ + 'open_mqtt_protocol' => true, + 'package_max_length' => 2 * 1024 * 1024, + 'connect_timeout' => 1.0, + 'write_timeout' => 3.0, + 'read_timeout' => 0.5, +]; +$config->setSwooleConfig($swooleConfig); +$client = new Client('127.0.0.1', 1883, $config); + +// You can also set it up like this +$config = new ClientConfig([ + 'userName' => '', + 'password' => '', + 'clientId' => '', + 'keepAlive' => 10, + 'protocolName' => 'MQTT', + 'protocolLevel' => 4, + 'properties' => [], + 'reconnectDelay' => 3, + 'swooleConfig' => [] +]); +$client = new Client('127.0.0.1', 1883, $config); +``` diff --git a/docs/zh-cn/_sidebar.md b/docs/zh-cn/_sidebar.md index e4502da..aca75e8 100644 --- a/docs/zh-cn/_sidebar.md +++ b/docs/zh-cn/_sidebar.md @@ -3,3 +3,6 @@ * MQTT 协议解析 * [Protocol API](zh-cn/protocol) + +* 版本升级指南 + * [1.2 升级指南](zh-cn/upgrade/1.2.md) \ No newline at end of file diff --git a/docs/zh-cn/client.md b/docs/zh-cn/client.md index 58c3965..3f27114 100644 --- a/docs/zh-cn/client.md +++ b/docs/zh-cn/client.md @@ -5,38 +5,41 @@ 创建一个MQTT客户端实例 ```php -Simps\MQTT\Client::__construct(array $config, array $swConfig = [], int $type = SWOOLE_SOCK_TCP, int $clientType = Client::COROUTINE_CLIENT_TYPE) +Simps\MQTT\Client::__construct(string $host, int $port, ?ClientConfig $config = null, int $clientType = Client::COROUTINE_CLIENT_TYPE) ``` -* 参数`array $config` +* 参数`string $host` -客户端选项数组,可以设置以下选项: +Broker 的 IP 地址 + +* 参数`int $port` + +Broker 的端口 + +* 参数`ClientConfig $config` + +客户端配置对象。 + +示例: ```php $config = [ - 'host' => '127.0.0.1', // MQTT服务端IP - 'port' => 1883, // MQTT服务端端口 - 'user_name' => '', // 用户名 + 'userName' => '', // 用户名 'password' => '', // 密码 - 'client_id' => '', // 客户端id - 'keep_alive' => 10, // 默认0秒,设置成0代表禁用 - 'protocol_name' => 'MQTT', // 协议名,默认为MQTT(3.1.1版本),也可为MQIsdp(3.1版本) - 'protocol_level' => 4, // 协议等级,MQTT3.1.1版本为4,5.0版本为5,MQIsdp为3 + 'clientId' => '', // 客户端id + 'keepAlive' => 10, // 默认0秒,设置成0代表禁用 + 'protocolName' => 'MQTT', // 协议名,默认为MQTT(3.1.1版本),也可为MQIsdp(3.1版本) + 'protocolLevel' => 4, // 协议等级,MQTT3.1.1版本为4,5.0版本为5,MQIsdp为3 'properties' => [], // MQTT5 中所需要的属性 - 'reconnect_delay' => 3, // 重连时的延迟时间 + 'reconnectDelay' => 3, // 重连时的延迟时间 + 'swooleConfig' => [] ]; +$configObj = new Simps\MQTT\Config\ClientConfig($config); +$client = new Simps\MQTT\Client('127.0.0.1', 1883, $configObj); ``` !> Client 会根据设置的`protocol_level`来使用对应的协议解析 -* 参数`array $swConfig` - -设置`Swoole\Coroutine\Client | Swoole\Client`的配置,请参考Swoole文档:[set()](https://wiki.swoole.com/#/coroutine_client/client?id=set) - -* 参数`int $type` - -设置`sockType`,如:`SWOOLE_TCP`、`SWOOLE_TCP | SWOOLE_SSL` - * 参数`int $clientType` 设置客户端类型,使用协程 Client 还是同步阻塞 Client。默认为协程 Client。 diff --git a/docs/zh-cn/protocol.md b/docs/zh-cn/protocol.md index 4f93b7a..1936b08 100644 --- a/docs/zh-cn/protocol.md +++ b/docs/zh-cn/protocol.md @@ -5,17 +5,17 @@ ## MQTT 3.1.x ```php -Simps\MQTT\Protocol::pack(array $array) +Simps\MQTT\Protocol\V3::pack(array $array) -Simps\MQTT\Protocol::unpack(string $data) +Simps\MQTT\Protocol\V3::unpack(string $data) ``` ## MQTT 5.0 ```php -Simps\MQTT\ProtocolV5::pack(array $array) +Simps\MQTT\Protocol\V5::pack(array $array) -Simps\MQTT\ProtocolV5::unpack(string $data) +Simps\MQTT\Protocol\V5::unpack(string $data) ``` ## Constants @@ -23,12 +23,12 @@ Simps\MQTT\ProtocolV5::unpack(string $data) MQTT 协议等级和名称的常量 ```php -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; // 3.1 -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1; // 3.1.1 -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0; // 5.0 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; // 3.1 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1_1; // 3.1.1 +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_5_0; // 5.0 -Simps\MQTT\ProtocolInterface::MQISDP_PROTOCOL_NAME; // MQIsdp -Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_NAME; // MQTT +Simps\MQTT\Protocol\ProtocolInterface::MQISDP_PROTOCOL_NAME; // MQIsdp +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_NAME; // MQTT ``` ## ReasonCode diff --git a/docs/zh-cn/upgrade/1.2.md b/docs/zh-cn/upgrade/1.2.md new file mode 100644 index 0000000..e8bc887 --- /dev/null +++ b/docs/zh-cn/upgrade/1.2.md @@ -0,0 +1,93 @@ +# 1.2 升级指南 + +1.2 版本主要修改了 Client 的构造函数参数和 Protocol 的命名空间。 + +## Protocol + +新增一层`Protocol`,使用`V3`和`V5`来区分 MQTT 协议等级。 + +同时将`Simps\MQTT\Types`也移动到了`Protocol`下,修改为`Simps\MQTT\Protocol\Types`。 + +### 1.1 + +```php +Simps\MQTT\Protocol::pack(array $array) +Simps\MQTT\ProtocolV5::pack(array $array) +Simps\MQTT\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; + +Simps\MQTT\Types::CONNECT; +``` + +### 1.2 + +```php +Simps\MQTT\Protocol\V3::pack(array $array) +Simps\MQTT\Protocol\V5::pack(array $array) +Simps\MQTT\Protocol\ProtocolInterface::MQTT_PROTOCOL_LEVEL_3_1; + +Simps\MQTT\Protocol\Types::CONNECT; +``` + +## Client + +Client 之前是直接传递数组参数的,现在改为对象的方式。 + +### 1.1 + +```php +use Simps\MQTT\Client; + +$config = [ + 'host' => '127.0.0.1', + 'port' => 1883, + 'user_name' => '', + 'password' => '', + 'client_id' => Client::genClientID(), + 'keep_alive' => 10, +]; +$swooleConfig = [ + 'open_mqtt_protocol' => true, + 'package_max_length' => 2 * 1024 * 1024, + 'connect_timeout' => 1.0, + 'write_timeout' => 3.0, + 'read_timeout' => 0.5, +]; +$client = new Client($config, $swooleConfig); +``` + +### 1.2 + +```php +use Simps\MQTT\Client; +use Simps\MQTT\Config\ClientConfig; + +$config = new ClientConfig(); +$config->setUserName('') + ->setPassword('') + ->setClientId(Client::genClientID()) + ->setKeepAlive(10); + +$swooleConfig = [ + 'open_mqtt_protocol' => true, + 'package_max_length' => 2 * 1024 * 1024, + 'connect_timeout' => 1.0, + 'write_timeout' => 3.0, + 'read_timeout' => 0.5, +]; +$config->setSwooleConfig($swooleConfig); +$client = new Client('127.0.0.1', 1883, $config); + +// 也可以这样设置 +$config = new ClientConfig([ + 'userName' => '', + 'password' => '', + 'clientId' => '', + 'keepAlive' => 10, + 'protocolName' => 'MQTT', + 'protocolLevel' => 4, + 'properties' => [], + 'reconnectDelay' => 3, + 'swooleConfig' => [] +]); +$client = new Client('127.0.0.1', 1883, $config); +```