ESPHome  2024.3.1
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[4];
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  // Anything else no encoding
31  case RawEncoding::NONE:
32  default:
33  output << (char) b;
34  break;
35  }
36  items_left--;
37  index++;
38  }
39 
40  auto result = output.str();
41  // Is there a lambda registered
42  // call it with the pre converted value and the raw data array
43  if (this->transform_func_.has_value()) {
44  // the lambda can parse the response itself
45  auto val = (*this->transform_func_)(this, result, data);
46  if (val.has_value()) {
47  ESP_LOGV(TAG, "Value overwritten by lambda");
48  result = val.value();
49  }
50  }
51  this->publish_state(result);
52 }
53 
54 } // namespace modbus_controller
55 } // 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
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
optional< transform_func_t > transform_func_