From 84a830195fb991bcf7792c26d36999b5b8d60e0d Mon Sep 17 00:00:00 2001 From: stegm Date: Thu, 6 Jan 2022 16:40:22 +0100 Subject: [PATCH] Fix offset bug in modbus text sensor. (#3006) --- .../text_sensor/modbus_textsensor.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp b/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp index 25b79474e8..c90890c88f 100644 --- a/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp +++ b/esphome/components/modbus_controller/text_sensor/modbus_textsensor.cpp @@ -14,18 +14,18 @@ void ModbusTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Modbus Controller Te void ModbusTextSensor::parse_and_publish(const std::vector &data) { std::ostringstream output; uint8_t max_items = this->response_bytes; + uint8_t index = this->offset; char buffer[4]; - bool add_comma = false; - for (auto b : data) { + while ((max_items != 0) && index < data.size()) { + uint8_t b = data[index]; switch (this->encode_) { case RawEncoding::HEXBYTES: sprintf(buffer, "%02x", b); output << buffer; break; case RawEncoding::COMMA: - sprintf(buffer, add_comma ? ",%d" : "%d", b); + sprintf(buffer, index != this->offset ? ",%d" : "%d", b); output << buffer; - add_comma = true; break; // Anything else no encoding case RawEncoding::NONE: @@ -33,9 +33,8 @@ void ModbusTextSensor::parse_and_publish(const std::vector &data) { output << (char) b; break; } - if (--max_items == 0) { - break; - } + + index++; } auto result = output.str();