PHP MQTT: The broker responded with unauthorized

Hello everyone,
I used the code to subscribe on the mqtt of ttn with this code :

I have configured everything but I have a problem.
MQTT [eu1.cloud.thethings.network:1883] [test-subscriber] The broker responded with unauthorized. Subscribing to a topic using QoS 0 failed. An exception occurred.

Have you already done some MQTT testing with a cli client like mosquitto_sub?
Use -v and -d options for verbose and debug output.

How to put the topic on the php-mqtt code ??

<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

require __DIR__ . '/../shared/config.php';

use PhpMqtt\Client\Examples\Shared\SimpleLogger;

use PhpMqtt\Client\Exceptions\MqttClientException;

use PhpMqtt\Client\MqttClient;

use Psr\Log\LogLevel;

// Créez une instance d'un enregistreur conforme à la norme PSR-3. Pour cet exemple, nous utiliserons également le logger pour enregistrer les exceptions.

$logger = new SimpleLogger(LogLevel::INFO);

try {

    // Créez une nouvelle instance d'un client MQTT et configurez-la pour utiliser l'hôte et le port du courtier partagé.

    $client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_PORT, 'test-subscriber', MqttClient::MQTT_3_1, null, $logger);

    // Se connecter au courtier sans paramètres de connexion spécifiques mais avec une session propre.

    $client->connect(null, true);

    // Subscribe to the topic 'foo/bar/baz' using QoS 0.

    $client->subscribe('foo/bar/baz', function (string $topic, string $message, bool $retained) use ($logger, $client) {

        $logger->info('We received a {typeOfMessage} on topic [{topic}]: {message}', [

            'topic' => $topic,

            'message' => $message,

            'typeOfMessage' => $retained ? 'retained message' : 'message',

        ]);

        // After receiving the first message on the subscribed topic, we want the client to stop listening for messages.

        $client->interrupt();

    }, MqttClient::QOS_AT_MOST_ONCE);

    // Since subscribing requires to wait for messages, we need to start the client loop which takes care of receiving,

    // parsing and delivering messages to the registered callbacks. The loop will run indefinitely, until a message

    // is received, which will interrupt the loop.

    $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('Subscribing to a topic using QoS 0 failed. An exception occurred.', ['exception' => $e]);

}

If you can run PHP, can you run it as a Webhook rather than the connection-based MQTT?

Simpler and less load on both ends.

I have my teacher who wants to do on mqtt

You did not (yet) answer my question.

Take care that you have MQTT with a CLI MQTT client like mosquitto_sub working succesfully first. Then the next step should be to get it working from within PHP.

Hello,
Yes it works on mqttfx and I solved my problem, now I’m looking for the topic name.
I took this one :
v3/*********@ttn/devices/eui-a8*********/join
I need a topic that can recover the payload
image

The topic for all the device in the application — v3/+/devices/+/up

Hello, I found it and it works

<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../shared/config.php';

use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\Examples\Shared\SimpleLogger;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\MqttClient;
use Psr\Log\LogLevel;

// Créez une instance d'un enregistreur conforme à la norme PSR-3. Pour cet exemple, nous utiliserons également le logger pour enregistrer les exceptions.
$logger = new SimpleLogger(LogLevel::INFO);

try {
    // Créez une nouvelle instance d'un client MQTT et configurez-la pour utiliser l'hôte et le port du courtier partagé.
    $client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_PORT, 'test-publisher', MqttClient::MQTT_3_1, null, $logger);

    // Créez et configurez les paramètres de connexion selon les besoins.
    $connectionSettings = (new ConnectionSettings)
        ->setUsername(AUTHORIZATION_USERNAME)
        ->setPassword(AUTHORIZATION_PASSWORD);

    // Connectez-vous au courtier avec les paramètres de connexion configurés et avec une session propre.
    $client->connect($connectionSettings, true);

    // S'abonner au sujet 'v3/@ttn/devices/eui-a86/up' en utilisant QoS 0.

    $client->subscribe('v3/@ttn/devices/eui-a86/up', function (string $topic, string $message, bool $retained) use ($logger, $client) {
        $logger->info('Nous avons reçu un {typeOfMessage} sur le topic [{topic}]: {message}', [
            'topic' => $topic,
            'message' => $message,
            'typeOfMessage' => $retained ? 'retained message' : 'message',

        ]);
        // $msg =json_decode($message);
        json_decode($message);
        // $frm_payload = $msg->frm_payload;
        // Après avoir reçu le premier message sur le sujet souscrit, nous voulons que le client cesse d'écouter les messages.
        $client->interrupt();
    }, MqttClient::QOS_AT_MOST_ONCE);

    // Puisque la souscription nécessite d'attendre les messages, nous devons lancer la boucle client qui s'occupe de la réception,
    // de l'analyse et de la livraison des messages aux callbacks enregistrés. La boucle s'exécutera indéfiniment, jusqu'à ce qu'un message
    // soit reçu, ce qui interrompra la boucle.
    $client->loop(true);

    // Termine gracieusement la connexion au courtier.
    $client->disconnect();
} catch (MqttClientException $e) {
    // MqttClientException est l'exception de base de toutes les exceptions de la bibliothèque. Si vous l'attrapez, vous attraperez toutes les exceptions liées à MQTT.
    $logger->error('Connecting with username and password or publishing with QoS 0 failed. An exception occurred.', ['exception' => $e]);
} 

But I would like to decode the message and take a part

I made this :

        $msg =json_decode($message);
        $frm_payload = $msg->frm_payload;
<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

require __DIR__ . '/../shared/config.php';

use PhpMqtt\Client\ConnectionSettings;

use PhpMqtt\Client\Examples\Shared\SimpleLogger;

use PhpMqtt\Client\Exceptions\MqttClientException;

use PhpMqtt\Client\MqttClient;

use Psr\Log\LogLevel;

// Créez une instance d'un enregistreur conforme à la norme PSR-3. Pour cet exemple, nous utiliserons également le logger pour enregistrer les exceptions.

$logger = new SimpleLogger(LogLevel::INFO);

try {

    // Créez une nouvelle instance d'un client MQTT et configurez-la pour utiliser l'hôte et le port du courtier partagé.

    $client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_PORT, 'test-publisher', MqttClient::MQTT_3_1, null, $logger);

    // Créez et configurez les paramètres de connexion selon les besoins.

    $connectionSettings = (new ConnectionSettings)

        ->setUsername(AUTHORIZATION_USERNAME)

        ->setPassword(AUTHORIZATION_PASSWORD);

    // Connectez-vous au courtier avec les paramètres de connexion configurés et avec une session propre.

    $client->connect($connectionSettings, true);

    // S'abonner au sujet 'v3/nad@ttn/devices/eui-a86/up' en utilisant QoS 0.

    $client->subscribe( 'v3/nad@ttn/devices/eui-a86/up', function (string $topic, string $message, bool $retained) use ($logger, $client) {

        $logger->info('Nous avons reçu un {typeOfMessage} sur le topic [{topic}]: {message}', [

            'topic' => $topic,

            'message' => $message,

            'typeOfMessage' => $retained ? 'retained message' : 'message',

        ]);
    $message = file_get_contents("php://input");

        // $msg =json_decode($message);

        // $frm_payload = $msg->frm_payload;

        $json = json_decode($message, true);

        $end_device_ids = $json['end_device_ids'];

        $device_id = $end_device_ids['device_id'];

        $application_id = $end_device_ids['application_ids']['application_id'];

       

        $received_at = $json['received_at'];

        $uplink_message = $json['uplink_message'];

            $frm_payload = $uplink_message['frm_payload'];

            $data_rate_index = isset($uplink_message['settings']['data_rate_index']) ? $uplink_message['settings']['data_rate_index'] : 0;

            $consumed_airtime = $uplink_message['consumed_airtime'];

        // Après avoir reçu le premier message sur le sujet souscrit, nous voulons que le client cesse d'écouter les messages.

        $client->interrupt();

    }, MqttClient::QOS_AT_MOST_ONCE);

    // Puisque la souscription nécessite d'attendre les messages, nous devons lancer la boucle client qui s'occupe de la réception,

    // de l'analyse et de la livraison des messages aux callbacks enregistrés. La boucle s'exécutera indéfiniment, jusqu'à ce qu'un message

    // soit reçu, ce qui interrompra la boucle.

    $client->loop(true);

    // Termine gracieusement la connexion au courtier.

    $client->disconnect();

} catch (MqttClientException $e) {

    // MqttClientException est l'exception de base de toutes les exceptions de la bibliothèque. Si vous l'attrapez, vous attraperez toutes les exceptions liées à MQTT.

    $logger->error('Connecting with username and password or publishing with QoS 0 failed. An exception occurred.', ['exception' => $e]);

}

// Journal quotidien via un log

$file = date('Ymd').".txt";

$output = "$received_at\t$application_id\t$device_id\t$f_cnt\t$f_port\t$frm_payload\t$data_rate_index\t$consumed_airtime\t$rssi\t$snr\n";

if (!file_exists($file)) {  // Put column headers at top of file

    file_put_contents($file, "received_at\tapplication_id\tdevice_id\tf_cnt\tf_port\tfrm_payload\tdata_rate_index\tconsumed_airtime\trssi\tsnr\n");

}

file_put_contents($file, $output, FILE_APPEND | LOCK_EX);

// Application log

$file = $application_id.".txt";

$output = "$received_at\t$device_id\t$f_cnt\t$f_port\t$frm_payload\t$data_rate_index\t$consumed_airtime\t$rssi\t$snr\n";

if (!file_exists($file)) {  // Put column headers at top of file

    file_put_contents($file, "received_at\tdevice_id\tf_cnt\tf_port\tfrm_payload\tdata_rate_index\tconsumed_airtime\trssi\tsnr\n");

}

file_put_contents($file, $output, FILE_APPEND | LOCK_EX);

//Log D

$file = $application_id."__".$device_id.".txt";

$output = "$received_at\t$f_cnt\t$f_port\t$frm_payload\t$data_rate_index\t$consumed_airtime\t$rssi\t$snr\n";

if (!file_exists($file)) {  // Put column headers at top of file

    file_put_contents($file, "received_at\tf_cnt\tf_port\tfrm_payload\tdata_rate_index\tconsumed_airtime\trssi\tsnr\n");

}

file_put_contents($file, $output, FILE_APPEND | LOCK_EX);

?>

I tried to get inspiration from this code : TheThingsStack-Integration-Starters/WebHook-to-Tab-PHP at main · descartes/TheThingsStack-Integration-Starters · GitHub

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 45

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 46

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 47

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 47

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 49

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 51

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 52

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 54

Warning: Undefined variable $received_at in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $application_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $device_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $f_cnt in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $f_port in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $frm_payload in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $data_rate_index in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $consumed_airtime in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $rssi in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $snr in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 77

Warning: Undefined variable $application_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 87

Warning: Undefined variable $received_at in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $device_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $f_cnt in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $f_port in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $frm_payload in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $data_rate_index in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $consumed_airtime in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $rssi in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $snr in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 89

Warning: Undefined variable $application_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 99

Warning: Undefined variable $device_id in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 99

Warning: Undefined variable $received_at in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $f_cnt in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $f_port in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $frm_payload in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $data_rate_index in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $consumed_airtime in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $rssi in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Warning: Undefined variable $snr in C:\xampp\htdocs\client-s\suscribe\connectersouscrire.php on line 101

Is why you get Undefined variable - read here for more

I don’t really see the connection

you are trying to use out of scope variables … secondly what is the purpose of “$message = file_get_contents(“php://input”);” this is waiting for console input and overwriting the message you just received.

To read in the php file ??

Whilst you are correct, it reads in the raw JSON from the post element of the HTTP request, there is no need to shout - not everyone knows everything about all languages.

Nick, maybe I misunderstand but he is trying to receive a message thru MQTT and Log the received json elements, he is not using it as a hook …

LOL, it’s worse than that - he’s using MQTT and copied & pasta’d my WebHook code …

… but now I look beyond the muddle, you are totally correct, it’s not going to help overwriting the message with the input from some random other place.

As this is a student project, I think we need to wait for the OP to clean up the code and then move on to learning how to decode the frm_payload in to a byte array and then slice up the byte array in to the appropriate variables.

No I don’t shout, sorry for the capital letters

I’ve succeeded I’m really stupid

Not withstanding your self-esteem, can you tell us what you did wrong so others finding this thread can benefit from your learning experience please.