Handle ESP32 chunked MQTT messages missing topic on non-first chunks, causing panic (#5786)

Co-authored-by: Samuel Sieb <samuel-github@sieb.net>
This commit is contained in:
Adam Liddell 2025-07-10 09:34:43 +01:00 committed by Jesse Hills
parent 23dd2d648e
commit 0ef5f1fd65
No known key found for this signature in database
GPG Key ID: BEAAE804EFD8E83A

View File

@ -153,11 +153,15 @@ void MQTTBackendESP32::mqtt_event_handler_(const Event &event) {
case MQTT_EVENT_DATA: {
static std::string topic;
if (!event.topic.empty()) {
// When a single message arrives as multiple chunks, the topic will be empty
// on any but the first message, leading to event.topic being an empty string.
// To ensure handlers get the correct topic, cache the last seen topic to
// simulate always receiving the topic from underlying library
topic = event.topic;
}
ESP_LOGV(TAG, "MQTT_EVENT_DATA %s", topic.c_str());
this->on_message_.call(!event.topic.empty() ? topic.c_str() : nullptr, event.data.data(), event.data.size(),
event.current_data_offset, event.total_data_len);
this->on_message_.call(topic.c_str(), event.data.data(), event.data.size(), event.current_data_offset,
event.total_data_len);
} break;
case MQTT_EVENT_ERROR:
ESP_LOGE(TAG, "MQTT_EVENT_ERROR");