Template sensor: sum of turned on heating devices

Tags: #<Tag:0x00007fc3fd016b48>

Hi all,

I cannot find the answer on my problem:
I have some electric devices that are turned on if I have a lot of excess solar energy. I wish to have a “dummy sensor” that shows the total power of the turned on devices.

So for example: I have 2 heaters controlled each by a switch:

  • “switch.switch1” → turns on 800W heater
  • “switch.switch2” → turns on 1600W heater

I think the best option is to create a template sensor, but how to calculate the value?

sensor:
  - platform: template
    sensors:
      totalpower:
        friendly_name: Total power consumption
        unit_of_measurement: Watt
        value_template: >
          ???  (value = (800 when switch1 on) + (1600 when switch2 on))

The only solution I currently have is to build an if statement:

  • if(switch1 and not switch2) → 800W
  • if(switch2 and not switch1) → 1600W

This would problably work, but will become a extremelly long if statement when adding more and more electric devices.

Thx!

What about (800 if switch1 else 0)?

well, you didn’t list the entities that the power is coming from or the attribute, so you’ll have to fill in the blanks yourself. But there’s plenty of examples of this on the forums with ‘count all lights that are on’, etc. You’d just have to tailor it to pull from a map.

{%- set switches = {'switch.a':800,'switch.b':1600} %}
{%- set ns = namespace(sum=0) %}
{%- for s in expand(switches.keys() | list) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') %}
  {%- set ns.sum = ns.sum + switches[s] %}
{%- endfor %}
{{ ns.sum }}

You’ll still need to make the switches collection in the first line for each swithc, but the rest should remain the same.

1 Like

Thx Petro!

Looks perfect!

Here’s an alternative approach. Store the value as a custom attribute in the switch entity.

If you name the custom attribute power then the value of power for the first switch is 800 and 1600 for the second switch. Now the values becomes accessible to any template such as in a Template Sensor, automation, script, etc.

This calculates the total power of the switches that are currently on.

{{ expand('switch.switch', 'switch.switch2') | selectattr('state', 'eq', 'on')
    | map(attribute='attributes.power') | map('int') | sum }}

You can create custom attributes for an entity via the UI using Configuration > Customization.