I need to calculate current from the values that my inverter is providing
- sensor:
- name: "Tesla-HLE-3K Current"
unit_of_measurement: "A"
icon: mdi:current-ac
state: >
{% set voltage = states('sensor.tesla_hle_3k_voltage') | float(default=0) %}
{% set power = states('sensor.tesla_hle_3k_power') | float %}
{% set power_factor = states('sensor.tesla_hle_3k_power_factor') | float %}
{% set current_divisor = voltage * (power_factor / 100) %}
{% if (current_divisor != 0) %}
{{ (power / current_divisor) | abs | round(2, default=0) }}
{% else %} 'unavailable' {% endif %}
It works fine but I have few questions.
- For things like this, is using template the recommended way or does HA have another trick up it's sleeve
- Under certain conditions, the value cannot be calculated and therefore I return
unavailable. Is that the correct implementation? I sawavailabilityin the docs but I am confused. If the valueunavailableof a state of a sensor does the job, then why is the availability attribute needed? I thought that the state template would not be evaluated if the availability attribute returns False. Please excuse me if that is a dumb question. - I had to do the same calculation for a few other energy sensors. Replication bit me a few times so I started looking for a way to reuse. Looks like it's not straightforward in the templating world. I came across https://github.com/home-assistant/core/pull/42244#issuecomment-716042818. python_script does not support imports so I looked at the custom component method but the custom component does not appear to be designed for providing such functionality. Like the
iot_classmanifest attribute seems irrelevant for such a use case. I looked for an example but could not find a way.

