ESPHome  2025.2.0
modbus_textsensor.cpp
Go to the documentation of this file.
1 
2 #include "modbus_textsensor.h"
3 #include "esphome/core/log.h"
4 
5 namespace esphome {
6 namespace modbus_controller {
7 
8 static const char *const TAG = "modbus_controller.text_sensor";
9 
10 void ModbusTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Modbus Controller Text Sensor", this); }
11 
12 void ModbusTextSensor::parse_and_publish(const std::vector<uint8_t> &data) {
13  std::string output_str{};
14  uint8_t items_left = this->response_bytes;
15  uint8_t index = this->offset;
16  while ((items_left > 0) && index < data.size()) {
17  uint8_t b = data[index];
18  switch (this->encode_) {
20  output_str += str_snprintf("%02x", 2, b);
21  break;
22  case RawEncoding::COMMA:
23  output_str += str_sprintf(index != this->offset ? ",%d" : "%d", b);
24  break;
25  case RawEncoding::ANSI:
26  if (b < 0x20)
27  break;
28  // FALLTHROUGH
29  // Anything else no encoding
30  default:
31  output_str += (char) b;
32  break;
33  }
34  items_left--;
35  index++;
36  }
37 
38  // Is there a lambda registered
39  // call it with the pre converted value and the raw data array
40  if (this->transform_func_.has_value()) {
41  // the lambda can parse the response itself
42  auto val = (*this->transform_func_)(this, output_str, data);
43  if (val.has_value()) {
44  ESP_LOGV(TAG, "Value overwritten by lambda");
45  output_str = val.value();
46  }
47  }
48  this->publish_state(output_str);
49 }
50 
51 } // namespace modbus_controller
52 } // namespace esphome
mopeka_std_values val[4]
void publish_state(const std::string &state)
Definition: text_sensor.cpp:9
bool has_value() const
Definition: optional.h:87
std::string str_sprintf(const char *fmt,...)
Definition: helpers.cpp:324
void parse_and_publish(const std::vector< uint8_t > &data) override
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
optional< transform_func_t > transform_func_
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:310