[I am aware of a very similar question, but the answers are not helping]
In my scenario it would be helpful to get notified when my client goes offline - no matter if it exits graceful or not. Specifying a last will seemed like a good idea (and following the real-life application of a last will I thought that this will take always take effect).
But when I use client.disconnect()
the last will is not published.
Now I am wondering how I can solve this problem. On some pages it is stated that this can somehow be configured, so that the last will is sent anyways. My paho-mqtt version is 1.6.1 and PyPi states that it implements MQTT 5.0 which is required for that functionality.
But I don't get it working and don't even understand what I should do:
client.disconnect("disconnect-with-will-message")
not working
client.disconnect(0)
not working
client.disconnect(1)
not working
Is there a solution other than having a manual publish statement in the case of a graceful exit?
Solution:
Using paho-mqtt it needs to be specified that the mqtt5 protocol should be used:
import paho.mqtt.client as mqtt
import paho.mqtt.reasoncodes as reasoncodes
import paho.mqtt.packettypes as packettypes
client = mqtt.Client(protocol=mqtt.MQTTv5)
client.will_set('last/willi')
client.connect('localhost')
client.publish('hello/world')
client.loop()
client.disconnect(reasoncodes.ReasonCodes(packettypes.PacketTypes.DISCONNECT, "Disconnect", 4))
The client.disconnect()
function can take 2 arguments for MQTTv5 clients
reasoncode
and properties
From the spec it says the disconnect-with-will reasoncode
should be 4