PHP
本文主要介绍如何在 PHP 项目中使用 php-mqtt/client 客户端库 ,实现 SX-IOT设备与 MQTT 服务器的连接、订阅、收发消息等功能。
前提条件
安装依赖包
sudo apt install php composer -y
连接使用
连接设置
本文将使用自定义的接入认证方式,服务器接入信息如下: -Broker: mqtt.geek-smart.cn -TCP Port: 1883 -WebSocket Port: 8083
导入依赖包
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
定义连接地址、认证信息以及消息发布主题
设置 MQTT Broker 连接地址,端口以及 topic。
$server = "mqtt.geek-smart.cn";
$port = 1883;
$clientId = "php-client";
$username = '************';
$password = '************';
$clean_session = false;
$pub_topic = '/HYUGHV/lVtAcHuor***/4cebd60bf***/publish';
$sub_topic = '/HYUGHV/lVtAcHuor***/4cebd60bf***/subscribe';
$mqtt_version = MqttClient::MQTT_3_1_1;
定义消息发布函数
$payload = array(
'type' => 'info'
);
$jsonp = json_encode($payload);
$mqtt->publish(
// topic
$pub_topic,
// payload
$jsonp,
// qos
0,
// retain
true
);
定义 on_message 回调函数,用于打印订阅主题接收的消息内容
$mqtt->subscribe($sub_topic, function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
连接 MQTT
$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
$mqtt->connect($connectionSettings, $clean_session);
完整代码
<?php
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
$server = "mqtt.geek-smart.cn";
$port = 1883;
$clientId = "php-client";
$username = '************';
$password = '************';
$clean_session = false;
$pub_topic = '/HYUGHV/lVtAcHuor***/4cebd60bf***/publish';
$sub_topic = '/HYUGHV/lVtAcHuor***/4cebd60bf***/subscribe';
$mqtt_version = MqttClient::MQTT_3_1_1;
$connectionSettings = (new ConnectionSettings)
->setUsername($username)
->setPassword($password)
->setKeepAliveInterval(60);
// Last Will
//->setLastWillTopic('last-will/topic')
//->setLastWillMessage('client disconnect')
//->setLastWillQualityOfService(1);
$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");
$payload = array(
'type' => 'info'
);
$jsonp = json_encode($payload);
$mqtt->publish(
// topic
$pub_topic,
// payload
$jsonp,
// qos
0,
// retain
true
);
printf("msg send $jsonp to $pub_topic\n");
$mqtt->subscribe($sub_topic, function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
测试验证
运行
php pubsub_tcp.php