php - phpMQTT 非阻塞发布和接收
问题描述
我正在编写一个程序,将 PHP 中的 Web 服务连接到 MQTT 代理。代理在 Raspberry Pi 上运行 Mosquitto。
这个想法是让 Web 服务发送请求(提交表单),然后将发布发送到 MQTT 代理,然后等待回复。
但是,问题在于循环似乎会导致 PHP 致命错误,因为它是一个无限循环。
我尝试添加 quitstop() 函数以在收到消息后退出循环,但程序在到达该点之前崩溃。
MQTT 对我来说仍然很新,但我需要发送请求,然后保持循环打开,直到我收到答案才能继续执行我的程序。
这是处理表单提交的代码:
require("phpMQTT.php");
$server = "xxx.xxx.xxx.xx"; // change if necessary
$port = 1883; // change if necessary
$username = "username"; // set your username
$password = "password"; // set your password
$client_id = "phpMQTT-request-1234"; // make sure this is unique for connecting to sever - you could use uniqid()
$mqtt = new phpMQTT($server, $port, $client_id);
$msg = $_POST['box'];
if (!empty($msg)) {
if ($mqtt->connect(true, null, $username, $password)) {
$mqtt->publish("dev/test", $msg, 0);
$mqtt->close();
}
subscribeToTopic($mqtt);
}
function subscribeToTopic($mqtt)
{
$topics['dev/test'] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while ($mqtt->proc()) {
}
$mqtt->close();
}
function procmsg($topic, $msg)
{
global $mqtt;
echo $msg;
quitstop($mqtt);
}
function quitstop($mqtt)
{
$mqtt->close();
}
解决方案
推荐阅读
- ruby-on-rails - 在 ruby 上安装 gtk2 gem
- angular - ngOnchange 不检测动态变化
- woocommerce - 删除仅添加到购物车的单个产品页面
- javascript - 我如何在反应打字稿中引用文档?
- azure-pipelines - Azure Pipelines:可以从管道资源而不是存储库资源中使用模板吗?
- javascript - 这个 XSS 有效负载如何用于此代码?
- sql-server - SSIS Web 服务任务 - 输入变量
- css - 在反应中以“库生成的组件”中的css类为目标
- c++ - 从 Raspberry Pi 进行串行输入后 Arduino 重新启动
- r - 如何用栅格数据拉直倾斜的 ggplot2 地图?