I want to connect to my Mosquitto broker running on my VPS with ubuntu 22.04.
I am using the library php-mqtt/clients and my code works fine in visual studio code but when I upload it to my web server (Apache2 and PHP 8.2.4) it does not work. Something is happening as if there is an error the code will disconnect and then I will see some of the json messages on the screen
I am using a javascript AJAX to retrieve the JSON but without success. I am under the impression that my Apache 2 configuration is the issue. Port 1883, 8883 (TLS) and 9001 (TLS Websocket) all work with MQTTX and 9001 works via javascript.
Chat GPT advises this but I do not trust it
<VirtualHost *:443>
ServerName example.com
# SSL configuration
SSLEngine on
SSLCertificateFile /path/to/certificate.pem
SSLCertificateKeyFile /path/to/key.pem
# PHP Mosquitto configuration
MosquittoTLSVersion tlsv1.2
MosquittoCACertificateFile /path/to/ca.crt
MosquittoClientCertificateFile /path/to/client.crt
MosquittoClientKeyFile /path/to/client.key
# PHP application configuration
DocumentRoot /path/to/app
<Directory /path/to/app>
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Here is my PHP named “testweb.php”
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/shared/config.php';
use PhpMqttClientConnectionSettings;
use PhpMqttClientExamplesSharedSimpleLogger;
use PhpMqttClientExceptionsMqttClientException;
use PhpMqttClientMqttClient;
use PsrLogLogLevel;
// Create an instance of a PSR-3 compliant logger. For this example, we will also use the logger to log exceptions.
$logger = new SimpleLogger(LogLevel::INFO);
// Define your MQTT authorization credentials.
$username = 'name';
$password = 'password';
try {
// Create a new instance of an MQTT client and configure it to use the shared broker host and port.
$client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_TLS_PORT, 'test-publisher', MqttClient::MQTT_3_1, null, $logger);
// Create and configure the connection settings as required.
$connectionSettings = (new ConnectionSettings)
->setUseTls(true)
->setTlsSelfSignedAllowed(true)
->setTlsClientCertificateFile("client.crt")
->setTlsClientCertificateKeyFile("client.key")
->setTlsClientCertificateKeyPassphrase("certificatepasswd1!*")
->setUsername($username)
->setPassword($password);
// Connect to the broker with the configured connection settings and with a clean session.
$client->connect($connectionSettings, true);
// Subscribe to a topic.
$client->subscribe('sensor/data', function ($topic, $message){
echo $message;
}, 0);
$client->loop(true);
// Gracefully terminate the connection to the broker.
$client->disconnect();
} catch (MqttClientException $e) {
// MqttClientException is the base exception of all exceptions in the library. Catching it will catch all MQTT related exceptions.
$logger->error('Connecting with TLS or publishing with QoS 0 failed. An exception occurred.', ['exception' => $e]);
}
and my very basic javascript for test purposes:
<html>
<head>
<title> MQTT Test via PHP and AJAX</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="temperature">Temperature = </p>
<p id="humidity">Humidity = </p>
<p id="latitude">Latitude = </p>
<p id="longitude">Longitude = </p>
<p id="date">Date = </p>
<p id="status"> Status =</p>
<script>
// Send an AJAX request to the PHP script to get the latest message
i = 0;
setInterval(function() {
$.ajax({
url: 'testweb.php',
dataType: 'json',
success: function(data) {
// Update the HTML elements with the new data
document.getElementById('temperature').innerHTML = data.temperature;
document.getElementById('humidity').innerHTML = data.humidity;
document.getElementById('latitude').innerHTML = data.latitude;
document.getElementById('longitude').innerHTML = data.longitude;
document.getElementById('date').innerHTML = data.date + "/" + data.month + "/" + data.year + " " + data.hours + ":" + data.minutes + ":" + data.seconds;
}
});
document.getElementById('status').innerHTML = "Status = Javascript has been running " + i + " time";
i = i+1;
}, 1000); // Poll every second
</script>
</body>
</html>
Does anybody have an idea how to make this work and if I have to change something in Apache2?
When I try opening the testweb.php in the browser it keeps loading non stop and sometimes (I can not figure what trigggers this) I get an Error that indicate could not connect to socket.
I do not know what to try next as I would just be trying stuff without knowing what I am doing at this stage.