Calculations in an automation

Hi,

i’m trying to set a value based on a (simple) calculation.

I’m guessing it’s just a syntax issue.

What am I doing wrong? I’m trying to set number.ohme_target_percent to be equal to input_number.polestar_charge_limit - sensor.polestar_battery_charge_level

action: number.set_value
metadata: {}
data:
  value: input_number.polestar_charge_limit - sensor.polestar_battery_charge_level
target:
  entity_id: number.ohme_target_percent

Thaks
Paul

Hi Paul, you can simply test this in the Developer tools → TEMPLATE
Also, there is a helper that can do calculations. (no deductions…) :blush:

You need the following

action: number.set_value
metadata: {}
data:
  value: "{{ states('input_number.polestar_charge_limit') | float - states('sensor.polestar_battery_charge_level') | float }}"
target:
  entity_id: number.ohme_target_percent
1 Like

Thanks, that’s great. One more question. How do I make it set the value to 0 if the calculation fails and the answer is out of range?

What values would be wrong?
Negative or large positive numbers?

Yes the result has to be a positive number between 0 and 100. It’s a percentage charge to add to a car.

action: number.set_value
metadata: {}
data:
  value: "[{{ states('input_number.polestar_charge_limit') | float - states('sensor.polestar_battery_charge_level') | float , 0] | max }}"
target:
  entity_id: number.ohme_target_percent

Will make sure the value is 0 or more.
So probably this here will limit it to max 100:

action: number.set_value
metadata: {}
data:
  value: "[[{{ states('input_number.polestar_charge_limit') | float - states('sensor.polestar_battery_charge_level') | float , 0] | max, 100] | min }}"
target:
  entity_id: number.ohme_target_percent

But I have never tried this method

Thanks, will try to decipher that. I think the number.ohme_target_percent has a max of 100, so I really guess if I set it to 0 first, then if it fails it will stay at 0 if the calculation fails. How would I do that?

I don’t understand what you are saying