How to include standard C++ Header files in ESPHome yaml file

Hello,

because my ESP8266 ist battery powered, I managed to measure the battery voltage, so that I could be informed about emtpy battery for recharging. Using the analog input, I’m measuring the battery voltage. But on the user Interface I would like to see the percentage of battery level. Therefore I wrote the following code:

sensor:
  # Sensor for measuring battery voltage
  - platform: adc
    id: BatteryVoltMeasurement
    pin: A0
    name: "Battery Voltage"
    update_interval: 2s
    filters:
      # Factor for converting range 0.0-1.0 Volts into 3.01-4.15 Volts.
      - multiply: 4.554

text_sensor:
  - platform: template
    name: "Battery Level"
    id: template_text_battery_level
    update_interval: 2s
    lambda: !lambda |-
      float volt = id(BatteryVoltMeasurement).state;

      // the following lines convert the voltage level to percent range
      float moveToZero = -3.01;
      float skalingFactor = 87.43;
      float percent = (volt+moveToZero) * skalingFactor;
      if(percent < 0.0) {
        percent = 0.0;
      } else if (percent > 100.0) {
        percent = 100.0;
      }

      std::stringstream ss;
      ss << std::fixed << std::setprecision(0) << percent << "%";
      std::string s = ss.str();
      return {s};

As you can see, I’m using stringstream for converting a floating point value into a string value without any decimal places.

Now, my question is: How can I include C++ header files like inside of the yaml file?
I only found the following workaround:

I added a custom header file to the includes in my yaml file:

esphome:
  ...
  includes: std_includes.h

And the file std_includes.h contains:

#include <sstream>      // std::stringstream
#include <iostream>     // std::fixed
#include <iomanip>      // std::setprecision

But I believe there is a way doing that inside of the yaml file without the overhead of adding an extra include file.

3 Likes

That’s the only way I know to do it. But you also don’t need to. There’s a nice helper function you could use instead.
return str_sprintf("%.0f", percent);

1 Like