I’m trying to make an automation that will take the target charge percentage (number.lux_ac_battery_charge_level) for my batteries and deduct current battery charge level (sensor.lux_battery ) to calculate the top up charge percentage required, and change an entity (input_number.battery_topup_level) to that value.
The script below gets the correct value of target charge as well as current charge, but it always return “0” as the topup charge required - ie: it has not updated the entity. What am I doing wrong?
alias: caluculate charge time required
description: >-
Set the battery charge level based on the predicted solar generation for the
next day.
trigger:
- platform: time
at: "22:00:00"
condition: []
action:
- service: number.set_value
data:
value: >-
{% set charge_target = ((states('number.lux_ac_battery_charge_level')) |
float) %} {% set current_charge = ((states('sensor.lux_battery'))|
float) %} {% set charge_topup = (charge_target - current_charge) %}
{{[charge_topup, 0] | max | round }}
target:
entity_id: input_number.battery_topup_level
- service: notify.notify
data:
message: >-
Charge target = {{ states("number.lux_ac_battery_charge_level") }}
Current charge = {{ states("sensor.lux_battery") }} Top up required =
{{ states("input_number.battery_topup_level") }}
mode: single
Obviously these numbers have changed since the last time I ran the automation, but they are what I would expect them to be. I note that the first one has a decimal point whereas the second one doesn’t?
Now paste the corrected template I posted previously and give us the output.
The decimal doesn’t matter. We’re casting to a float in both cases. Your other sensor value will just technically have an unnecessarily high precision, since it’s an int.
Because you’re calling the wrong service. Surely your log or the trace would’ve complained.
Change it to:
service: input_number.set_value
No. This only shows in the template editor, because it doesn’t understand YAML. The - in >- is the indicator to strip leading and trailing whitespace. Read up on YAML to know more.
Thanks, this has fixed it. No, traces didn’t flag that up. Thank you as well for pointing me to template editor. That will be a useful learning tool for me.