关于mqtt:php调用阿里云mqtt

5次阅读

共计 4615 个字符,预计需要花费 12 分钟才能阅读完成。

依赖

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();
    }

}
正文完
 0