From e6f8e73705dc310cb8b188fd509b543fe3ad7cf9 Mon Sep 17 00:00:00 2001 From: Gareth Cooper Date: Thu, 8 Apr 2021 13:26:34 +0100 Subject: [PATCH] Receive long MQTT payload (#1590) --- esphome/components/mqtt/mqtt_client.cpp | 14 +++++++++++--- esphome/components/mqtt/mqtt_client.h | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/esphome/components/mqtt/mqtt_client.cpp b/esphome/components/mqtt/mqtt_client.cpp index 190df0b2f3..b8743fc142 100644 --- a/esphome/components/mqtt/mqtt_client.cpp +++ b/esphome/components/mqtt/mqtt_client.cpp @@ -25,9 +25,17 @@ void MQTTClientComponent::setup() { ESP_LOGCONFIG(TAG, "Setting up MQTT..."); this->mqtt_client_.onMessage([this](char *topic, char *payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { - std::string payload_s(payload, len); - std::string topic_s(topic); - this->on_message(topic_s, payload_s); + if (index == 0) + this->payload_buffer_.reserve(total); + + // append new payload, may contain incomplete MQTT message + this->payload_buffer_.append(payload, len); + + // MQTT fully received + if (len + index == total) { + this->on_message(topic, this->payload_buffer_); + this->payload_buffer_.clear(); + } }); this->mqtt_client_.onDisconnect([this](AsyncMqttClientDisconnectReason reason) { this->state_ = MQTT_CLIENT_DISCONNECTED; diff --git a/esphome/components/mqtt/mqtt_client.h b/esphome/components/mqtt/mqtt_client.h index 885f4a9a96..e4f7c479b2 100644 --- a/esphome/components/mqtt/mqtt_client.h +++ b/esphome/components/mqtt/mqtt_client.h @@ -259,6 +259,7 @@ class MQTTClientComponent : public Component { }; std::string topic_prefix_{}; MQTTMessage log_message_; + std::string payload_buffer_; int log_level_{ESPHOME_LOG_LEVEL}; std::vector subscriptions_;