I’m struggling to code a template sensor to behave the way I’d like it to, and could use some help.
I have two sensors that I’m adding together. However, I want this to be conditional based on the state of an input number:
- sensor:
- name: "SoC at End of Charge"
unique_id: "soc_end_of_charge"
unit_of_measurement: 'kWh'
device_class: energy
state: "{{((states('sensor.soc_at_start_of_charge')| float(0) + states('sensor.soc_required_charge')| float(0))) | round(2) }}
{% set start = states('sensor.soc_at_start_of_charge') | float %}
{% set end = states('sensor.soc_at_end_of_charge') | float %}
{% set target = states('input_number.target_usable_soc') | float %}
{{ (start - (1.75)) if (start > target) }}"
I’d like to add ‘sensor.soc_at_start_of_charge’ to ‘sensor.soc_required_charge’ so long as ‘input_number.target_usable_soc’ is larger than ‘sensor.soc_at_start_of_charge’.
If ‘input_number.target_usable_soc’ is smaller than ‘sensor.soc_at_start_of_charge’ then I’d like to subtract a fixed number (1.75) from ‘sensor.soc_at_start_of_charge’.
Currently the Template editor is coming up with errors:
ValueError: Template error: float got invalid input ‘unavailable’ when rendering template … but no default was specified
If you can point me in the right direction here that would be awesome.
Only quote single line templates. Use this > for multi-line templates.
- sensor:
- name: "SoC at End of Charge"
unique_id: "soc_end_of_charge"
unit_of_measurement: 'kWh'
device_class: energy
state: >
{% if states('input_number.target_usable_soc')|float(0) > states('sensor.soc_at_start_of_charge')|float(0) %}
{{ states('sensor.soc_at_start_of_charge')|float(0) + states('sensor.soc_required_charge_min_zero_max_nine')|float(0)
{% else %}
{{ states('sensor.soc_at_start_of_charge')|float(0) - 1.75 }}
{% endif %}
availability: >
{{ states('sensor.soc_at_start_of_charge')|is_number and
states('sensor.soc_required_charge_min_zero_max_nine')is_number and
states('input_number.target_usable_soc')|is_number }}
Not you have not specified what you want to happen if input_number.target_usable_socequalssensor.soc_at_start_of_charge. In the above exmple the else case is perfomed (subtract 1.75).