If statement to define a template sensor - help please

Hi,
First off, I’m new to home assistant so I have probably made a stupid mistake, but any help would be gratefully received.

I want to define the value of a new sensor (“solar_auto_batt_charge_level”) based on another sensor (“solar_auto_batt_charge_temp”) using the following rules:

if “solar_auto_batt_charge_temp” is greater than 2000, then “solar_auto_batt_charge_level” = 2000
If 2000 > “solar_auto_batt_charge_temp” > -3000, the “solar_auto_batt_charge_level” = “solar_auto_batt_charge_temp”
If “solar_auto_batt_charge_temp” is less than than -3000, then “solar_auto_batt_charge_level” = -3000

I have added the following code into my sensor.yaml file which passes the config check, but “solar_auto_batt_charge_level” is reported as “unavailable” in home assistant. Note, “solar_auto_batt_charge_temp” is working correctly and reporting the appropriate values.

    solar_auto_batt_charge_level:
      friendly_name: Solar Auto Lux Batt charge Level
      unit_of_measurement: "W"
      device_class: power
      value_template: >
        {% set car_charge_temp = state('sensor.solar_auto_batt_charge_temp') | float(0) %}
        {% if car_charge_temp > 2000.0 %}
          2000.0
        {% elif 2000.0 > car_charge_temp > -3000.0 %}
          {{ (car_charge_temp) | float(0) }}
        {% elif car_charge_temp < -3000.0 %}
          -3000.0
        {% else %}
          0.0
        {% endif %}

Can anyone tell me what I have done wrong? Thanks in advance.

image

states

2 Likes

at a quick glance as i run out the door, state(xxx should be states(xxx and the float(0) i thought would be float(default=0.0) so if it has no value it will make it 0

in all my template sensors i just test the same thing each time instead of set, im not sure if there is a reduced subset in config.yaml…

also if you are using elif you dont need to do both the >= and < because it will exit the loop at the first true

float(0) is also an acceptable format for supplying a default.

The issue is just the state() / states() thing.

1 Like

All,
Thank you for solving this, I have been looking at this for ages and couldn’t see the wood for the trees… correcting state for states fixed the problem.