doujiu7704 2018-11-08 08:46
浏览 215

非阻塞MQTT用户[PHP]

I am using a raspberry Pi to act as an MQTT broker for a group of sensors. The idea is to have a form with an input field on a website, and based on the value of the input field when submitted, the client should publish a message to the MQTT broker and then start a subscription to the same topic.

The website should then wait for a response from the MQTT server (i.e. message sent = "temp" and the RBP publishes a new message "Temp is 35 degrees Celsius".

However, when I invoke the subscriber function PHP receives the fatal error Fatal error: Maximum execution time of 30 seconds exceeded

It seems the PHP is blocking the script for too long, therefore quitting before receiving the a message. I need the PHP script to listen for a maximum of 1-2 minutes, and then it can close the MQTT connection.

<?php
require("phpMQTT.php");

$server = "xx.xx.xx.xx";              
$port = 1883;                       
$username = "username";             
$password = "password";             
$client_id = uniqid();  

$mqtt = new phpMQTT($server, $port, $client_id);

//Read message from form, which type of sensor to read    
$msg = $_POST['sensor'];

if (!empty($msg)) {
    if ($mqtt->connect(true, null, $username, $password)) {
        //Publish type of sensor to read
        $mqtt->publish("dev/sensors", $msg , 0);
        $mqtt->close();
    }

    //Start listen for response 
    subscribeToTopic($mqtt);
}

function subscribeToTopic($mqtt)
{
    //Set topic to listen to
    $topics['dev/sensors'] = array("qos" => 0, "function" => "procmsg");
    $mqtt->subscribe($topics, 0);

    //Listen for the response in the subscribed topic
    while ($mqtt->proc()) {

    }
    $mqtt->close();

}
function procmsg($topic, $msg)
{
    global $mqtt;
    echo $msg;

    //Close mqtt-connection after message is received
    $mqtt->close();
}

?>

If using MQTT is not possible for website / MQTT server connections, what would be a more suitable alternative to achieve this logic?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
    • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 保护模式-系统加载-段寄存器