Help with power template

Hi, I am hoping for some help.

I have created a template to take readings from a sensor which ignores all positive value and when it goes negative I want to record the value and make it in to a positive number (this will be live power going back in to the grid)

How i have it now it responds unavailable, the input sensor is ok and reading fine

here is my template

  - platform: template
    sensors:
      solar_power_exported:
        friendly_name: "Solar Power Exported"
        unique_id: solar_power_exported
        unit_of_measurement: W
        value_template: >
          {% if (state('sensor.power_solar_difference') < 0) %}
            {{ abs(state('sensor.power_solar_difference') | float) }}  # Convert to float
          {% else %}
            0
          {% endif %}

I used AI to generate it as I wasn’t sure on where to start.

Thanks

Remove this:

# Convert to float

It’s being handled as a literal string and not a comment. As a result, the value isn’t a number and unit_of_measurement requires a number to report it in Watts.

Thanks

but I still get Unavailable

power-solar

  - platform: template
    sensors:
      solar_power_exported:
        friendly_name: "Solar Power Exported"
        unique_id: solar_power_exported
        unit_of_measurement: W
        value_template: >
          {% if (state('sensor.power_solar_difference') < 0) %}
            {{ abs(state('sensor.power_solar_difference') | float) }}
          {% else %}
            0
          {% endif %}

On closer inspection, I found more errors created by whatever AI tool you had used, such as calling the states() function state() and not supplying float() with a default value.

- platform: template
    sensors:
      solar_power_exported:
        friendly_name: "Solar Power Exported"
        unique_id: solar_power_exported
        unit_of_measurement: W
        value_template: >
          {% set psd = states('sensor.power_solar_difference') | float(0) %}
          {{ psd | abs if psd < 0 else 0 }}

Thank you so much, its working :smiley:

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. Only you, the author of this topic (or a moderator) can do that. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.