I am writing a program connecting a web service in PHP to an MQTT broker. The broker is running Mosquitto on a Raspberry Pi.
The idea is to have the web service send a request (a form is submitted) and then send a publish to the MQTT broker and then wait for a reply.
However, the problem is that the loop seems to cause a PHP fatal error due to the fact that it is an endless loop.
I've tried adding the quitstop() function to quit the loop after a message is received, but the program crashes before it reaches that point.
MQTT is still very new to me, but I need to send the request and then keep the loop open until I receive the answer in order to proceed with my program.
This is the code to handle the form submit:
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();
}