Still couldn’t figure out why my code was failing so I turned up logging to 11 and noticed a couple of messages which didn’t make sense. The device was connecting than disconnecting which indicated a another problem. As part of the Message Queue Telemetry Transport(MQTT) specification there is a “feature” Last Will and Testament(LWT) which a client can configure so that the MQTT broker sends a message to a topic if the device disconnects unexpectedly.
I was looking at the code and noticed that LWT was being used and that the topic didn’t exist in my Azure Event Grid MQTT Broker namespace. When the LWT configuration was commented out the application worked.
void Mqtt5ClientESP32::begin(const char* uri, const char* client_id, const char* user, const char* pass, bool use_v5) {
connected_ = false;
insecure_ = false;
cfg_.broker.address.uri = uri;
if (client_id) cfg_.credentials.client_id = client_id;
if (user) cfg_.credentials.username = user;
if (pass) cfg_.credentials.authentication.password = pass;
cfg_.broker.verification.use_global_ca_store = false;
cfg_.broker.verification.certificate = nullptr;
cfg_.broker.verification.certificate_len = 0;
cfg_.broker.verification.skip_cert_common_name_check = false;
/*
cfg_.session.last_will.topic = "devices/esp32/lwt";
cfg_.session.last_will.msg = "offline";
cfg_.session.last_will.qos = 1;
cfg_.session.last_will.retain = true;
*/
cfg_.session.protocol_ver =
#if CONFIG_MQTT_PROTOCOL_5
use_v5 ? MQTT_PROTOCOL_V_5 : MQTT_PROTOCOL_V_3_1_1;
#else
MQTT_PROTOCOL_V_3_1_1;
(void)use_v5; // MQTT v5 support disabled at build time
#endif
}
Two methods were added so that the LWT could be configured if required
void SetLWT(const char *topic, const char *msg, int msg_len,int qos, int retain);
void Mqtt5ClientESP32::SetLWT(const char *topic, const char *msg, int msg_len,int qos, int retain){
cfg_.session.last_will.topic = topic;
cfg_.session.last_will.msg = msg;
cfg_.session.last_will.msg_len= msg_len;
cfg_.session.last_will.qos = qos;
cfg_.session.last_will.retain = retain;
}
Paying close attention to the logging I noticed the “Subscribing to ssl/mqtts” followed by “Subscribe request sent”
I checked the sample application and found that if the connect was successful the application would then try and subscribe to a topic that didn’t exist.
mqtt.onConnected([]{
Serial.println("[MQTT] Connected event");
mqttReady = true;
/*
Serial.println("[MQTT] Subscribing to ssl/mqtt5");
if (mqtt.subscribe("ssl/mqtt5", 1, true)) {
Serial.println("[MQTT] Subscribe request sent");
} else {
Serial.println("[MQTT] Subscribe request failed");
}
*/
I commented out that code and the application started without any messages
Just to make sure I checked that the message count in the Azure Storage Queue was increasing and the payload client ID matched my device
Yet again a couple of hours lost from my life which I can never get back
















































