Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mqtt check if subscribed topic has stopped publishing messages

I am trying to implement a way to know when a specific device has stopped publishing messages to an mqtt broker and in that case send an email to myself. I want to do this to be able to know if there is a problem with the device that is publishing the messages so I can check it and turn it back on. To try to accomplish this I created a mqtt client that subscribes to the topic that the device publishes e.g. test/device_1 and then set as last will and testament for that device status/device_1 where I put as payload="Offline". Ideally, I want to be able to do this for more than 1 device, but let's assume I just want it for the simple case of one device.

I created another script that implements another client that is subscribed to the topic status/device_1 and then on the on_message function it checks if it gets the payload="Offline" and if it does get it then I send an email to myself.

This approach however doesn't work as when I turn off my device, the mqtt client that is subscribed to the topic test/device_1 keeps listening but gets no messages. In other words, it doesn't send its last will even when the topic is empty. However, it seems to work when I stop the script that is subscribed to the topic test/device_1.

Am I missing something or is it not possible to accomplish what I am trying to do? Any advice is appreciated!

like image 311
thelaw Avatar asked Oct 24 '25 05:10

thelaw


1 Answers

First LWT messages are only published by the broker if the client goes offline unexpectedly, which means if it shuts down cleanly then it will not get published, you have to manually publish a message as part of shut down process.

You can set the retained flag on the LWT so that any client that subscribes after the device has gone offline it will still see the state message.

You should also clear that message on when the device starts up, either by publishing something like Online or a null payload to clear the retained message.

like image 168
hardillb Avatar answered Oct 26 '25 18:10

hardillb