This commit is contained in:
szdot 2024-06-11 17:09:03 +08:00
commit 4eebf28fc5
2 changed files with 1 additions and 40 deletions

View File

@ -3,50 +3,11 @@
namespace Home\Controller; namespace Home\Controller;
use Think\Controller; use Think\Controller;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\ConnectionSettings;
class IndexController extends Controller class IndexController extends Controller
{ {
public function index() public function index()
{ {
//$this->display(); $this->display();
$server = 'www.szdot.top'; // MQTT 代理地址
$port = 1883; // MQTT 代理端口
$clientId = 'php-mqtt-client'; // 客户端 ID
$username = 'admin'; // 用户名(如果需要)
$password = '123456'; // 密码(如果需要)
try {
// 创建连接设置对象
$settings = (new ConnectionSettings)
->setUsername($username)
->setPassword($password);
// 实例化 MQTT 客户端
$mqtt = new MqttClient($server, $port, $clientId);
// 连接到 MQTT 代理
$mqtt->connect($settings);
// 检查是否连接成功
if ($mqtt->isConnected()) {
echo "Connected to MQTT broker successfully\n";
// 发布消息到指定的主题
$mqtt->publish('demo', 'Hello MQTT', 0);
echo "Message published successfully\n";
// 断开连接
$mqtt->disconnect();
echo "Disconnected from MQTT broker\n";
} else {
echo "Could not connect to MQTT broker\n";
}
} catch (MqttClientException $e) {
echo "Could not connect to MQTT broker: " . $e->getMessage();
}
} }
} }

View File