Mark
Mark

Reputation: 5100

How to answer to ajax request while receiving MQTT messages

I'm fairly new to PHP and MQTT and I'm trying to figure out how to answer to an Ajax request (from the JavaScript front-end) while receiving MQTT messages. The goal is to update the web page with the new data received. I'm aware I can use WebSockets and send the incoming messages directly from the PHP page, but for several reasons I don't want to use WebSockets here.

So far, here the code I use to answer to Ajax requests:

<?php
$result = [];
$result['success'] = false;
$result['message'] = "unknown";

if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'quit':
            $msg = shell_exec('sudo systemctl stop startup.service');
            $result['success'] = true;
            $result['message'] = $msg;
            break;

        case 'restart':
            $msg = shell_exec('sudo systemctl restart startup.service');
            $result['success'] = true;
            $result['message'] = $msg;
            break;

        case "do-something":
            // do something!
            $result['success'] = "true|false";
            $result['message'] = "blabla";
            break;    
    }

    echo json_encode($result);
}

and here the code I use to receive MQTT messages:

<?php 
require('vendor/autoload.php');
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

$server   = '<address>';
$port     = 1883;
$clientId = 'id';
$username = '<user>';
$password = '<password>';

$mqtt = new MqttClient($server, $port, $clientId);

$connectionSettings = (new ConnectionSettings)
  ->setUsername($username)
  ->setPassword($password)
  ->setKeepAliveInterval(60)
  ->setLastWillQualityOfService(1);

$mqtt->connect($connectionSettings, true);
$mqtt->subscribe('wsc/power', function ($topic, $message) {
    printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);

What I don't understand is how to join the two snippets. The MQTT one enables its own loop so any instruction placed after $mqtt->loop(true); is not executed.

How to handle async requests while the loop is active?

Upvotes: 0

Views: 73

Answers (0)

Related Questions