网上找的mqtt类:https://github.com/bluerhinos/phpMQTT/blob/master/phpMQTT.php
用的thinkphp5.0,下载后放入extend文件夹下。
新建控制器 application/lora/controller/SubController.php
<?php
namespace app\lora\controller;
use think\Controller;
use think\Db;
class SubController extends Controller
{
public function _initialize()
{
header("Content-Type:text/html; charset=utf-8");
// 客户端id 可以用随机数
$this->client = "2cc415fdcb574fb297e3185132d6481a";
// mqtt主机 主机,请配置为自己的主机
$this->host = "127.0.0.1";
// mqtt端口
$this->port = 1883;
// 密钥 用于证书配置,如果需要ssl认证,则必须填写
// $this->cert= 'ca.pem';
// mqtt账号
$this->username = "";
// mqtt密码
$this->password = "";
// 订阅主题 订阅的主题,注意使用的主题一定要是mqtt配置过的主题,比如百度天工需要策略认证过的
// 自己学习的时候,可以随意自定义,一般跟发布主题一致便可以收到消息
// 如要要接受所有主题,请使用#
// $this->topics_name="#";
$this->topics_name = "application/1/#";
}
//运行 并且订阅
function index()
{
// 创建mqtt实例
$this->mqtt = new \phpMQTT($this->host, $this->port, $this->client);
// 若mqtt链接失败
if (!$this->mqtt->connect(true, NULL, $this->username, $this->password)) {
echo "mqtt链接失败!";
}
// 注意:这里qos的设置,有些broker限制了使用0,则可以用1试试。百度天工测试代码 则为1
$topics[$this->topics_name] = array("qos" => 0, "function" => array($this, "message"));
$this->mqtt->subscribe($topics, 0);
while ($this->mqtt->proc()) {
}
}
// 回调消息
public function message($topic, $msg)
{
cache('msg', date("Y-m-d H:i:s", time()) . ": 收到订阅消息 $topic : $msg \n\r");
}
public function test()
{
dump(cache('msg'));
}
}
可在回调函数中把数据写入数据库。
因订阅需要以守护进程运行,故采用thinkphp5自定义命令行
application/command.php
<?php
return [
'app\index\command\Mqtt',
];
application/index/command/Mqtt.php
<?php
namespace app\index\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Request;
class Mqtt extends Command
{
protected function configure()
{
$this->setName('mqttsub')->setDescription('订阅mqtt');
}
protected function execute(Input $input, Output $output)
{
$request = Request::instance();
$request->module("lora");
$output->writeln(controller('lora/SubController')->index());
}
}
最后执行 nohup php think mqttsub &
版权声明:本文为m0_37619318原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。