一、引入MQtt库 git地址:https://github.com/bluerhinos/phpMQTT 我这边没用composer引入,直接把库里面的PHPMQtT.php代码复制出来,改了个名字
git地址:https://github.com/bluerhinos/phpMQTT
我这边没用composer引入,直接把库里面的PHPMQtT.php代码复制出来,改了个名字叫MqttNewService
php think make:command Mqtt mqtt
return [ // 指令定义 'commands' => [ 'mqtt' => 'app\command\Mqtt' ],];
bin2hex() 函数把 ASCII 字符的字符串转换为十六进制值。字符串可通过使用 pack() 函数再转换回去。
pack() 函数把数据装入一个二进制字符串。
因为我这边是和硬件通信,所有消息都是16进制的,所以需要用的这两个函数,如果你的业务使用string或者JSON,那就不需要使用这两个函数了,可以把下面代码里面对应的函数删掉
;use think\console\Command;use think\console\Input;use think\console\Output;use app\common\service\MqttNewService;class Mqtt extends Command{ protected function configure() { // 指令配置 $this->setName('mqtt') ->setDescription('the mqtt command'); } protected function execute(Input $input, Output $output) { $this->subscribe(); } //订阅接收消息 protected function subscribe() { $server = 'xx.com'; $port = 1883; $clientId = 'test_emqx'. rand(1000000, 99999999); $topic = "test-mqtt-12345"; $username = ""; $pwd = ""; $mqtt = new MqttNewService($server, $port, $clientId); if(!$mqtt->connect(true, NULL, $username, $pwd)) { exit(1); } $mqtt->debug = true; $topics[$topic] = array('qos' => 0, 'function' => array($this,"procMsg")); $mqtt->subscribe($topics, 0); while($mqtt->proc()) { } $mqtt->close(); } function procMsg($topic, $msg){ $msg = bin2hex($msg); echo $msg. "\n"; }}
在项目下使用php think mqtt将这个脚本运行起来,然后用MQTTX软件发送消息进行测试MQTTX是用来测试mqtt的软件,下载地址:https://www.emqx.com/zh/products/mqttx
可以看到脚本已经接收到了数据
//发布消息 public function publish() { $msg = input('msg'); $server = 'xx.com'; $port = 1883; $username = ''; $passWord = ''; $clientId = 'test_emqx'. rand(1000000, 99999999); $mqtt = new MqttNewService($server, $port, $clientId); if ($mqtt->connect(true, NULL, $username, $password)) { $mqtt->publish('test-mqtt-12345', pack('H*',$msg), 0, false); $mqtt->close(); } else { echo "Time out!\n"; } }
使用postman测试这个接口,正常收到了数据,如有问题,可以下面留言
来源地址:https://blog.csdn.net/LuoHuaX/article/details/129286593
--结束END--
本文标题: thinkphp6.0连接mqtt进行通信
本文链接: https://www.lsjlt.com/news/398262.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
一口价域名售卖能注册吗?域名是网站的标识,简短且易于记忆,为在线用户提供了访问我们网站的简单路径。一口价是在域名交易中一种常见的模式,而这种通常是针对已经被注册的域名转售给其他人的一种方式。
一口价域名买卖的过程通常包括以下几个步骤:
1.寻找:买家需要在域名售卖平台上找到心仪的一口价域名。平台通常会为每个可售的域名提供详细的描述,包括价格、年龄、流
443px" 443px) https://www.west.cn/docs/wp-content/uploads/2024/04/SEO图片294.jpg https://www.west.cn/docs/wp-content/uploads/2024/04/SEO图片294-768x413.jpg 域名售卖 域名一口价售卖 游戏音频 赋值/切片 框架优势 评估指南 项目规模
0