ESPHome  2022.6.3
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 max_items = this->response_bytes;
17  uint8_t index = this->offset;
18  char buffer[4];
19  while ((max_items != 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 
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
void publish_state(const std::string &state)
Definition: text_sensor.cpp:12
bool has_value() const
Definition: optional.h:87
void parse_and_publish(const std::vector< uint8_t > &data) override
Definition: a4988.cpp:4
uint32_t val
Definition: datatypes.h:85
optional< transform_func_t > transform_func_