php-mqtt/client

Listening for PINGREQ of other clients

playbackdev opened this issue · 5 comments

Hi!
Could you explain, is it possible to subscribe to PINGREQ messages of other clients?

Details for example: There are many clients, which publishing any messages on any topics, including PINGREQ messages too.
So there is also the "main" client, which only subscribed to all possible topics and listening for messages, which other clients sending.
So i want the main client to be able to subscribe and listen to PINGREQ messages from other clients to check their connection to the broker, is it possible?

When i'm trying to debug handleMessage() in MqttClient.php i didn't see any PINGREQ messages from other client, only PINGRESP messages from own PINGREQ

No, this is not possible. The PINGREQ and PINGRESP messages are only sent and seen between a client and the broker as they are used to keep the connection between a client and broker alive. This is an MQTT limitation and not something this library can change.

For your use case, the last will and testament can be used. When the client connects, it publishes its online status to e.g. clients/{clientId}/online: true. The last will ensures the topic is set to clients/{clientId}/online: false when the client disconnects from the broker.

Thanks for your answer!
So, should i implement manually in my code publishing online status true to some topic while client is connecting?
Or is there some default broker feature to implement it similar to specifying last will message and topic when connecting?

You most likely need to implement the publishing of the online status yourself. Maybe some MQTT clients (in other programming languages) have a built-in feature for this, but this library does not. Currently, as there is no way to detect a reconnect when using the auto-reconnect feature, this might be incompatible with auto-reconnects though.^

Thanks!

With this library, the whole thing would look something like this:

$clientId = 'my-client';
$client = new MqttClient($host, $port, $clientId, MqttClient::MQTT_3_1);

$connectionSettings = (new ConnectionSettings)
    ->setLastWillTopic("clients/{$clientId}/online")
    ->setLastWillMessage('false')
    ->setLastWillQualityOfService(MqttClient::QOS_AT_LEAST_ONCE)
    ->setRetainLastWill(true);

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

// Retain the online status. This allows other clients to retrieve it at a later point in time.
$client->publish("clients/{$clientId}/online", 'true', MqttClient::QOS_AT_LEAST_ONCE, true);