How to set the Last Will and Testament (LWT) message using mosquitto_pub in MQTT?

Replace --will-message with --will-payload (see the man page for more info) i.e.

mosquitto_pub -h localhost -t "home/alerts" -m "Client disconnected unexpectedly" -q 1 --will-topic "home/alerts" --will-payload "Client disconnected unexpectedly" --will-qos 1

If you do this, the mosquitto logs will contain something like:

1743924290: New connection from ::1:55171 on port 1883.
1743924290: New client connected from ::1:55171 as auto-DADB0CA7-910A-3896-242B-7D15302F780C (p2, c1, k60).
1743924290: Will message specified (32 bytes) (r0, q1).
1743924290:     home/alerts
1743924290: Sending CONNACK to auto-DADB0CA7-910A-3896-242B-7D15302F780C (0, 0)
1743924290: Received PUBLISH from auto-DADB0CA7-910A-3896-242B-7D15302F780C (d0, q1, r0, m1, 'home/alerts', ... (32 bytes))
1743924290: Sending PUBACK to auto-DADB0CA7-910A-3896-242B-7D15302F780C (m1, rc0)
1743924291: Received DISCONNECT from auto-DADB0CA7-910A-3896-242B-7D15302F780C
1743924291: Client auto-DADB0CA7-910A-3896-242B-7D15302F780C disconnected.

Note that, as mosquitto_pub will “publish a single message on a topic and exit”, setting a will is unlikely to have much of an impact (a will is generally used when there is a long running connection – as may be the case with mosquitto_sub). I guess there is a possibility that mosquitto_pub might connect, send the CONNECT packet (with the will), and then loose the connection before the message is published (in which case the broker will send the will), but this is unlikely to happen frequently (unless you have a very unreliable connection).

Read more here: Source link