Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MQTT: Add Online / Last Will messages (LWT) #166

Open
aly-fly opened this issue Jan 1, 2025 · 0 comments
Open

MQTT: Add Online / Last Will messages (LWT) #166

aly-fly opened this issue Jan 1, 2025 · 0 comments

Comments

@aly-fly
Copy link

aly-fly commented Jan 1, 2025

As you are not accepting PRs, I am sending the recommended updates here.
Changes below implement Online and Offline status, which can be used by high-level MQTT systems, like HA, to correctly handle the disconnected device.

List of global variables - add:

String               mqttalivemsg;                       // MQTT mesasage for online status
String               mqttlwtmsg;                         // MQTT mesasage for LWT (Last Will and Testament)

List of definistions - add:
#define MQTT_CONN_SUBTOPIC "connection" // Subtopic where "online", "offline" and Last Will messages are published

M Q T T P U B _ C L A S S -
enum add:
MQTT_ALIVE

amqttpub[10] add
{ MQTT_CONN_SUBTOPIC, MQSTRING, &mqttalivemsg, false }, // Definition for MQTT_ALIVE
and increase number of items from 9 to 10.

M Q T T R E C O N N E C T:
mqttclient.connect replace with:

mqttlwtmsg = "offline"; 
  sprintf ( subtopic, "%s/%s",
            ini_block.mqttprefix.c_str(),
            MQTT_CONN_SUBTOPIC ) ;

  res = mqttclient.connect ( clientid,                    // Connect to broker and set LWT message at the broker
                             ini_block.mqttuser.c_str(),
                             ini_block.mqttpasswd.c_str(),
                             subtopic,
                             0,
                             false,
                             mqttlwtmsg.c_str() ) ;

Documentation:
https://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament/

Result:
image

When network connection breaks for any reason, the MQTT broker publishes the connection = offline message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant