I downloaded mosquitto mqtt broker and am running the broker on port 1883 on local machine, and have successfully tested its working using mosquitto_pub.exe and mosquitto_sub.exe files provided. When I publish a message over a topic I am able to receive it from its subscriber. I tested it using the cmd tool provided in windows 10 (for both publisher and subscriber on same machine). Now my understanding of the client is that a broker needs to be running in order to subscribe to it. So as per my requirements I downloaded the https://github.com/php-mqtt/client and using ajax in my php file I am trying to get the published message from the publisher which is a cmd tool previously started. However I am unable to get any message and after waiting for the timeout period and then I get error message (500- internal server error), but in the subscriber cmd window I am getting the message. Please help me understand what is wrong with my approach. I have used this to get all the devices that publish to the mentioned topic. I have also given the expected output as an Image which is produced from the code given. The "Approve" button of course isn't in the given code. I would add it once I get the list of publishers in the left side list. The sensors that have been listed there are simply hard coded html - the following is my code -
php code-
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Manage
<small>Devices</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i>Home</a></li>
<li class="active">Devices</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-md-12 col-xs-12">
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
if ($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php elseif ($this->session->flashdata('error')) : ?>
<div class="alert alert-error alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php endif; ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">Add Device</h3>
</div>
<form role="form" action="<?php base_url('devices/create') ?>" method="post">
<div class="box-body">
<?php echo validation_errors(); ?>
<table style="width:max-content;" class="table">
<tr>
<td class="td">
<button id="btnscansensors" type="button" class="btn btn-light" style="margin:5px">
<img id="wifi" src="../images/icons/wi-fi.png" width="96" /> Scan for sensors
</button>
</td>
<td class="td">
<button id="btnstopscansensors" type="button" class="btn btn-light" style="width:96px; height: 110px;margin:5px">
<span style="margin-right:5px">Stop Scan</span>
</button>
</td>
</tr>
</table>
<table class="table">
<tr>
<td class="td">
<div class="list-group" style="overflow-y: scroll; height: 25vw;" ;>
<?php //sensor list populate on button click
?>
<a href="#" class="list-group-item list-group-item-action">Sensor 1</a>
<a href="#" class="list-group-item list-group-item-action">Sensor 2</a>
<a href="#" class="list-group-item list-group-item-action">Sensor 3</a>
<a href="#" class="list-group-item list-group-item-action">Sensor 4</a>
<a href="#" class="list-group-item list-group-item-action">Sensor 5</a>
</div>
</td>
<td class="td">
<div class="form-group">
<label for="group_name">Device name</label>
<input type="text" class="form-control" id="device_name" name="device_name" placeholder="Device name">
</div>
<div class="form-group">
<label for="group_name">Active</label>
<select class="form-control" id="status" name="status">
<option value="1">Active</option>
<option value="2">Inactive</option>
</select>
</div>
</td>
</tr>
</table>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save Changes</button>
<a href="<?php echo base_url('devices/') ?>" class="btn btn-warning">Back</a>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- col-md-12 -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php
$dir = dirname(__FILE__, 4);
require $dir.'/vendor/autoload.php';
use PhpMqtt\Client\MqttClient;
if (isset($_POST['function_to_call'])) {
echo "read_topic being called";
switch ($_POST['function_to_call']) {
case 0: {
echo "read_topic being called";
read_topic();
break;
}
default:
break;
}
}
//function read_topic($topic, $server, $port, $keepalive, $timeout) {
function read_topic()
{
$server = 'localhost';
$port = 1883;
$clientId = 'test-subscriber';
$mqtt = new MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->subscribe('Registration', function ($topic, $message) {
echo $message; // for testing
echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
$mqtt->disconnect();
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("#devicesSideTree").addClass('active');
$("#createDevicesSideTree").addClass('active');
$('#btnstopscansensors').on('click', () => {
StopScanSensors();
});
$("#btnscansensors").on('click', (event) => {
ScanSensors();
//$.ajax();
$.ajax({
type: 'post',
//url: 'create.php',
data: "function_to_call=0",
success: function(data) {
alert('successful');
},
error: function (request, status, error) {
alert(request.responseText);
}
});
event.preventDefault();
//$.ajax();
});
function ScanSensors() {
$('#btnscansensors').prop('disabled', true);
$('#wifi[src$=".png"]').each(function(index, element) {
element.src = element.src.replace('.png', '.gif');
});
//$.ajax();
}
function StopScanSensors() {
$('#btnscansensors').prop('disabled', false);
$('#wifi[src$=".gif"]').each(function(index, element) {
element.src = element.src.replace('.gif', '.png');
});
//$.ajax();
}
});
</script>
PHP runs on the server side and renders the HTML that is then sent to browser. By the time the page is loaded in the browser the PHP code has stopped running, so won't receive any messages.
Also your PHP code connects then instantly disconnects from the broker.
$mqtt->connect();
$mqtt->subscribe('Registration', function ($topic, $message) {
echo $message; // for testing
echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
$mqtt->loop(true);
$mqtt->disconnect();
If you want to receive and display live MQTT messages in your webpage you can not use PHP, you will need to enable MQTT over WebSockets in the broker and then use either the Paho Javascript client on the MQTT.js client to subscribe to the messages actually in the page.