ESPHome  2024.10.2
modbus_textsensor.cpp
Go to the documentation of this file.
1 
2 #include "modbus_textsensor.h"
3 #include "esphome/core/log.h"
4 #include <iomanip>
5 #include <sstream>
6 
7 namespace esphome {
8 namespace modbus_controller {
9 
10 static const char *const TAG = "modbus_controller.text_sensor";
11 
12 void ModbusTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Modbus Controller Text Sensor", this); }
13 
14 void ModbusTextSensor::parse_and_publish(const std::vector<uint8_t> &data) {
15  std::ostringstream output;
16  uint8_t items_left = this->response_bytes;
17  uint8_t index = this->offset;
18  char buffer[5];
19  while ((items_left > 0) && index < data.size()) {
20  uint8_t b = data[index];
21  switch (this->encode_) {
23  sprintf(buffer, "%02x", b);
24  output << buffer;
25  break;
26  case RawEncoding::COMMA:
27  sprintf(buffer, index != this->offset ? ",%d" : "%d", b);
28  output << buffer;
29  break;
30  case RawEncoding::ANSI:
31  if (b < 0x20)
32  break;
33  // FALLTHROUGH
34  // Anything else no encoding
35  default:
36  output << (char) b;
37  break;
38  }
39  items_left--;
40  index++;
41  }
42 
43  auto result = output.str();
44  // Is there a lambda registered
45  // call it with the pre converted value and the raw data array
46  if (this->transform_func_.has_value()) {
47  // the lambda can parse the response itself
48  auto val = (*this->transform_func_)(this, result, data);
49  if (val.has_value()) {
50  ESP_LOGV(TAG, "Value overwritten by lambda");
51  result = val.value();
52  }
53  }
54  this->publish_state(result);
55 }
56 
57 } // namespace modbus_controller
58 } // 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
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_