我正在编写一个程序,将 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();
}