1

依赖

composer require php-mqtt/client v1.1.0

使用

$mqtt - new MqttService([
  'acessKeyID' => 'XXXX',//账号的 AccessKey,在阿里云控制台查看
  'accessKeySecret' => 'XXXX', //账号的的 SecretKey,在阿里云控制台查看
  'endpoint' => 'XXXX.mqtt.aliyuncs.com',// 设置当前用户的接入点域名,接入点获取方法请参考接入准备章节文档,先在控制台创建实例
  'instanceId' => 'XXXX', //实例 ID,购买后从控制台获取
  'groupId' => 'GID_XXXX',//MQTT GroupID,创建实例后从 MQTT 控制台创建
  'topic'=>'XXXX', //需要操作的 Topic,第一级父级 topic 需要在控制台申请
  'deviceId' => 'XXXX',//客户端唯一表示
])
# 获取客户端参数
$mqtt->getClientInfo($deviceId)
# p2p 发送消息
$mqtt->p2pPublish(deviceId, '我是测试');
# 自定义发送消息内容 $clientId 生成规则:$topic + $groupId + '@@@' + $deviceId 例如:'topic/p2p/GID_XXXX@@@00001'
$mqtt->publish($clientId, '我是测试');

MqttService二次封装


class MqttService
{
    /**
     * 此处填写阿里云帐号 AccessKey ID
     * @var
     */
    protected $acessKeyID;
    /**
     * 此处填写阿里云帐号 AccessKey Secret
     * @var
     */
    protected $accessKeySecret;

    /**
     * 接入点地址,购买实例后从控制台获取
     * @var
     */
    protected $endpoint;

    /**
     * @var int
     * 标准协议端口
     */
    protected $port = 1883;
    /**
     * @var int
     * SSL 端口
     */
    protected $sslPort = 8883;
    /**
     * @var int
     * WebSocket 端口
     */
    protected $webSocketPort = 80;

    /**
     * @var int
     * WebSocket SSL/TLS 端口
     */
    protected $webSocketSslPort = 443;

    /**
     * @var int
     * Flash 端口
     */
    protected $flashPort = 843;

    /**
     * 实例 ID,购买后从控制台获取
     * @var
     */
    protected $instanceId;
    /**
     * MQTT 客户端ID 前缀, GroupID,需要在 MQTT 控制台申请
     * @var
     */
    protected $groupId;
    /**
     * @var
     * 需要操作的 Topic,第一级父级 topic 需要在控制台申请
     */
    protected $topic;

    /**
     * MQTT 客户端ID 后缀,DeviceId,业务方自由指定,需要保证全局唯一,禁止 2 个客户端连接使用同一个 ID
     * @var
     */
    protected $deviceId;
    /**
     * @var
     */
    protected $clientId;

    /**
     * @var bool
     * 如果使用 HTTPS 加密则配置为 true
     */
    protected $useTLS = false;
    /**
     * @var int
     */
    protected $connectTimeout = 5;
    /**
     * @var
     */
    protected $mqtt;

    /**
     * Application constructor.
     * @param array $config
     * @throws \PhpMqtt\Client\Exceptions\ConfigurationInvalidException
     * @throws \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException
     * @throws \PhpMqtt\Client\Exceptions\ProtocolNotSupportedException
     */

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        // connect
        $this->mqtt = $this->setMqttClient();
        //close
        register_shutdown_function(function () {
            $this->disconnect();
        });
    }

    /**
     * @param $toDeviceId
     * @param $message
     * @return mixed
     * @throws \PhpMqtt\Client\Exceptions\ConfigurationInvalidException
     * @throws \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException
     * @throws \PhpMqtt\Client\Exceptions\DataTransferException
     * @throws \PhpMqtt\Client\Exceptions\ProtocolNotSupportedException
     * @throws \PhpMqtt\Client\Exceptions\RepositoryException
     */
    public function p2pPublish(string $toDeviceId, string $message)
    {
        $p2p_topic = $this->topic . '/p2p/' . $this->clientId($toDeviceId);
        return $this->publish($p2p_topic, $message);
    }

    /**
     * @param string $topic
     * @param string $message
     * @param int $qualityOfService
     * @param bool $retain
     * @return mixed
     * @throws \PhpMqtt\Client\Exceptions\ConfigurationInvalidException
     * @throws \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException
     * @throws \PhpMqtt\Client\Exceptions\DataTransferException
     * @throws \PhpMqtt\Client\Exceptions\ProtocolNotSupportedException
     * @throws \PhpMqtt\Client\Exceptions\RepositoryException
     */
    public function publish(string $topic, string $message, int $qualityOfService = 0, bool $retain = false)
    {
        $this->mqttClient()->publish($topic, $message, $qualityOfService, $retain);
        return $this->deviceId;
    }
    /**
     * @return array
     */
    public function getClientInfo($deviceId)
    {
        return [
            'endpoint'      => $this->endpoint,
            'useTLS'        => $this->useTLS,
            'port'          => $this->port(),
            'webSocketPort' => $this->webSocketPort(),
            'username'      => $this->username(),
            'password'      => $this->password(),
            'clientId'      => $this->clientId($deviceId),
        ];
    }

    /**
     * @return MqttClient
     * @throws \PhpMqtt\Client\Exceptions\ConfigurationInvalidException
     * @throws \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException
     * @throws \PhpMqtt\Client\Exceptions\ProtocolNotSupportedException
     */
    protected function setMqttClient()
    {
        $this->clientId     = $this->clientId($this->deviceId);
        $mqtt               = new MqttClient($this->endpoint, $this->port(), $this->clientId);
        $connectionSettings = (new ConnectionSettings())
            ->setUsername($this->username())
            ->setPassword($this->password())
            ->setUseTls($this->useTLS)
            ->setConnectTimeout($this->connectTimeout);
        $mqtt->connect($connectionSettings, true);
        return $mqtt;
    }

    /**
     * @return MqttClient
     */
    public function mqttClient(): MqttClient
    {
        return $this->mqtt;
    }

    /**
     * @param $deviceId
     * @return string
     */
    public function clientId($deviceId)
    {
        return $this->groupId . '@@@' . $deviceId;
    }

    /**
     * @return int
     */
    protected function port()
    {
        return $this->useTLS ? $this->sslPort : $this->port;
    }

    /**
     * @return int
     */
    protected function webSocketPort()
    {
        return $this->useTLS ? $this->webSocketSslPort : $this->webSocketPort;
    }

    /**
     * @return string
     */
    protected function username()
    {
        return 'Signature|' . $this->acessKeyID . '|' . $this->instanceId;
    }

    /**
     * @return string
     */
    protected function password()
    {
        $hash = hash_hmac('sha1', $this->clientId, $this->acessKeyID, true);
        return base64_encode($hash);
    }

    /**
     * @throws \PhpMqtt\Client\Exceptions\DataTransferException
     */
    protected function disconnect()
    {
        $this->mqtt->disconnect();
    }

}

qmister
88 声望1 粉丝

引用和评论

0 条评论