Template Sensor - value_template syntax issue

Hi, I have an existing template sensor that calculates the net power use for my home, which works fine, but I’m trying to create a new template sensor, based on the working sensor, that returns only “on” or “off” depending on whether the net power is positive or negative, so that I can create a sensor graph that shows red or green whether I’m consuming or exporting power.

I’ve read the Templating documenation but my code keeps getting rejected by Home Assistant (invalid config), even with several variations on the code.

I’ve tried:

      net_power_state:
        friendly_name: "Power Generation State"
        value_template: >-
          {% if states('sensor.envoy_net_power') | float > 0 %}
            Off
          {% else %}
            On

I’ve also tried “if is_state”, “if state”, “if is_state_attr” and “if state_attr”. All with no joy. I’m missing something and I hope somone can point out where my syntax is wrong.
Thanks.

Put this in your binary sensor config (not sensor):

- platform: template
  sensors:
    net_power_state:
      friendly_name: "Power Generation State"
      value_template: "{{ states('sensor.envoy_net_power')|float > 0 }}"
2 Likes

Yeah the “if” is superfluous, you need the template to return true or false

1 Like

Thanks Tom, much appreciated. As I wanted it to evaluate to “true” when the value was negative I used “< 0” and now I have to wait till the sun is doing it’s thing tomorrrow to see how the new graph reads. Thanks also Mutt for further clarification.
Generation Status