So im trying to do a minor calculation with sensors. I have put static values 8 and 3 i run a similar python code and it returns 160 as it should. I’m trying to do the exact same thing but in a template, however it returns 0. Any ideas what could it be?
{% set battery_charge = 8 | int %}
{% set charging_speed = 3 | int %}
{% set charging_time = 0 | int %}
{% for i in range(0, battery_charge) -%}
{% if charging_speed > battery_charge %}
{% set charging_time = charging_time + ((battery_charge * 60) / charging_speed) | int %}
{% set battery_charge = 0 %}
{% endif %}
{% set battery_charge = battery_charge - charging_speed | int%}
{% set charging_time = charging_time + 60 | int %}
{%- endfor %}
{{ charging_time | int}}
Ah, you’re using a while loop. Now this is going to be a pain to implement in jinja. Jinja doesn’t allow while loops.
You should just use a python script instead. THis will create sensor.charging_time every time you run the script. You can create an auotmation to run it based on changes for each sensor change.
charge_time.py
Charging_Speed = data.get('charge_speed')
Battery_Size = data.get('battery_size')
if Charging_Speed is not None and Battery_Size is not None:
Battery_Charge = Battery_Size
Charging_Time = 0
while Battery_Charge > 0:
if(Charging_Speed > Battery_Charge):
Charging_Time += ((Battery_Charge * 60 )/ Charging_Speed)
Battery_Charge = 0
break
Battery_Charge = Battery_Charge - Charging_Speed
Charging_Time += 60
hass.states.set('sensor.charging_time', str(Charging_Time), {'friendly_name':'Charging Time'})
automation:
- trigger:
- platform: state
entity_id:
- sensor.battery_size
- sensor.charge_speed
action:
- service: python_script.charge_time
data:
charge_speed: "{{ states('sensor.charge_speed') | int }}"
battery_size: "{{ states('sensor.battery_size') | int }}"