当前位置: 首页 > article >正文

php 中使用MQTT

MQTT 是一种基于发布/订阅模式的 轻量级物联网消息传输协议 ,可以用极少的代码和带宽为联网设备提供实时可靠的消息服务,它广泛应用于物联网、移动互联网、智能硬件、车联网、电力能源等行业。

本文主要介绍如何在 PHP项目中使用composer require php-mqtt/client库 ,实现客户端与 MQTT 服务器 的连接、订阅、收发消息等功能。

<?phpnamespace app\command;use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use util\LogHelperUtil;// composer require php-mqtt/client
class Mqtt extends Command
{protected function configure(){$this->setName('mqtt')->setDescription('mqtt Hello');}protected function execute(Input $input, Output $output){$mqttConfig = config('mqtt');// MQTT代理的配置$server = $mqttConfig['host'] ?? ''; // MQTT代理的地址$port = $mqttConfig['port'] ?? 1883; // MQTT代理的端口$username = 'test_mqtt'; // MQTT代理的用户名(如果需要)$password = '123456'; // MQTT代理的密码(如果需要)$clientId = 'service-mqtt-' . time(); // 客户端IDtry {// 创建MQTT客户端实例$mqtt = new MqttClient($server, intval($port), $clientId);$settings = (new ConnectionSettings())->setUsername($username)->setPassword($password)->setKeepAliveInterval(10)   // 根据需要设置心跳间隔->setReconnectAutomatically(true) // 是否会尝试自动重新连接->setDelayBetweenReconnectAttempts(2000) // 定义重新连接尝试之间的延迟(毫秒)。->setMaxReconnectAttempts(10); // 重新连接的最大尝试次数$mqtt->connect($settings); // 连接到MQTT代理// 订阅一个主题$topic = 'testtopic/#';$mqtt->subscribe($topic, function ($topic, $message) use ($mqtt) {$time = self::getTime("Y年m月d日G时i分s秒x毫秒");echo "{$time} 主题:{$topic} - 收到:" . ($message) . PHP_EOL;if ($topic != 'testtopic/service/2' && $topic != 'testtopic/golang') {$mqtt->publish('testtopic/service/2', "hello[{$topic}]", 2, true);}}, 2);// 保持脚本运行,以便接收消息
//            while ($mqtt->isConnected()) {
//                $mqtt->loop();
//            }$mqtt->loop();
//            $mqtt->disconnect(); // 断开连接} catch (\Exception $e) {echo "MQTT Error: " . $e->getMessage();}$output->writeln("Received message on topic");}private static function getTime($tag){list($usec, $sec) = explode(" ", microtime());$now_time = $sec . '.' . substr($usec, 2, 4);list($usec, $sec) = explode(".", $now_time);$date = date($tag, $usec);return str_replace('x', $sec, $date);}
}
http://www.lryc.cn/news/2394490.html

相关文章:

  • C#定时器深度对比:System.Timers.Timer vs System.Threading.Timer性能实测与选型指南
  • go的select多路复用
  • 深度理解与剖析:前端声明式组件系统
  • 解决8080端口被占问题
  • 介绍一种LDPC码译码器
  • 3DMAX+Photoshop教程:将树木和人物添加到户外建筑场景中的方法
  • 【IOS】【OC】【应用内打印功能的实现】如何在APP内实现打印功能,连接本地打印机,把想要打印的界面打印成图片
  • 随记 配置服务器的ssl整个过程
  • 数据库高可用架构设计:集群、负载均衡与故障转移实践
  • Correlations氛围测试:文本或图像的相似度热图
  • 从0到1:多医院陪诊小程序开发笔记(上)
  • 建立连接后 TCP 请求卡住
  • 尚硅谷redis7 99 springboot整合redis之连接集群
  • hive 笔记
  • 无线通信模块简介
  • Go语言之空接口与类型断言
  • 把 CURSOR 的工具活动栏改成和 VSCODE 一样的左侧展示
  • 碰一碰系统源码搭建==saas系统
  • 不加载PHP OpenTelemetry SDK实现Trace‌与Logs
  • Three.js搭建小米SU7三维汽车实战(6)颜色切换
  • mysql慢sql的实际处理方案之一
  • GitLab 18.0 正式发布,15.0 将不再受技术支持,须升级【六】
  • c/c++的opencv车牌识别
  • 4.2.3 Spark SQL 手动指定数据源
  • 【论文解读】CVPR2023 PoseFormerV2:3D人体姿态估计(附论文地址)
  • WPF的交互核心:命令系统(ICommand)
  • Maven工程演示
  • uniapp分包配置,uniapp设置subPackages
  • 计算机网络 HTTP篇常见面试题总结
  • C++八股 —— 手撕线程池